#include <SPI.h>
#include <GD.h>
#include <PS2Keyboard.h>
#include "cmdflash.h"

#include "eforth.h"
#include "eforth-nuc.h"

const int DataPin = 4;
const int IRQpin =  3;

PS2Keyboard keyboard;

void setup()
{
  delay(1000);
  Serial.begin(115200);
  keyboard.begin(DataPin, IRQpin);

  GD.begin();
  GD.ascii();
  GD.copy(RAM_SPRIMG, nuc, sizeof(nuc));
  GD.fill(COMM, 0, 48);
  GD.wr16(COMM, NUC_ENTRY);
  GD.wr16(COMM+2, RAM_SPRIMG + sizeof(nuc));
  GD.microcode(eforth_code, sizeof(eforth_code));

  while (1) {
    if (GD.rd(COMM + 7)) {
      byte c = GD.rd(COMM + 6);
      Serial.write(c);
      GD.wr(COMM + 7, 0);
    }
    if (keyboard.available()) {
      GD.wr(COMM + 8, keyboard.read());
    }
  }
}

void loop() {
  if (keyboard.available()) {
    
    // read the next key
    char c = keyboard.read();
    
    // check for some of the special keys
    if (c == PS2_ENTER) {
      Serial.println();
    } else if (c == PS2_TAB) {
      Serial.print("[Tab]");
    } else if (c == PS2_ESC) {
      Serial.print("[ESC]");
    } else if (c == PS2_PAGEDOWN) {
      Serial.print("[PgDn]");
    } else if (c == PS2_PAGEUP) {
      Serial.print("[PgUp]");
    } else if (c == PS2_LEFTARROW) {
      Serial.print("[Left]");
    } else if (c == PS2_RIGHTARROW) {
      Serial.print("[Right]");
    } else if (c == PS2_UPARROW) {
      Serial.print("[Up]");
    } else if (c == PS2_DOWNARROW) {
      Serial.print("[Down]");
    } else if (c == PS2_DELETE) {
      Serial.print("[Del]");
    } else {
      
      // otherwise, just print all normal characters
      Serial.print(c);
    }
  }
}
