//Target atmega168

#include <avr/io.h>
#include <avr/power.h>

#include "avrport.h"
#include "avrtime.h"
#include "avrtty.h"

#include "Test_common.h"
//#define BAUD_RATE 38400
//#define BAUD_RATE 19200

char x[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
void main (void) {
  const uint8_t port = 0;
  const uint32_t baudrate = 19200;

  uint8_t hex;
  uint8_t idata = 0;
  uint8_t odata = 0;
  char cc;

  const char str[] = "\r\nAhh, we are booting...\r\n";
  uint8_t wbuf[100];
  uint8_t rbuf[100];

  init();
  power_all_disable();

  time_init(0, TIME_CLKPS_64);
  tty_init(port, baudrate, wbuf, 100, rbuf, 100);

  (void) buf_chars(&ttydata[0].wr, str);

  while (1) {
    time_get();
    port_run();
    cc = tty_run(port, 1);

    GETHEX;
    if (hex != idata) {
      idata = hex;
      buf_putlast(&ttydata[port].wr, x[idata]);
    }

    if (cc && cc != odata) {
      odata = cc;
    }
    hex = odata;

    WRLED;
  }

}
