#include "common-app.h"

static unsigned counter;

void
init (void)
{
  REGS->mailboxes.mboxout = 0;

  /* Enable scrubber */
  SUPERVISOR->scrub_cfg = HYDRA_SUPERVISOR_REGS_SCRUB_CFG_IRAM_EN
    | HYDRA_SUPERVISOR_REGS_SCRUB_CFG_DRAM_EN;

  counter = 0;
}

void
main (void)
{
  unsigned mbi = REGS->mailboxes.mboxin;  /* written by mgmt */
  unsigned mbo = REGS->mailboxes.mboxout; /* written by app */
  unsigned rwslot = (mbi >> 8) & 0xff; /* Remote slots (read from). */
  unsigned rrslot = mbo & 0xff;
  unsigned lwslot = (mbo >> 8) & 0xff; /* Local slots (write to).  */
  unsigned lrslot = mbi & 0xff;
  unsigned lnslot = (lwslot + 1) & 3;
  volatile uint32_t *src;
  volatile uint32_t *dst;

  /* Watchdog */
  SUPERVISOR->wd_key = WD_KEY;

  /* Something to read. */
  if (rrslot != rwslot) {
    src = &REGS->sh_mem[rrslot << 5];

    counter = src[1];
    mbo = (mbo + 0x01) & 0xffffff03;
  }

  if (lnslot != lrslot) {
    /* Free slot, send. */
    dst = &REGS->sh_mem[128 + (lwslot << 5)];

    dst[0] = 0x80;
    dst[1] = counter;

    counter++;

    mbo = (mbo + 0x100) & 0xffff03ff;
  }

  REGS->mailboxes.mboxout = mbo;
}
