#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include "midas.h"



#define MIDPVERSION 0.1.0
#define MIDPVERSTR "0.1.0"

gmpModule       *module;                /* current playing module */
gmpInformation  *info;                  /* current module playing info */
int             callMP;


char            *title =
"MIDAS Module Player for Linux, version " MIDPVERSTR "\n"
"Copyright 1996 Petteri Kangaslampi & Jarno Paananen\n";


char            *usage =
"Usage:\tMIDP\t[options] <filename> [options]\n"\
"Options:\n"\
"\t-?, -h\t This information\n"\
"\t-mx\tMixing rate x Hz\n"\
"\t-ox\tOutput mode (8=8-bit, 1=16-bit, s=stereo, m=mono\n"\
"\n";


static int mode, rate;

void PollMIDAS(void)
{
    int         error;

    while(1)
    {
        if ( (error = midasSD->StartPlay()) != OK )
            midasError(error);
        do
        {
            if ( (error = midasSD->Play(&callMP)) != OK )
                midasError(error);
            if ( callMP )
            {
                if ( (error = gmpPlay()) != OK )
                    midasError(error);
            }
        } while( callMP );
	usleep(100);
    }
}


int main(int argc, char *argv[])
{
    int                error;
    static fileHandle  f;
    static uchar       buf[48];
    int                i,j;
    gmpInstrument      *inst;
    char               *fileName = NULL;

    setbuf(stdout, NULL);
    setbuf(stdin, NULL);

    puts(title);

    midasSetDefaults();

    if ( argc < 2 )
    {
        puts(usage);
        exit(EXIT_SUCCESS);
    }

    midasSetDefaults();
//    midasConfig();

/* These settings control the default output mode, useful for GUS people at least */
//    midasOutputMode |= sd8bit;
//    midasOutputMode |= sdMono;
//    midasOutputMode &= ~sdStereo;

    for ( i = 1 ; i < argc; i++ )
    {
        if ( argv[i][0] == '-' )
	{
	    switch ( argv[i][1] )
	    {
	        case 'm':
		    sscanf(&argv[i][2], "%d", &midasMixRate );
		    break;

	        case 'o':
		    for ( j = 2; j < 4; j++ )
		    {
		        switch ( argv[i][j] )
			{
			    case '1':
			        midasOutputMode &= ~sd8bit;
				midasOutputMode |= sd16bit;
			        break;
			    case '8':
			        midasOutputMode &= ~sd16bit;
				midasOutputMode |= sd8bit;
			        break;
			    case 's':
			        midasOutputMode &= ~sdMono;
				midasOutputMode |= sdStereo;
			        break;
			    case 'm':
			        midasOutputMode &= ~sdStereo;
				midasOutputMode |= sdMono;
			        break;
                        }
		    }
		    break;

	        default:
		    fileName = argv[i];  // :)

	    }
	}
	else
	    fileName = argv[i];

    }

    if ( fileName == NULL )
    {
        puts("No filename given!\n");
	return 1;
    }

    midasInit();

    /* Read first 48 bytes of module: */
    if ( (error = fileOpen(fileName, fileOpenRead, &f)) != OK )
        midasError(error);
    if ( (error = fileRead(f, buf, 48)) != OK )
        midasError(error);
    if ( (error = fileClose(f)) != OK )
        midasError(error);

    if ( mMemEqual(buf, "Extended Module:", 16) )
    {
        puts("Loading Fasttracker 2 module");
        if ( (error = gmpLoadXM(fileName, 1, NULL, &module)) != OK )
            midasError(error);
    }
    else
    {
        if ( mMemEqual(buf+44, "SCRM", 4) )
        {
            puts("Loading Screamtracker 3 module");
            if ( (error = gmpLoadS3M(fileName, 1, NULL, &module)) != OK )
                midasError(error);
        }
        else
        {
            puts("Loading Protracker module");
                if ( (error = gmpLoadMOD(fileName, 1, NULL, &module)) != OK )
                    midasError(error);
        }
    }

    printf("Module: %s\n", module->name);

    for ( i = 0; i < module->numInsts; i++ )
    {
      inst = module->instruments[i];
      if ( i & 1 )
      {
	  printf("%i: %s\n", i+1, inst->name);
      }
      else
      {
	  sprintf(buf, "%i: %s", i+1, inst->name);
	  j = ((40 - strlen(buf))+7)/8;
	  printf("%s", buf);
	  while (j--)
	    printf("\t");
      }
    }
    printf("\n");
    midasPlayModule(module, 0);

    midasSD->GetMixRate(&rate);
    printf("Playing at %d Hz", rate);
    
    midasSD->GetMode(&mode);
    if ( mode & sd8bit )
        printf(" 8-bit");
    else
        printf(" 16-bit");

    if ( mode & sdMono )
        printf(" mono\n");
    else
        printf(" stereo\n");


    PollMIDAS();

/* actually, we never get here (yet) */

    printf("\n");
    midasStopModule(module);
    if ( (error = gmpFreeModule(module)) != OK )
        midasError(error);
    midasClose();
    errPrintList();

    return 0;
}
