#include <7125.h>

char txb[100], rxb[100];

void InitSH (void) {
  SetSRReg (0);

  PFC.PECRL4.WORD = 0x0000;  
  PFC.PECRL3.WORD = 0x0000;  
  PFC.PECRL2.WORD = 0x0000;  
  PFC.PECRL1.WORD = 0x0000;  
  PFC.PEIORL.WORD = 0xFF33;  

  PFC.PACRL1.BIT.PA3MD = 1; // RXD1(PA3)
  PFC.PACRL2.BIT.PA4MD = 1; // TXD1(PA4)

  PE.DRL.BIT.B0 = 0; // LED Clear 
  PE.DRL.BIT.B1 = 1; // LED Clear

  STB.CR4.BIT._CMT    = 0;
  CMT0.CMCSR.BIT.CMIE = 0;
  CMT0.CMCSR.BIT.CKS = 1;
  CMT0.CMCSR.BIT.CMF = 0;
  CMT0.CMCNT = 0;
  CMT0.CMCOR = 782;

  SCI1_INIT (br115200, 1, txb, sizeof(txb), rxb, sizeof(rxb));
}

void wait (long num) {
  int i;

  CMT.CMSTR.BIT.STR0 = 1;
  for (i = 0; i < num; i++) {
    while (!CMT0.CMCSR.BIT.CMF) ;
    CMT0.CMCSR.BIT.CMF = 0;
  }
  CMT.CMSTR.BIT.STR0 = 0;
}

void main (void) {
  int i, j, k;

  InitSH ();

  i = j = k = 0;

  SCI1_PRINTF ("i = %d, j = %d, k = %d\n", i, j, k);

  while (1) {
    PE.DRL.BIT.B0 ^= 1;
    PE.DRL.BIT.B1 ^= 1;
    i++;
    SCI1_PRINTF ("Hello! %05d\n", i);
    wait (1000);
    while (SCI1_IN_DATA_CHECK() > 0) SCI1_OUT_DATA(SCI1_IN_DATA());
  }
}
