#include "registers.h"

DataRegister::DataRegister(sc_module_name name, ofstream * file): sc_module(name)
{
	_secbus_debug(cout, TRACE, "BUILDING REGISTER ..."<<"\n");

	SC_METHOD(ps);
	sensitive << clk.pos();
	SC_METHOD(pc);
	sensitive << clk.neg();

	output = file;

	data_s = new sc_signal<int> [SIZE_256_IN_WORDS];

	_secbus_debug(cout, TRACE, "REGISTER BUILT"<<"\n");
}

void DataRegister::ps()
{
	if (!reset) 
	{
		address_s = 0xFFFFFFFF;
		be_s = 0;
		for(unsigned int i=0;i<SIZE_256_IN_WORDS;i++)
			data_s[i] = 0;
        return;
    }

	if (in.enable) 
	{	
		if (in.flush)
		{
			address_s	= 0xFFFFFFFF;
			be_s		= 0;
			for(unsigned int i=0;i<SIZE_256_IN_WORDS;i++)
				data_s[i]	= 0;
		}
		else
		{
			int data_v;
			//set data
			for (unsigned int j=0;j<SIZE_256_IN_WORDS;j++)
			{
				data_v	= data_s[j];

				for (unsigned int u=0;u<4;u++)
				{
					if ((((in.be.read()>>(j*4)) & 0xF) & (0x1<<u))!= 0)
						data_v	= (data_v & ~(0xFF<<(u*8))) | (in.data[j] & (0xFF<<(u*8)));
				}
				data_s[j]	= data_v;	
			}
			//set be
			be_s = be_s | in.be;
			//set address
			address_s = aligned(in.address, SIZE_256_IN_BYTES);
		}
	}
}

void DataRegister::pc()
{

	_secbus_debug(*output, DEBUG, dec<<"register address :"<<hex<<address_s<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register be :"<<hex<<be_s<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 0 :"<<hex<<data_s[0]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 1 :"<<hex<<data_s[1]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 2 :"<<hex<<data_s[2]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 3 :"<<hex<<data_s[3]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 4 :"<<hex<<data_s[4]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 5 :"<<hex<<data_s[5]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 6 :"<<hex<<data_s[6]<<"\n");
	_secbus_debug(*output, DEBUG, dec<<"register data 7 :"<<hex<<data_s[7]<<"\n");
	
	out.be			=  be_s;
	out.address		= address_s;
	for(unsigned int i=0;i<SIZE_256_IN_WORDS;i++)
		out.data[i] = data_s[i];
	
}
