#include <reg52.h>
#include "display.h"
#include "delay.h"


// DB	 P1
// CTL P3

sbit RS = P3 ^ 0;
sbit RW = P3 ^ 1;
sbit E = P3 ^ 2;
sbit CSA = P3 ^ 4;
sbit CSB = P3 ^ 5;

// 2 Screen 8 Page 64 Line
static unsigned char displayCache[2][8][64]={0};
static unsigned char sDisplayCache[32][16]={0};
static unsigned char lock=0;

void addDot(unsigned char x, unsigned char y)
{
	if(lock)
		return;
  displayCache[x / 64][y / 8][x % 64] += 1 << (y % 8);
}

void sAddDot(unsigned char x, unsigned char y)
{
	if(x>31|y>15|lock)
		return;
  addDot(2*x,2*y);
	addDot(2*x,2*y+1);
	addDot(2*x+1,2*y);
	addDot(2*x+1,2*y+1);
}
void cacheLock()
{
	lock=1;
}

void cacheUnlock()
{
	lock=0;
}

unsigned char checkLock()
{
	return lock;
}

void write()
{
  RW = 0;
  E = 0;
  E = 1;
  delay(2);
  E = 0;
}

void draw()
{
	
	unsigned int i, j;
	if(!lock)
		return;
	else
		lock=0;

  CSA = 1;
  CSB = 0;
  for(i = 0; i < 8; i++)
    {
      RS = 0;
      RW = 0;
      P1 = 0xb8 + i;
      write();
      P1 = 0X40;
      write();

      for(j = 0; j < 64; j++)
        {
          RS = 1;
          RW = 0;
          P1 = displayCache[0][i][j];
          write();
        }
    }
  CSA = 0;
  CSB = 1;
  for(i = 0; i < 8; i++)
    {
      RS = 0;
      RW = 0;
      P1 = 0xb8 + i;
      write();
      P1 = 0X40;
      write();

      for(j = 0; j < 64; j++)
        {
          RS = 1;
          RW = 0;
          P1 = displayCache[1][i][j];
          write();
        }
    }
}



void clear()
{
  unsigned int i, j;
  CSA = 1;
  CSB = 0;
  for(i = 0; i < 8; i++)
    {
      RS = 0;
      RW = 0;
      P1 = 0xb8 + i;
      write();
      P1 = 0X40;
      write();

      for(j = 0; j < 64; j++)
        {
          RS = 1;
          RW = 0;
          P1 = 0x00;;
          write();
        }
    }
  CSA = 0;
  CSB = 1;
  for(i = 0; i < 8; i++)
    {
      RS = 0;
      RW = 0;
      P1 = 0xb8 + i;
      write();
      P1 = 0X40;
      write();

      for(j = 0; j < 64; j++)
        {
          RS = 1;
          RW = 0;
          P1 = 0x00;
          write();
        }
    }
}

void init()
{
  E = 0;
  RS = 1;
  CSA = 1;
  CSB = 0;
  RS = 0;
  P1 = 0X3F;
  write();

  CSA = 0;
  CSB = 1;
  RS = 0;
  P1 = 0X3F;
  write();
}


void test()
{
	unsigned int i, j, k;
	for(i=0;i<2;i++)
		for(j=0;j<8;j++)
			for(k=0;k<64;k++)
			displayCache[i][j][k]=0x55;
	cacheLock();
	draw();
}


void writeData(unsigned char d)
{
  RS = 1;
  RW = 0;
  P1 = d;
}

void setCommand(unsigned char d)
{
  RS = 0;
  RW = 0;
  P1 = d;
}


void setPage(unsigned char p)
{
  setCommand(0xb8 + p);
}

void setLine(unsigned char p)
{
  setCommand(0xc0 + p);
}

void setY(unsigned char p)
{
  setCommand(0x40 + p);
}