#include "sys.h"

void init() {
  square0->output_address = pdmout0;
  square0->high_val = 0xafff;
  square0->low_val = 0x0000;
  square0->flags = SQUARE_FLAG_ENABLE_msk;
  // will set the period later
}

int strlen(const char* str) {
  int i = 0;
  while(str[i] != '\0') {
    i++;
  }
  return i;
}

void log(const char* stuff) {
  uart_writen(uart0, stuff, strlen(stuff));
}

void dump(uint8_t a) {
  uint8_t hi = a >> 4;
  uint8_t lo = a & 0xf;

  const char* letters = "0123456789abcdef";

  uart_write(uart0, letters[hi]);
  uart_write(uart0, letters[lo]);
}

#define midi_uart uart1

#define MODE_IDLE 0
#define MODE_DOWN 1
#define MODE_UP 2

int main() {
  const int periods[] = {
    1493,
    0,
    1330,
    0,
    1185,
    1119,
    0,
    996,
    0,
    887,
    0,
    791,
  };

  init();

  led0->output = 42;

  int keydown = 0;
  int mode = MODE_IDLE;

  while(1) {
    uint8_t c = uart_read(midi_uart);

    if (c == 0xfe) {
      // nothing
    } else if (c == 0x90) {
      mode = MODE_DOWN;
    } else if (c == 0x80) {
      mode = MODE_UP;
    } else if ((c & 0x80) == 0) {
      if (mode == MODE_DOWN) {
        int period = 0;

        keydown = c;

        log("dn ");
        dump(c);
        log("\r\n");

        if (c > 0x3b) {
          if (c < 0x48) {
            period = periods[c - 0x3c];
          }
        }

        uart_read(midi_uart);

        square0->period = period;
      } else if (mode == MODE_UP) {
        log("up ");
        dump(c);
        log("\r\n");

        uart_read(midi_uart);

        if (keydown == c) {
          square0->period = 0;
        }
      }
    } else {
      log("weird: ");
      dump(c);
      log("\r\n");
    }
  }
}
