#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <dos.h>
#include "types.h"
#include "develop.h"
#include "scriplib.h"
#include "file_lib.h"
#include "gamedefs.h"
#include "keyboard.h"
#include "util_lib.h"
#include "function.h"
#include "control.h"
#include "fx_man.h"
#include "sounds.h"
#include "config.h"
#include "sndcards.h"

// we load this in to get default button and key assignments
// as well as setting up function mappings

#include "function.c"

//
// Sound variables
//
int32 FXDevice;
int32 MusicDevice;
int32 FXVolume;
int32 MusicVolume;
fx_blaster_config BlasterConfig;
int32 NumVoices;
int32 NumChannels;
int32 NumBits;
int32 MixRate;
int32 MidiPort;
int32 ReverseStereo;

int32 ControllerType;

//
// Screen variables
//

int32 ScreenMode;
int32 ScreenWidth;
int32 ScreenHeight;

static char setupfilename[128]={SETUPFILENAME};
static boolean setupread = false;
static int32 scripthandle;

/*
===================
=
= CONFIG_GetSetupFilename
=
===================
*/
#define MAXSETUPFILES 20
void CONFIG_GetSetupFilename( void )
   {
   struct find_t fblock;
   char extension[10];
   char * src;
   char * filenames[MAXSETUPFILES];
   int32 numfiles;
   int32 i;

   strcpy(setupfilename,SETUPFILENAME);

   // determine extension

   src = setupfilename + strlen(setupfilename) - 1;

   while (*src != '.')
      {
      src--;
      }
   strcpy (&extension[1],src);
   extension[0] = '*';

   numfiles=0;
   if (_dos_findfirst(extension,0,&fblock)==0)
      {
      do
         {
         filenames[numfiles]=SafeMalloc(128);
         strcpy(filenames[numfiles],fblock.name);
         numfiles++;
         if (numfiles == MAXSETUPFILES)
            break;
         }
      while(!_dos_findnext(&fblock));
      }
   i = CheckParm (SETUPNAMEPARM);
   if (i!=0)
      {
      numfiles = 0;
      strcpy(setupfilename,_argv[i+1]);
      }
   if (numfiles>1)
      {
      int32 time;
      int32 oldtime;
      int32 count;

      printf("\nMultiple Configuration Files Encountered\n");
      printf("========================================\n\n");
      printf("Please choose a configuration file from\n");
      printf("the following list by pressing it's\n");
      printf("corresponding letter:\n\n");
      printf("The default file will be used if no selection\n");
      printf("is made within 10 seconds.\n\n");
      for (i=0;i<numfiles;i++)
         {
         if (strcmpi(filenames[i],SETUPFILENAME))
            printf("%c. %s\n",'a'+i,filenames[i]);
         else
            printf("%c. %s <DEFAULT>\n",'a'+i,filenames[i]);
         }
      printf("\n");
      KB_FlushKeyboardQueue();
      KB_ClearKeysDown();
      count = 9;
      oldtime = clock();
      time=clock()+(10*CLOCKS_PER_SEC);
      while (clock()<time)
         {
         if (clock()>oldtime)
            {
            printf("%ld seconds left. \r",count);
            fflush(stdout);
            oldtime = clock()+CLOCKS_PER_SEC;
            count--;
            }
         if (KB_KeyWaiting())
            {
            int32 ch = KB_Getch();
            ch -='a';
            if (ch>=0 && ch<numfiles)
               {
               strcpy (setupfilename, filenames[ch]);
               break;
               }
            }
         }
      printf("\n");
      }
   printf("Using Setup file: %s\n",setupfilename);
   i=clock()+(3*CLOCKS_PER_SEC/4);
   while (clock()<i)
      {
      ;
      }
   for (i=0;i<numfiles;i++)
      {
      SafeFree(filenames[i]);
      }
   }

/*
===================
=
= CONFIG_FunctionNameToNum
=
===================
*/

int32 CONFIG_FunctionNameToNum( char * func )
   {
   int32 i;

   for (i=0;i<NUMGAMEFUNCTIONS;i++)
      {
      if (!stricmp(func,gamefunctions[i]))
         {
         return i;
         }
      }
   return -1;
   }

/*
===================
=
= CONFIG_FunctionNumToName
=
===================
*/

char * CONFIG_FunctionNumToName( int32 func )
   {
   if (func < NUMGAMEFUNCTIONS)
      {
      return gamefunctions[func];
      }
   else
      {
      return NULL;
      }
   }

/*
===================
=
= CONFIG_SetMouseDefaults
=
===================
*/
void CONFIG_SetMouseDefaults( void )
   {
   int32 i;
   int32 function;

   for (i=0;i<MAXMOUSEBUTTONS;i++)
      {
      function = CONFIG_FunctionNameToNum(mousedefaults[i]);
      if (function != -1)
         CONTROL_MapButton( function, i, false );
      function = CONFIG_FunctionNameToNum(mouseclickeddefaults[i]);
      if (function != -1)
         CONTROL_MapButton( function, i, true );
      }
   }

/*
===================
=
= CONFIG_SetJoystickDefaults
=
===================
*/
void CONFIG_SetJoystickDefaults( void )
   {
   int32 i;
   int32 function;

   for (i=0;i<MAXJOYBUTTONS;i++)
      {
      function = CONFIG_FunctionNameToNum(joystickdefaults[i]);
      if (function != -1)
         CONTROL_MapButton( function, i, false );
      function = CONFIG_FunctionNameToNum(joystickclickeddefaults[i]);
      if (function != -1)
         CONTROL_MapButton( function, i, true );
      }
   CONTROL_JoystickPort = 0;
   }

/*
===================
=
= CONFIG_SetDefaultKeys
=
===================
*/
void CONFIG_SetDefaultKeys( void )
   {
   int32 i;
   int32 base;
   int32 function;
   char * keyname1;
   char * keyname2;
   kb_scancode key1,key2;

   for (i=0;i<NUMKEYENTRIES;i++)
      {
      base = i*3;
      function = CONFIG_FunctionNameToNum(keydefaults[base]);
      keyname1 = keydefaults[base+1];
      keyname2 = keydefaults[base+2];
      key1 = 0;
      key2 = 0;
      if (*keyname1)
         {
         key1 = (byte) KB_StringToScanCode( keyname1 );
         }
      if (*keyname2)
         {
         key2 = (byte) KB_StringToScanCode( keyname2 );
         }
      CONTROL_MapKey( function, key1, key2 );
      }
   }

/*
===================
=
= CONFIG_SetDefaults
=
===================
*/

void CONFIG_SetDefaults( void )
   {
   CONTROL_ClearAssignments();
   CONFIG_SetMouseDefaults();
   CONFIG_SetDefaultKeys();
   FXDevice = NumSoundCards;
   MusicDevice = NumSoundCards;
   FXVolume = 128;
   MusicVolume = 128;
   ReverseStereo = 0;
   ControllerType = controltype_keyboardandmouse;
   }

/*
===================
=
= CONFIG_ReadKeys
=
===================
*/

void CONFIG_ReadKeys( int32 scripthandle )
   {
   int32 i;
   int32 numkeyentries;
   int32 function;
   char keyname1[80];
   char keyname2[80];
   kb_scancode key1,key2;

   CONFIG_SetDefaultKeys();
   numkeyentries = SCRIPT_NumberEntries( scripthandle,"KeyDefinitions" );

   for (i=0;i<numkeyentries;i++)
      {
      function = CONFIG_FunctionNameToNum(SCRIPT_Entry(scripthandle,"KeyDefinitions", i ));
      if (function != -1)
         {
         memset(keyname1,0,sizeof(keyname1));
         memset(keyname2,0,sizeof(keyname2));
         SCRIPT_GetDoubleString
            (
            scripthandle,
            "KeyDefinitions",
            SCRIPT_Entry( scripthandle, "KeyDefinitions", i ),
            keyname1,
            keyname2
            );
         key1 = 0;
         key2 = 0;
         if (keyname1[0])
            {
            key1 = (byte) KB_StringToScanCode( keyname1 );
            }
         if (keyname2[0])
            {
            key2 = (byte) KB_StringToScanCode( keyname2 );
            }
         CONTROL_MapKey( function, key1, key2 );
         }
      }
   }

/*
===================
=
= CONFIG_ReadButtons
=
===================
*/

void CONFIG_ReadButtons( int32 scripthandle )
   {
   int32 i;
   char str[80];
   char temp[80];
   int32 function;


   if ( ControllerType == controltype_keyboardandmouse )
      {
      CONFIG_SetJoystickDefaults();
      for (i=0;i<MAXMOUSEBUTTONS;i++)
         {
         sprintf(str,"MouseButton%ld",i);
         memset(temp,0,sizeof(temp));
         SCRIPT_GetString( scripthandle,"Controls", str,temp);
         function = CONFIG_FunctionNameToNum(temp);
         if (function != -1)
            CONTROL_MapButton( function, i, false );
         sprintf(str,"MouseButtonClicked%ld",i);
         memset(temp,0,sizeof(temp));
         SCRIPT_GetString( scripthandle,"Controls", str,temp);
         function = CONFIG_FunctionNameToNum(temp);
         if (function != -1)
            CONTROL_MapButton( function, i, true );
         }
      }

   if (
         ( ControllerType == controltype_keyboardandjoystick ) ||
         ( ControllerType == controltype_keyboardandgamepad )
      )
      {
      CONFIG_SetJoystickDefaults();
      for (i=0;i<MAXJOYBUTTONS;i++)
         {
         sprintf(str,"JoystickButton%ld",i);
         memset(temp,0,sizeof(temp));
         SCRIPT_GetString( scripthandle,"Controls", str,temp);
         function = CONFIG_FunctionNameToNum(temp);
         if (function != -1)
            CONTROL_MapButton( function, i, false );
         sprintf(str,"JoystickButtonClicked%ld",i);
         memset(temp,0,sizeof(temp));
         SCRIPT_GetString( scripthandle,"Controls", str,temp);
         function = CONFIG_FunctionNameToNum(temp);
         if (function != -1)
            CONTROL_MapButton( function, i, true );
         }
      }

   }

/*
===================
=
= CONFIG_ReadSetup
=
===================
*/

void CONFIG_ReadSetup( void )
   {
   int32 dummy;
   int32 scripthandle;

   CONFIG_SetDefaults();
   setupread = true;
   scripthandle = SCRIPT_Load(setupfilename);
   SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenMode",&ScreenMode);
   SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenWidth",&ScreenWidth);
   SCRIPT_GetNumber( scripthandle, "Screen Setup", "ScreenHeight",&ScreenHeight);

   SCRIPT_GetNumber( scripthandle, "Sound Setup", "FXDevice",&FXDevice);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "MusicDevice",&MusicDevice);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "FXVolume",&FXVolume);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "MusicVolume",&MusicVolume);

   SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumVoices",&NumVoices);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumChannels",&NumChannels);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "NumBits",&NumBits);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "MixRate",&MixRate);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "MidiPort",&MidiPort);
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterAddress",&dummy);
   BlasterConfig.Address = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterType",&dummy);
   BlasterConfig.Type = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterInterrupt",&dummy);
   BlasterConfig.Interrupt = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterDma8",&dummy);
   BlasterConfig.Dma8 = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterDma16",&dummy);
   BlasterConfig.Dma16 = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "BlasterEmu",&dummy);
   BlasterConfig.Emu = dummy;
   SCRIPT_GetNumber( scripthandle, "Sound Setup", "ReverseStereo",&ReverseStereo);

   SCRIPT_GetNumber( scripthandle, "Controls","ControllerType",&ControllerType);
   SCRIPT_GetNumber( scripthandle, "Controls","JoystickPort",&dummy);

   CONTROL_JoystickPort = dummy;

   SCRIPT_GetNumber( scripthandle, "Controls","MouseSensitivity",&dummy);
   CONTROL_SetMouseSensitivity(dummy);

   CONTROL_ClearAssignments();

   CONFIG_ReadKeys(scripthandle);

   CONFIG_ReadButtons(scripthandle);
   }

/*
===================
=
= CONFIG_WriteSetup
=
===================
*/

void CONFIG_WriteSetup( void )
   {
   if (setupread)
      {
      int32 dummy;

      SCRIPT_PutNumber( scripthandle, "Sound Setup", "FXVolume",FXVolume,false,false);
      SCRIPT_PutNumber( scripthandle, "Sound Setup", "MusicVolume",MusicVolume,false,false);
      dummy = CONTROL_GetMouseSensitivity();
      SCRIPT_PutNumber( scripthandle, "Controls","MouseSensitivity",dummy,false,false);
      SCRIPT_Save (scripthandle, setupfilename);
      SCRIPT_Free (scripthandle);
      }
   }

