#include <SPI.h>
#include <GD.h>
#include "debug.h"

void setup()
{
  int i;

  Serial.begin(1000000);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  digitalWrite(SS_PIN, HIGH);
  while (1) {
    // dump(0, 256);
    // Serial.println("");
    dump(J1_CODE, 256);
    Serial.println("");
    delay(4000);
  }

  GD.begin();
  
  GD.ascii();

#if 1
  GD.wr(0, 0x11);
  GD.wr(1, 0x22);
  GD.wr(2, 0x33);
  GD.wr(3, 0x44);
  GD.wr(4, 0x55);
  GD.wr(5, 0x66);
  GD.wr(6, 0x77);
  GD.wr(7, 0x88);
  GD.wr(8, 0x99);
  GD.wr(9, 0x00);
#else
  for (i = 0; i < 10; i++)
    GD.wr(i, 55);
#endif
}

#include "j1firmware/flowtest.h"
#include "j1firmware/memtest.h"
#include "j1firmware/helloworld.h"

static void snap()
{
  Serial.print("insn addr ");
  Serial.println(GD.rd16(0x2808), HEX);
  Serial.print("st0 ");
  Serial.println(GD.rd16(0x280a), HEX);
  Serial.print("st1 ");
  Serial.println(GD.rd16(0x280c), HEX);
}

void loop()
{
  GD.microcode(flowtest_code, sizeof(flowtest_code));

  for (;;) {
    dump(COMM, 16);
    GD.wr(COMM, 1);
  }
  return;

#if 0
  snap();
  for (;;) {
    for (i = 0; i < 1000; i++) {
      unsigned int loc = 32 + random(100);
      unsigned int v = random(65536);
      GD.wr16(loc, v);
      if (GD.rd16(loc) != v) {
        Serial.print("memory fail");
        for (;;) ;
      }
    }
    snap();
    dump(0, 64);
    Serial.print("");
    Serial.print("");
  }

  delay(10000);
#endif
}
