//** Demonstration program for the new MIDPAK and DIGPAK loading and
//** unloading system.	Uses LOADER.C.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <alloc.h>

#include "midpak.h"
#include "doscalls.h"
#include "loader.h"

// Define memory allocation functions.	If using DOS memory allocation
// functions, provided through DOSCALLS, then set the conditional compilation
// 'DOSALLOC' to true.  If using C compiler library function memory allocation
// set 'DOSALLOC' to zero.  MUST BE SET TO 1 for RECURSE, because most memory
// allocation has to be on a paragraph boundary!

#define DOSALLOC 0
// Redirect memory allocation to either DOS memory allocate functions located
// in DOSCALLS or to C library far memory allocation functions.
unsigned char far * far memalloc(long int siz)
{
	unsigned char far *mem;

	#if DOSALLOC
		mem = fmalloc(siz);  // DOS far memory allocation functions
	#else
		mem = farmalloc(siz); // C's far memory allocation functions.
	#endif
	return(mem);
}

void far memfree(char far *memory)
{
	#if DOSALLOC
		ffree(memory);
	#else
		farfree(memory);
	#endif
}


void main(int argc,char **argv)
{
	char far *song;
	long int siz,songlen;
	int xcon,keypress,sequence=0,SegueNumber=0;
	char str[80];

	if ( LoadMidPak("MIDPAK.COM", "MIDPAK.ADV", "MIDPAK.AD" ) ) // Load MIDPAK into memory.
	{
		if ( InitMidPak() ) // Initialize MIDPAK driver.
		{
			song = fload("TEST.XMI", &songlen); // Load song into memory.
			if ( song )
			{
				RegisterXmidi(song,songlen); // register the song.
				SetRelativeVolume(100,0) ;
				PlaySequence(0); // play the song.
				printf("Have begun to play the song...\n");
				printf("Press a key '0'-'4' to 'segue' to that sequence.\n");
				xcon = 0;
				do
				{
					sequence = ReportSequenceNumber(); // Find out current sequence number.
					if ( SequenceStatus() == SEQ_PLAYING )
						sprintf(str,"Playing sequence #%d",sequence);
					else
						sprintf(str,"Sequence #%d not playing.",sequence);
					tprint(0,0,40,str,BLUE BEHIND YELLOW);
					sprintf(str,"Next segue request #%d",SegueNumber);
					tprint(0,1,40,str,BLUE BEHIND YELLOW);
					if ( keystat() )
					{
						keypress = getkey();
						switch ( keypress )
						{
							case 27: xcon = 1;
							default:
								if ( keypress >= '0' && keypress <= '4' )
								{
									SegueNumber = keypress-'0';
									SegueSequence(SegueNumber,-1);
									if ( SequenceStatus() != SEQ_PLAYING )
									{
										PlaySequence(SegueNumber);
									}
								}
								break;
						}
					}
				} while (!xcon);
			}
		}
	}

	DeInitMidPak();
	UnLoadMidPak();
}
