/* For free support for VSIDE, please visit www.vsdsp-forum.com */

#include <vo_stdio.h>
#include <volink.h>     // Linker directives like DLLENTRY
#include <apploader.h>  // RunLibraryFunction etc
#include <consolestate.h>
#include <string.h>
#include <consolestate.h>
#include <kernel.h>
#include <vo_gpio.h>
#include <clockspeed.h>
#include <math.h>

int BlinkEyes(register u_int16 loops, u_int16 eyes) {
  int i;
  for (i=0; i<loops; i++) {
    int j;
    PERIP(GPIO0_ODATA) ^= eyes;
    for (j=0; j<i; j++) PERIP(0);
    PERIP(GPIO0_ODATA) ^= eyes;
    for (j=i; j<loops; j++) PERIP(0);
  }
  PERIP(GPIO0_ODATA) ^= eyes;
}

ioresult main(char *parameters) {
  int noMoreParams=0, nParam=0, printNewLine=1;
  int hasPrintedAnything=0;
  int wait=0;
  char *p = parameters;
  int i;
  int eyes = 0;
  u_int16 blinkLoops = SqrtI(clockSpeed.cpuClkHz/8);
  
  nParam = RunProgram("ParamSpl", parameters);

  GpioSetPin(0x05, 1);	/* SPI XCS */
  for (i=0; i<nParam; i++) {
    if (!strcmp(p, "-b")) {
      int delays[4] = {100, 700, 100, 0};
      int j;
      for (j=0; j<4; j++) {
	BlinkEyes(blinkLoops, (1<<6)|(1<<7));
	BlinkEyes(blinkLoops, (1<<6)|(1<<7));
	Delay(delays[j]);
      }
    } else if (!strcmp(p, "-l")) {
      GpioSetPin(0x06, 0);
    } else if (!strcmp(p, "+l")) {
      GpioSetPin(0x06, 1);
    } else if (!strcmp(p, "!l")) {
      GpioSetPin(0x06, !(PERIP(GPIO0_ODATA) & (1<<6)));
    } else if (!strcmp(p, "/l")) {
      BlinkEyes(blinkLoops, 1<<6);
    } else if (!strcmp(p, "-r")) {
      GpioSetPin(0x07, 0);
    } else if (!strcmp(p, "+r")) {
      GpioSetPin(0x07, 1);
    } else if (!strcmp(p, "!r")) {
      GpioSetPin(0x07, !(PERIP(GPIO0_ODATA) & (1<<7)));
    } else if (!strcmp(p, "/r")) {
      BlinkEyes(blinkLoops, 1<<7);
    } else if (!strcmp(p, "-h")) {
      printf("Usage: CatSEyes [-l|+l|-r|+r|-b|-h]\n"
	     "-l\tOpen left eye\n"
	     "+l\tClose left eye\n"
	     "!l\tToggle left eye\n"
	     "/r\tToggle left eye smoothly\n"
	     "-r\tOpen right eye\n"
	     "+r\tClose right eye\n"
	     "!r\tToggle right eye\n"
	     "/r\tToggle right eye smoothly\n"
	     "-b\tBlink eyes\n"
	     );
    } else {
      printf("E: Unknown parameter \"%s\"\n", p);
    }

    p += strlen(p)+1;
  }

  return S_OK;
}
