//** 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 "digplay.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;
	char far *slurp;
	SNDSTRUC snd;

	if ( LoadDigPak("SOUNDRV.COM") ) // Load DIGPAK file into memory.
	{
		if ( InitDigPak() ) // Init DIGPAK driver.
		{
			if ( LoadMidPak("MIDPAK.COM", "MIDPAK.ADV", "MIDPAK.AD" ) ) // Load MIDPAK into memory.
			{
				if ( InitMidPak() ) // Initialize MIDPAK driver.
				{
					song = fload("MIDPAK.XMI", &songlen); // Load song into memory.
					slurp = fload("SLURP.SND", &siz); // Load sound effect into memory.
					if ( song && slurp ) // if both sound and sound loaded.
					{
						RegisterXmidi(song,songlen); // register the song.
						PlaySequence(0); // play the song.
						snd.sound = slurp;
						snd.sndlen = siz;
						snd.frequency = 11000;
						MassageAudio(&snd); // massage the sound effect.
						DigPlay2(&snd); // play the sound effect.
						printf("Playing a song and a sound effect with MIDPAK and DIGPAK.\n");
						printf("Press a key to cause MIDPAK and DIGPAK to get de-initialized\n");
						printf("and re-initialized.\n");
						getch();

						DeInitMidPak();  // De-Init MIDPAK FIRST
						DeInitDigPak();  // Then De-Init DIGPAK
						printf("DigPak and MidPak de-initialized, doing system command.\n");
						system("dir");
						printf("press a key to re-initialize DIGPAK and MIDPAK\n");
						getch();

						InitDigPak(); // Init DIGPAK FIRST
						InitMidPak(); // The INIT MIDPAK

						RegisterXmidi(song,songlen);
						PlaySequence(0);
						DigPlay2(&snd);
						printf("Press a key to exit program.\n");
						getch();
					}
				}
			}
		}
	}

	DeInitMidPak();
	UnLoadMidPak();
	DeInitDigPak();
	UnLoadDigPak();
}

