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

#include "pres.h"
#include "bgstripes.h"

static prog_uchar *pp;
int y = 0;
int sx = 200 << 4;
int sy = 200 << 4;
int sw = 4;
int sh = 0;

void setup()
{
  int i;
  for (i = 2; i < 7; i++) {
    pinMode(i, INPUT);
    digitalWrite(i, HIGH);
  }
  GD.begin();
  GD.microcode(bgstripes_code, sizeof(bgstripes_code));
  GD.copy(0x3e80, ramp, sizeof(ramp));
  GD.wr(COMM+0, 150);
  GD.ascii();
  pp = pres;
}

void copystr(int x, int y)
{
  int dst = x + (y << 6);
  byte c;
  while ((c = pgm_read_byte_near(pp++)) != 0)
    GD.wr(dst++, c);
}

void loop()
{
  switch (pgm_read_byte_near(pp++)) {
    case 'c':
      while (digitalRead(3) == 1) {
        sx += (analogRead(0) - 512) / 16;
        sy -= (analogRead(1) - 512) / 16;
        GD.waitvblank();
        int i;
        for (i = 0; i < (sw * sh); i++) {
          GD.sprite(i, (sx >> 4) + 16 * (i % sw), (sy >> 4) + 16 * (i / sw), i, 0, 0);
        }
      }
      GD.fill(RAM_PIC, ' ', 4096);
      int i;
      for (i = 0; i < 32; i++)
        GD.sprite(i, 400, 400, 0, 0, 0);
      sh = 0;
      delay(300);
      break;
    case 't':
      copystr(2, 3);
      y = 5;
      break;
    case 'l':
      copystr(4, y);
      y += 2;
      break;
    case 'i': {
      byte im = pgm_read_byte_near(pp++);
      prog_uchar *pal = (prog_uchar*)pgm_read_word_near(images + (2 * im));
      GD.copy(RAM_SPRPAL, pal, 64 * 2);
      prog_uchar *comp = (prog_uchar*)pgm_read_word_near(images + (2 * im) + 1);
      sw = pgm_read_byte_near(comp++);
      sh = pgm_read_byte_near(comp++);
      GD.uncompress(RAM_SPRIMG, comp);
      break;
    }
    case 'r':
      pp = pres;
  }
}
