#include <vo_stdio.h>
#include <stdlib.h>
#include <string.h>
#include <apploader.h> // Contains LoadLibrary() and DropLibrary()
#include <timers.h>
#include <aucommon.h>
#include <consolestate.h>
#include <audio.h>
#include <kernel.h>
#include <vo_gpio.h>

#define BUFSIZE 128

#define UI_DELAY (TICKS_PER_SEC/20)


#if 0
/* Map 8 LEDs to GPIO buttons, LED1 through LED8. */
u_int16 ledToGpio[8] = {
  0x0b, 0x0a, 0x09, 0x06, 0x05, 0x04, 0x0e, 0x0f
};
#else
/* Map 8 LEDs to GPIO buttons, left to right, top-down. */
u_int16 ledToGpio[8] = {
  0x05, 0x06, 0x04, 0x09, 0x0e, 0x0a, 0x0f, 0x0b
};
#endif

ioresult main(char *parameters) {
  static s_int16 myBuf[BUFSIZE];
  u_int32 lastUi = ReadTimeCount();
  int quit = 0;
  int untilOutput = 16;
  int verbose = 0, report = 0;
  s_int16 volume;

  printf("AmpBoard Demo\n");

  if (!stdaudioin || !stdaudioout) {
    printf("E: NO AUDIO IN OR OUT!\n");
    Delay(2*TICKS_PER_SEC);
    return EXIT_FAILURE;
  }

  GpioSetAsInput(0x00); /* S1 */
  GpioSetAsInput(0x01); /* S2 */
  GpioSetAsInput(0x02); /* S3 */
  GpioSetAsInput(0x03); /* S4 */

  volume = ioctl(stdaudioout, IOCTL_AUDIO_GET_VOLUME, NULL);
  if (volume < 0) {
    /* Device doesn't support reading volume */
    volume = -32768;
  } else {
    volume -= 256; /* Scale so that 0 = full volume, 20 = -10 dB, etc. */
  }

  while (!quit) {
    u_int32 newTimeCount = ReadTimeCount();
    if (appFlags & APP_FLAG_QUIT) {
      quit = 1;
    }

    if (ioctl(stdin, IOCTL_TEST, NULL) > 0) {
      int c = fgetc(stdin);
      switch (c) {
      case 'q':
	quit = 1;
	break;
      }
    }

    if (newTimeCount-lastUi >= UI_DELAY) {
      int i;
      if (volume != -32768) {
	int setVolume = 0;
	lastUi += UI_DELAY;
	if (GpioReadPin(0x02)) {
	  /* S3 */
	  if (volume > 0) { /* If less than full volume */
	    volume--;
	    setVolume = 1;
	  }
	}

	if (GpioReadPin(0x03)) {
	  /* S4 */
	  if (volume < 96) { /* Stop at -48 dB */
	    volume++;
	    setVolume = 1;
	  }
	}

	if (setVolume) {
	  ioctl(stdaudioout, IOCTL_AUDIO_SET_VOLUME, (void *)(volume+256));
	  printf("vol %2.1f dB\n", -0.5*volume);
	}
      }

      for (i=0; i<8; i++) {
	/* We make each led represent a 6 dB step */
	GpioSetPin(ledToGpio[i], (volume <= i*12));
      }
    }



    fread(myBuf, sizeof(s_int16), BUFSIZE, stdaudioin);
    if (untilOutput) {
      /* Wait for a while before outputting because the first samples
	 are going to be mostly noise if hardware has just been started. */
      untilOutput--;
    } else {
      fwrite(myBuf, sizeof(s_int16), BUFSIZE, stdaudioout);
    }
  } /* while (!quit) */

  return S_OK;
}
