/*
      Direct MIDI Test
*/

/*                 */
/* Include headers */
/*                 */
#include <shinobi.h>
#include <sg_sd.h>
#include "..\share\sndutls.h"

/*                   */
/* Declare Prototype */
/*                   */
void UserVBlankIn( void );
void SoundInit( void );
void SoundMain( PDS_PERIPHERAL * );
void main( void );

/*                 */
/* Function Define */
/*                 */
void UserVBlankIn() {
  /* Call Sound Server */
  sdSysServer();
}

void SoundInit() {
  SDMIDI         midi_handle;
  SDS_MIDI_MES   midi;

  SoundInitialize( "MANATEE.DRV", "PIANO.MLT" );

  /* Send Initial Message */
  sdMidiOpenPort( &midi_handle );
  {
    /* Bank Change */
    sdMidiSetMes( midi_handle, &midi, SDD_MIDI_CTL_CHG, 32, 0 ); 
    sdMidiSendMes( midi_handle, &midi, 0 );
    /* Program Change */
    sdMidiSetMes( midi_handle, &midi, SDD_MIDI_PRG_CHG, 0 );
    sdMidiSendMes( midi_handle, &midi, 0 );
  }
  sdMidiClosePort( midi_handle );
}

void SoundMain( PDS_PERIPHERAL *pad ) {
  SDMIDI       midi_handle;
  SDS_MIDI_MES midi;
  GDFS         fd;
  Uint8        midi_ch = 0;
  static Uint8 n_on = 0;
  char *str[] = { "STOP", "PLAY" };

  if ( pad->press & PDD_DGT_ST ) {
    sdMidiOpenPort( &midi_handle );
    if ( n_on == 0 ) {
      /*Note ON */ 
      sdMidiSetMes( midi_handle, &midi, SDD_MIDI_NOTE_ON + midi_ch, 61, 127 );
      sdMidiSendMes( midi_handle, &midi, 2 );
      n_on = 1;
    } else {
      /*Note OFF */ 
      sdMidiSetMes( midi_handle, &midi, SDD_MIDI_NOTE_OFF + midi_ch, 61 );
      sdMidiSendMes( midi_handle, &midi, 0 );
      n_on = 0;
    }
    sdMidiClosePort( midi_handle );
  }
  njPrintC( NJM_LOCATION( 5, 8 ), "Play Status:" );
  njPrintC( NJM_LOCATION( 18, 8 ), str[ n_on ] );
}

void main(void)
{
  static Sint32  i = 0;
  PDS_PERIPHERAL *pad;

  /* Initialize System */
  njSetBorderColor( 0x00000000 );
#ifdef VGA
  sbInitSystem( NJD_RESOLUTION_VGA, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#else
  sbInitSystem( NJD_RESOLUTION_320x240_NTSCNI, NJD_FRAMEBUFFER_MODE_RGB565, 1 );
#endif

  njInitVertexBuffer( 20000, 0, 20000, 0, 0 );
  njInitPrint( NULL, 0, NJD_TEXFMT_ARGB_1555 );
  njSetBackColor( 0x00000000, 0x00000000, 0x000000FF );

  SoundInit();
  njSetVSyncFunction( UserVBlankIn );

  while ( 1 ) {
    pad = (PDS_PERIPHERAL *) pdGetPeripheral( PDD_PORT_A0 );
    njPrintC( NJM_LOCATION( 5, 4 ), "-- Send Direct MIDI Message Test --" );
    njPrintC( NJM_LOCATION( 5, 6 ), "Press START Button" );
    SoundLibVer( 5, 10 );
    SoundDrvVer( 5, 11 );
    SoundDrvStat( 5, 12 );

    SoundMain( pad );

    njWaitVSync();
  }
}

/******************************* end of file *******************************/
