#include <stdint.h>
#include "fip_urv_regs.h"
#include "fip_urv_cmd.h"
#include "common.h"

#define OC_I2C_PRES_LO 0
#define OC_I2C_PRES_HI 1
#define OC_I2C_CTRL    2
#define OC_I2C_RXTX    3
#define OC_I2C_STAT    4
#define OC_I2C_CR      4
#define OC_I2C_CFG     5

static inline void
i2c_wait_tip (void)
{
  volatile struct fip_urv_regs *regs = REGS;
  while (regs->i2c[OC_I2C_STAT] & 2)
    ;
}


int
main (void)
{
  volatile struct fip_urv_regs *regs = REGS;

  SUPERVISOR->wd_key = WD_KEY;

#if 1
  regs->spi[5] = 0x20;
  regs->spi[4] = 0x428;
  regs->spi[1] = 0x15;
  regs->spi[6] = 1;
  regs->spi[4] = 0x528;
  while (regs->spi[4] & 0x100)
    SUPERVISOR->wd_key = WD_KEY;
  regs->spi[0];
  regs->spi[1];
  regs->spi[6] = 0;
#endif
#if 0
  unsigned char i2c_buf[64];

  /* Init i2c: prescaler (400khz / 4) */
  regs->i2c[OC_I2C_PRES_LO] = 25;
  regs->i2c[OC_I2C_PRES_HI] = 0;
  regs->i2c[OC_I2C_CTRL] = 0x80;  /* Enable */

            unsigned bl;
            unsigned off;

            regs->i2c[OC_I2C_RXTX] = (0x19 << 1) | 0;
            regs->i2c[OC_I2C_CR] = 0x90;  /* START + WRITE */
            i2c_wait_tip ();

            regs->i2c[OC_I2C_RXTX] = 0x9a;
            regs->i2c[OC_I2C_CR] = 0x10;  /* WRITE */
            i2c_wait_tip ();

            regs->i2c[OC_I2C_RXTX] = (0x19 << 1) | 1;
            regs->i2c[OC_I2C_CR] = 0x90;  /* START + READ */
            i2c_wait_tip ();

            bl = 0;
            if (bl == 0) {
              /* Block transfer.  */
              regs->i2c[OC_I2C_CR] = 0x20;  /* READ */
              i2c_wait_tip ();
              bl = regs->i2c[OC_I2C_RXTX];
            }
            off = 0;
            bl--;
            for (off = 0; off <= bl; off++) {
              regs->i2c[OC_I2C_CR] = 0x20 | (off == bl ? 0x08 : 0);
              i2c_wait_tip ();
              i2c_buf[off] = regs->i2c[OC_I2C_RXTX];
            }
#endif
            while (1) ;
}
