#include "archinc.h"
#include "cli.h"
#include "strutil.h"
#include "zarlink.h"

#ifdef CONFIG_INCLUDE_ZARLINK

#include <stdlib.h>

static void ssiDelay(void)
{
  volatile int i;
  unsigned long dummy;

//   for(i=0;i<8;i++) 
    dummy = CTIME0;
}

/*
 * Include the proper hardware-dependent low-level routines 
 */

#ifdef CONFIG_BOARD_MEDUSA
#  include "zl_bus_rev1.c"
#else
#  ifdef CONFIG_BOARD_MEDUSA_REV2
#    include "zl_bus_rev2.c"
#  else
#    error "zl_bus: hardware not defined!
#  endif /* CONFIG_BOARD_MEDUSA_REV2 */
#endif /* CONFIG_BOARD_MEDUSA */

/*
 * The rest of this file is hardware independent
 */

void zarlinkIndexedWrite(unsigned short writeIndex, unsigned char writeData)
{
  busWrite(0x00, (unsigned char)(writeIndex & 0x00ff));
  busWrite(0x01, (unsigned char)((writeIndex >> 8) & 0x00ff));
  busWrite(0x02, writeData);
  return;
}

unsigned char zarlinkIndexedRead(unsigned short readIndex)
{
  busWrite(0x00, (unsigned char)(readIndex & 0x00ff));
  busWrite(0x01, (unsigned char)((readIndex >> 8) & 0x00ff));
  return busRead(0x02);
}

void zarlinkCommandWrite(unsigned char cmdData)
{
  busWrite(0x04, cmdData);
}

unsigned char zarlinkStatusRead(void)
{
  return busRead(0x04);
}

void zarlinkFrameWrite8(unsigned char frameData8)
{
  busWrite(0x03, frameData8);
}


void zarlinkFrameWrite(unsigned short frameData16)
{
#if 0
  // big endian
  busWrite(0x03, ((frameData16 >> 8) & 0xff));
  busWrite(0x03, ( frameData16       & 0xff));
#else
  // little endian
  busWrite(0x03, ( frameData16       & 0xff));
  busWrite(0x03, ((frameData16 >> 8) & 0xff));
#endif

}

unsigned char zarlinkFrameRead8(void)
{
  return (busRead(0x03));
}

unsigned short zarlinkFrameRead(void)
{
  union {
    unsigned short u16;
    unsigned char u8[2];
    } u;

#if 0
  // big endian
  u.u8[1] = busRead(0x03);
  u.u8[0] = busRead(0x03);
#else
  // little endian
  u.u8[0] = busRead(0x03);
  u.u8[1] = busRead(0x03);
#endif
  return u.u16;
}

void zarlinkCtrlBuffer1Write(unsigned short ctrlData16)
{
#if 0
  // big endian
  busWrite(0x06, ((ctrlData16 >> 8) & 0xff));
  busWrite(0x06, ( ctrlData16       & 0xff));
#else
  // little endian
  busWrite(0x06, ( ctrlData16       & 0xff));
  busWrite(0x06, ((ctrlData16 >> 8) & 0xff));
#endif
}

unsigned short zarlinkCtrlBuffer1Read(void)
{
  union {
    unsigned short u16;
    unsigned char u8[2];
    } u;

#if 0
  u.u8[1] = busRead(0x06);
  u.u8[0] = busRead(0x06);
#else
  u.u8[0] = busRead(0x06);
  u.u8[1] = busRead(0x06);
#endif

  return u.u16;
}

unsigned short zarlinkCtrlBuffer2Read(void)
{
  union {
    unsigned short u16;
    unsigned char u8[2];
    } u;

#if 0
  u.u8[1] = busRead(0x07);
  u.u8[0] = busRead(0x07);
#else
  u.u8[0] = busRead(0x07);
  u.u8[1] = busRead(0x07);
#endif
  
  return u.u16;
}

void zarlinkInterruptWrite(unsigned char intData)
{
  busWrite(0x05, (intData & 0x07));
}

unsigned char zarlinkInterruptRead(void)
{
  return busRead(0x05);
}

#endif /* CONFIG_INCLUDE_ZARLINK */

