//
//   Copyright (C) 2007 by sinamas <sinamas at users.sourceforge.net>
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 2 as
//   published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License version 2 for more details.
//
//   You should have received a copy of the GNU General Public License
//   version 2 along with this program; if not, write to the
//   Free Software Foundation, Inc.,
//   51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
//

#ifndef SOUND_CHANNEL3_H
#define SOUND_CHANNEL3_H

#include <stdint.h>

#include "length_counter.h"
#include "master_disabler.h"

namespace gambatte {

struct SaveState;

class Channel3 {
public:
	Channel3();
	bool isActive() const;
	bool isCgb() const;
	void reset();
	void resetCc(unsigned long, unsigned long);
	void init(bool);
	void setStatePtrs(SaveState&);
	void saveState(SaveState&) const;
	void loadState(SaveState const&);
	void setNr0(unsigned);
	void setNr1(unsigned, unsigned long);
	void setNr2(unsigned);
	void setNr3(unsigned);
	void setNr4(unsigned, unsigned long);
	void setSo(unsigned long);
	void update(uint_least32_t*, unsigned long, unsigned long, unsigned long);
	unsigned waveRamRead(unsigned, unsigned long) const;
	void waveRamWrite(unsigned, unsigned, unsigned long);

private:
	class Ch3MasterDisabler : public MasterDisabler {
	public:
		Ch3MasterDisabler(bool &m, unsigned long &wC) : MasterDisabler(m), waveCounter_(wC) {}
		virtual void operator()();

	private:
		unsigned long &waveCounter_;
	};

	unsigned char waveRam_[0x10];
	Ch3MasterDisabler disableMaster_;
	LengthCounter lengthCounter_;
	unsigned long soMask_;
	unsigned long prevOut_;
	unsigned long waveCounter_;
	unsigned long lastReadTime_;
	unsigned char nr0_;
	unsigned char nr3_;
	unsigned char nr4_;
	unsigned char wavePos_;
	unsigned char rshift_;
	unsigned char sampleBuf_;
	bool master_;
	bool cgb_;

	void updateWaveCounter(unsigned long);
};

}

#endif
