//
//   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 DUTY_UNIT_H
#define DUTY_UNIT_H

#include "sound_unit.h"
#include "master_disabler.h"
#include "../savestate.h"

namespace gambatte {

class DutyUnit : public SoundUnit {
public:
	DutyUnit();
	virtual void event();
	virtual void resetCounters(unsigned long);
	bool isHighState() const;
	void nr1Change(unsigned, unsigned long);
	void nr3Change(unsigned, unsigned long);
	void nr4Change(unsigned, unsigned long, unsigned long);
	void reset();
	void resetCc(unsigned long, unsigned long);
	void saveState(SaveState::SPU::Duty&, unsigned long);
	void loadState(SaveState::SPU::Duty const&, unsigned, unsigned, unsigned long);
	void killCounter();
	void reviveCounter(unsigned long);
	unsigned freq() const;
	void setFreq(unsigned, unsigned long);

private:
	unsigned long nextPosUpdate_;
	unsigned short period_;
	unsigned char pos_;
	unsigned char duty_;
	unsigned char inc_;
	bool high_;
	bool enableEvents_;

	void setCounter();
	void setDuty(unsigned);
	void updatePos(unsigned long);
};

class DutyMasterDisabler : public MasterDisabler {
public:
	DutyMasterDisabler(bool &m, DutyUnit &dutyUnit) : MasterDisabler(m), dutyUnit_(dutyUnit) {}
	virtual void operator()();

private:
	DutyUnit &dutyUnit_;
};

}

#endif
