#include <asm/sv_addr_ag.h>

#define byte   unsigned char
#define uword  unsigned short
#define udword unsigned int
#define dword  signed int

#define SERIAL_CTRL_W \
     ((IO_STATE(R_SERIAL0_CTRL, tr_baud,       c9600Hz) |\
       IO_STATE(R_SERIAL0_CTRL, rec_baud,      c9600Hz) |\
       IO_STATE(R_SERIAL0_CTRL, dma_err,       stop)     |\
       IO_STATE(R_SERIAL0_CTRL, rec_enable,    disable)   |\
       IO_STATE(R_SERIAL0_CTRL, rts_,          active)   |\
       IO_STATE(R_SERIAL0_CTRL, sampling,      middle)   |\
       IO_STATE(R_SERIAL0_CTRL, rec_stick_par, normal)   |\
       IO_STATE(R_SERIAL0_CTRL, rec_par,       even)     |\
       IO_STATE(R_SERIAL0_CTRL, rec_par_en,    disable)  |\
       IO_STATE(R_SERIAL0_CTRL, rec_bitnr,     rec_8bit)) >> 16)

#define SERIAL_CTRL_B \
     ((IO_FIELD(R_SERIAL0_CTRL, txd, 0)                  |\
       IO_STATE(R_SERIAL0_CTRL, tr_enable,     enable)   |\
       IO_STATE(R_SERIAL0_CTRL, auto_cts,      disabled) |\
       IO_STATE(R_SERIAL0_CTRL, stop_bits,     one_bit)  |\
       IO_STATE(R_SERIAL0_CTRL, tr_stick_par,  normal)   |\
       IO_STATE(R_SERIAL0_CTRL, tr_par,        even)     |\
       IO_STATE(R_SERIAL0_CTRL, tr_par_en,     disable)  |\
       IO_STATE(R_SERIAL0_CTRL, tr_bitnr,      tr_8bit)) >> 8)


void ser_init ()
{
  *R_SERIAL0_XOFF = 0;
  *(unsigned short*)R_SERIAL0_REC_CTRL = SERIAL_CTRL_W;
  *R_SERIAL0_TR_CTRL = SERIAL_CTRL_B;
}


void
ser_putch (unsigned char ch)
{
  while (1)
  {
    if (((*R_SERIAL0_READ) & IO_MASK(R_SERIAL0_READ, tr_ready)) ==
         IO_STATE(R_SERIAL0_READ, tr_ready, ready))
    {
      *R_SERIAL0_TR_DATA = ch;
      return;
    }
  }
}

ser_put_dword (unsigned int number)
{

  int i;

  unsigned char nybble;
  
  for (i=7; i >= 0 ; i--) {
    nybble = (number >> (i*4)) & 0xf;
    if(nybble > 9)
    {
      nybble += 7;
    }

    ser_putch(nybble + '0');
  }

}


void 
ser_put_str (unsigned char *str)
{
  int i;

  for (i=0; str[i]; i++) 
  {
    ser_putch(str[i]);
  }

}
