#include "ROMWireProtocol.h"

//#include <Arduino.h>

void setCtrlPins() {
  pinMode(OE, OUTPUT);
  pinMode(PGM, OUTPUT);
}

void setAddrPinsOut() {
  for(int a = Addr0; a <= Addr18; a++) {
    pinMode(a, OUTPUT);
    digitalWrite(a, LOW);
  }
}

void setDataPinsOut() {
  if(dataMode == MODE_OUTPUT) { return; }
  for(int d = Data0; d <= Data7; d++) {
    pinMode(d, OUTPUT);
    digitalWrite(d, LOW);
  }
  dataMode = MODE_OUTPUT;
}

void setDataPinsIn() {
  if(dataMode == MODE_INPUT) { return; }
  for(int d = Data0; d <= Data7; d++) {
    digitalWrite(d, LOW);
    pinMode(d, INPUT);
  }
  dataMode = MODE_INPUT;
}

void setByte(byte out) {
  for(int i = 0; i < 8; i++) {
    digitalWrite(Data0 + i, bitRead(out,i));
  }
}

void setAddress(unsigned long addr) {
  for(int i = 0; i < 19; i++) {
    digitalWrite(Addr0 + i, bitRead(addr, i) );
  }
}

byte readByte() {
  byte temp_in = 0;
  for(int i = 0; i < 8; i++) {
    if(digitalRead(Data0 + i)) {
      bitSet(temp_in, i);
    }
  }

  return temp_in;
}

byte readData(unsigned long address) {
  byte temp_read;
  //setByte(0);
  //setDataPinsIn();

  digitalWrite(PGM, HIGH);
  digitalWrite(OE, HIGH);

  setAddress(address);
  delayMicroseconds(3);

  digitalWrite(OE, LOW);
  delayMicroseconds(3);

  temp_read = readByte();

  return temp_read;
}

void writeByte(byte data, unsigned long address) {
  setAddress(address);
  setByte(data);

  digitalWrite(OE, HIGH);
  digitalWrite(PGM, HIGH);

  delayMicroseconds(10);

  digitalWrite(PGM, LOW);
  delayMicroseconds(3);
  digitalWrite(PGM, HIGH);
}

void programData(byte data, unsigned long address) {
  setDataPinsOut();

  writeByte(0xAA, 0x5555);
  writeByte(0x55, 0x2AAA);
  writeByte(0xA0, 0x5555);
  writeByte(data, address);

  delayMicroseconds(30);

  //Serial.println(data, HEX);
  //Serial.println(address, HEX);
}