//#define DOOM2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
#include <conio.h>
#include <dos.h>

#include "doomnet.h"
#include "ipxstr.h"
//#include "ipx_frch.h"		// FRENCH VERSION
#include "ipxsetup.h"

doomcom_t doomcom;
int vectorishooked;
#ifndef _MSC_VER
void interrupt (*olddoomvect) (void);
#else
void (far interrupt *olddoomvect) (void);
#endif

void StrToArgV(char *args, char **argv, int *argc)
	{
	char *pArg;

	argv[0] = myargv[0];

	*argc = 1;
	pArg = strtok(args, " ");

	while (pArg)
		{
		argv[(*argc)++] = pArg;
		if (stricmp(pArg, PARM_MSG) == 0) //get message as one argument
			{
			pArg = strtok(0, "\"");
			argv[(*argc)++] = pArg;
			}
		pArg = strtok(0, " ");
		}
	}
/*
=============
=
= LaunchDOOM
=
These fields in doomcom should be filled in before calling:

short	numnodes;      // console is allways node 0
short	ticdup;             // 1 = no duplication, 2-5 = dup for slow nets
short	extratics;          // 1 = send a backup tic in every packet

short	consoleplayer; // 0-3 = player number
short	numplayers;         // 1-4
short	angleoffset;   // 1 = left, 0 = center, -1 = right
short	drone;              // 1 = drone
=============
*/
	
void LaunchDOOM (void)
	{
	char *newargs[99];
	char	adrstring[10];
	long	flatadr;
	struct _SREGS sregs;
	int nArg, i;

	_segread(&sregs);

// prepare for DOOM
	 doomcom.id = DOOMCOM_ID;

// hook the interrupt vector
	olddoomvect = (void (interrupt far *)(void))_dos_getvect (doomcom.intnum);
#ifndef _MSC_VER
	_dos_setvect (doomcom.intnum,(void (cdecl far interrupt *)(void))MK_FP(sregs.cs, (int)NetISR));
#else
	_dos_setvect (doomcom.intnum, NetISR);
#endif
	vectorishooked = 1;

	if (slave)
		{
		//if there was a Master then convert the command line arguments passed
		//to pass to DOOM via spawnv()

		StrToArgV(masterArgs, newargs, &nArg);
		}
	else
		{
		//build the argument list for DOOM 
   		memcpy (newargs, myargv, (myargc+1)*sizeof(void *));
		nArg = myargc;
		}
	//add "-net &doomcom"
 	newargs[nArg++] = "-net";
 	flatadr = (long)sregs.ds*16 + (unsigned)&doomcom;
 	sprintf (adrstring,"%lu",flatadr);
 	newargs[nArg++] = adrstring;
 	newargs[nArg] = NULL;

//Launch DEHACKED and load patch if requested
	if ((i = CheckParm(PARM_DEHACK, nArg, newargs)) != 0)
		spawnl(P_WAIT, "dehacked", "dehacked.exe", "-load", newargs[i+1], 0);

//Display message at each players console
	if ((i = CheckParm(PARM_MSG, nArg, newargs)) != 0)
		{
		printf("\n\n\a%s\n\n", newargs[i+1]);
		printf("Press any key to continue...");
		getch();	
		printf("\n");
		}
#ifndef DEBUG
	if (!access("doom2.exe",0))
		spawnv  (P_WAIT, "doom2", newargs);
	else
		spawnv  (P_WAIT, "doom", newargs);
#endif

#ifdef DOOM2
	printf (STR_RETURNED"\n");
#else
	printf ("Returned from DOOM\n");
#endif
	}
