#include "LCDI2C4Bit.h"
#include <Wire.h>

extern "C" {
  #include <stdio.h>  //not needed yet
  #include <string.h> //needed for strlen()
  #include <inttypes.h>
  #include "WConstants.h"  //all things wiring / arduino
}

//command bytes for LCD
#define CMD_CLR 0x01
#define CMD_RIGHT 0x1C
#define CMD_LEFT 0x18
#define CMD_HOME 0x02

//stuff the library user might call---------------------------------

//constructor.  num_lines must be 1 or 2, currently.

byte dataPlusMask = 0; // TODO!!!

LCDI2C4Bit::LCDI2C4Bit( int devI2CAddress, int num_lines, int lcdwidth) {
  myNumLines = num_lines;
  myWidth = lcdwidth;
  myAddress = devI2CAddress;
}

void SetMCPReg( byte deviceAddr, byte reg, byte val ) {
  Wire.beginTransmission(deviceAddr);
  Wire.send(reg);
  Wire.send(val);
  Wire.endTransmission();
}

void SendToLCD( byte deviceAddr, byte data ) {
  data |= dataPlusMask;
  SetMCPReg(deviceAddr,0x0A,data);
  data ^= 0x80; // E
  delayMicroseconds(1);
  SetMCPReg(deviceAddr,0x0A,data);
  data ^= 0x80; // E
  delayMicroseconds(1);
  SetMCPReg(deviceAddr,0x0A,data);
  delay(1);

}

void WriteLCDByte( byte deviceAddr, byte bdata ) {
  SendToLCD(deviceAddr,bdata >> 4);
  SendToLCD(deviceAddr,bdata & 0x0F);
}

void LCDI2C4Bit::init( void ) {
  dataPlusMask = 0; // initial: 0
  SetMCPReg(myAddress,0x05,0x0C); // set CONFREG (0x05) to 0
  SetMCPReg(myAddress,0x00,0x00); // set IOREG (0x00) to 0
  //
  delay(50);
  SendToLCD(myAddress,0x03); 
  delay(5);
  SendToLCD(myAddress,0x03);
  delayMicroseconds(100);
  SendToLCD(myAddress,0x03);
  delay(5);
  SendToLCD(myAddress,0x02);
  WriteLCDByte(myAddress,0x28);
  WriteLCDByte(myAddress,0x08);
  WriteLCDByte(myAddress,0x0C); // turn on, cursor off, no blinking
  delayMicroseconds(60);
  WriteLCDByte(myAddress,0x01); // clear display
  delay(3);  
}

void LCDI2C4Bit::backLight( bool turnOn ) {
  dataPlusMask |= 0x40; // Lights mask
  if (!turnOn) dataPlusMask ^= 0x40;
  SetMCPReg(myAddress,0x0A,dataPlusMask);  
}


void LCDI2C4Bit::print( int value ) {
  dataPlusMask |= 0x10; // RS
  WriteLCDByte(myAddress,(byte)value);
  dataPlusMask ^= 0x10; // RS
}

void LCDI2C4Bit::printIn( char value[] ) {
  for ( char *p = value; *p != 0; p++ ) 
    print(*p);
}

void LCDI2C4Bit::clear() {
  commandWrite(CMD_CLR);
}

void LCDI2C4Bit::cursorTo(int line_num, int x) {
  commandWrite(CMD_HOME);
  int targetPos = x + line_num * myWidth;
  for ( int i = 0; i < targetPos; i++)
    commandWrite(0x14);
}

void LCDI2C4Bit::commandWrite( int command ) {
  // RS - leave low
  WriteLCDByte(myAddress,command);
  delay(1);
}
