/*

	Noctis galactic guide / DELE command.
	GOES Net Module.

*/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include <io.h>
#include "defs.h"
#include "modshare.hpp"

double 	object_id = 12345;
char   	object_label[25];
double 	s_object_id = 12345;
char   	s_object_label[25];

double	subject_id = 12345;
double  idscale = 0.00001;

Dword	round;
Dword	guide_consolidated;

Word 	i;
FILE * fh;
FILE * gh;
char	*file = "..\\DATA\\starmap3.map";
char	*guide = "..\\DATA\\starmap3.gd";

char	outbuffer[40];
char	textbuffer[40];
char	parbuffer[160];
char	nullbuffer[128];
char	objectname[21];
char	subjectname[21];

double	mblock_subject;
char	mblock_message[78];


Dword nearstar_sx	  	= 0x7fffffff;		//53
Dword nearstar_sy	  	= 0x7fffffff;		//57
Dword nearstar_sz	  	= 0x7fffffff;		//61
Uword obj_pNum;
Uword obj_mNum;
#define new_data_start 245+5+120

Uchar flags;
Udword discoverer;
char name[21];
char lastname[21];
Dword sx, sy, sz;
Uword data;
Udword nextAlternateFP;
Udword starFP;
Bool exactMatch = 0;

char find (char *tgtname, Udword starmap3Len)
{
	obj_pNum=0;
	obj_mNum=0;
	Word p, n, ctc, found;
	ctc = strlen (tgtname);
	if (ctc > 20 || ctc <= 0) {
		msg ("INVALID OBJECT NAME.");
		return(0);
	}
	n = 0;
	found = 0;
	exactMatch=0;
	fseek (fh, 10, SEEK_SET);
	while (ftell(fh)<starmap3Len) {
		fread(&flags, 1, 1, fh);
		fread(&discoverer, 4, 1, fh);
		fread(&name, 20, 1, fh);
		if (flags&0x8) {
			fread(&sx, 4, 1, fh);
			fread(&sy, 4, 1, fh);
			fread(&sz, 4, 1, fh);
			fread(&data, 2, 1, fh);
			fread(&nextAlternateFP, 4, 1, fh);
			if (memcmp(name, tgtname, ctc)==0 && !(flags&0x20)) {
				if (ctc<20 && ctc>=2 && name[ctc]==32 && name[ctc-1]!=32) {
					exactMatch=2;
					if (n>0) {
						msg("NEVERMIND, FOUND EXACT MATCH");
						msg(name);
						n=1;
					}
				}
				if (!exactMatch) {
					//found it
					if (n==1) {	//If this is the second match
						msg ("AMBIGUOUS SEARCH KEY:");
						msg ("PLEASE EXPAND NAME...");
						msg (divider);
						msg ("POSSIBLE RESULTS ARE:");
						msg (divider);
						lastname[20]=0;
						msg (object_label);
					}
					if (n>0) {
						msg (name);
					}
					n++;
				}
				if (exactMatch!=1) {
					memcpy(object_label, name, 20);
					memcpy(subjectname, object_label, 20);
					//memcpy(starname, subjectname, 20);
					//printf("FOUND. SX=%li SY=%li SZ=%li. ", sx, sy, sz);
					nearstar_sx = sx;
					nearstar_sy = sy;
					nearstar_sz = sz;
					//printf("FOUND. NSX=%li NSY=%li NSZ=%li. ", nearstar_sx, nearstar_sy, nearstar_sz);
					obj_pNum=0x1F;
					obj_mNum=0x1F;
					//msg("0x1F NOW.");
					found=1;
					while (p >= 0) {
						if (name[p] != 32) {
							if (name[p] == tgtname[p])
								return (found);
							else
								break;
						}
						p--;
					}
					if (exactMatch==2) return found;
				}
			}
		} else {
			fread(&starFP, 4, 1, fh);
			fread(&data, 2, 1, fh);
			fread(&nextAlternateFP, 4, 1, fh);
			if (memcmp(name, tgtname, ctc)==0 && !(flags&0x20)) {
				if (ctc<20 && ctc>=2 && name[ctc]==32 && name[ctc-1]!=32) {
					exactMatch=2;
					if (n>0) {
						msg("NEVERMIND, FOUND EXACT MATCH");
						msg(name);
						n=1;
					}
				}
				if (!exactMatch) {
					//found it
					if (n==1) {	//If this is the second match
						msg ("AMBIGUOUS SEARCH KEY:");
						msg ("PLEASE EXPAND NAME...");
						msg (divider);
						msg ("POSSIBLE RESULTS ARE:");
						msg (divider);
						lastname[20]=0;
						msg (object_label);
					}
					if (n>0) {
						msg (name);
					}
					n++;
				}
				if (exactMatch!=1) {
					memcpy(object_label, name, 20);
					memcpy(subjectname, object_label, 20);
					
					Dword pos = ftell(fh);
					fseek(fh, starFP+5, SEEK_SET);
					//fread(starname, 20, 1, fh);
					fseek(fh, starFP+25, SEEK_SET);
					fread(&nearstar_sx, 4, 1, fh);
					fread(&nearstar_sy, 4, 1, fh);
					fread(&nearstar_sz, 4, 1, fh);
					fseek(fh, pos, SEEK_SET);
					
					obj_pNum = ((data>>4)&0x1F);
					obj_mNum = ((data>>9)&0x1F);
					found=2;
					while (p >= 0) {
						if (name[p] != 32) {
							if (name[p] == tgtname[p])
								return (found);
							else
								break;
						}
						p--;
					}
					if (exactMatch==2) return found;
				}
			}
		}
	}
	
	if (!n)
		msg ("OBJECT NOT FOUND.");
	if (n > 1) {
		found=0;
	}
	return (found);
}
/*
char find (char *starname)
{
	Word p, n, ctc, found;
	ctc = strlen (starname);
	if (ctc > 20 || ctc <= 0) {
		msg ("INVALID OBJECT NAME.");
		return(0);
	}
	n = 0;
	found = 0;
	lseek (fh, 4, SEEK_SET);
	while (_read (fh, &s_object_id, 8) && _read (fh, &s_object_label, 24) == 24) {
		if (memcmp (&s_object_id, "Removed:", 8)) {
			if (!memcmp (s_object_label, starname, ctc)) {
				n++;
				memcpy (object_label, s_object_label, 24);
				object_id = s_object_id;
				memcpy (subjectname, object_label, 20);
				subject_id = object_id;
				if (object_label[21] == 'S') found = 1;
				if (object_label[21] == 'P') found = 2;
				p = 20;
				while (p >= 0) {
					if (s_object_label[p] != 32) {
						if (s_object_label[p] == starname[p])
							return (found);
						else
							break;
					}
					p--;
				}
			}
		}
	}
	if (!n)
		msg ("OBJECT NOT FOUND.");
	if (n > 1) {
		msg ("AMBIGUOUS SEARCH KEY:");
		msg ("PLEASE EXPAND NAME...");
		msg (divider);
		msg ("POSSIBLE RESULTS ARE:");
		msg (divider);
		lseek (fh, 4, SEEK_SET);
		while (_read (fh, &s_object_id, 8) && _read (fh, &s_object_label, 24) == 24) {
		if (memcmp (&s_object_id, "Removed:", 8) && !memcmp (s_object_label, starname, ctc)) {
			s_object_label[21] = 0;
			msg (s_object_label);
		}}
		msg (divider);
		found = 0;
	}
	return (found);
}
*/

void main ()
{
	CHECK_SITUATION;
	char query;
	Word tmessages;
	Word rmessages;
	Word is, rec, rec_start, rec_end;

	/*asm {	xor	ax, ax
		mov	es, ax
		cmp	byte ptr es:[0x449], 0x13
		je	startup }

	printf ("\nGalactic Organization of Explorers and Stardrifters (G.O.E.S)\n");
	printf ("-------------------------------------------------------------\n");
	printf ("This is a GOES NET module and must be run from a stardrifter.\n");
	printf ("Please use the onboard computer console to run this module.\n");
	printf ("\n\t- GOES NET onboard microsystem, EPOC 6011 REVISION 2\n");
	return;*/

	//startup:
	if (_argc<2) {
		msg ("________USAGE________");
		msg ("DELE OBJECTNAME");
		msg ("DELE OBJECTNAME:X..Y");
		msg ("^^^^^^^^^^^^^^^^^^^^^");
		msg ("PLEASE RUN AGAIN,");
		msg ("SPECIFYING PARAMETERS");
		return;
	}
	else {
		msg (" GOES GALACTIC GUIDE ");
		msg (divider);
	}
	//check galaxy
	#ifdef GALAXY2
	for (current_galaxy=0; current_galaxy<2; current_galaxy++) {
		if (current_galaxy==1) {
			file = file2;
			guide = guide2;
		}
	#endif
	fh = fopen (file, "rb");
	if (fh == NULL) {
		msg ("STARMAP NOT AVAILABLE");
		return;
	}
	Udword starmap3Len = 0;
	fseek(fh, 0, SEEK_END);
	starmap3Len = ftell(fh);
	fseek(fh, 0, SEEK_SET);
	Uword fileFormatVersion;
	Udword starmap3VersionHalf;
	fread(&fileFormatVersion, 2, 1, fh);
	fread(&starmap3VersionHalf, 4, 1, fh);
	fread(&starmap3VersionHalf, 4, 1, fh);
	
	i = 2;
	strcpy (parbuffer, _argv[1]);
	while (i < _argc) {
		strcat (parbuffer, " ");
		strcat (parbuffer, _argv[i]);
		i++;
	}

	i = 0;
	while (parbuffer[i]) {
		if (parbuffer[i] == '_')
			parbuffer[i] = 32;
		i++;
	}

	i = 0;
	while (i < 21 && parbuffer[i] != ':' && parbuffer[i] != 0) {
		objectname[i] = parbuffer[i];
		i++;
	}

	if (i == 21) {
		msg ("INVALID SUBJECT NAME.");
		fclose (fh);
		return;
	}

	if (parbuffer[i] == ':') {
		is = i+1; i++;
		while (parbuffer[i] != '.' && parbuffer[i] != 0) i++;
		parbuffer[i] = 0; rec_start = atoi (parbuffer + is);
		if (parbuffer[i+1] == '.') {
			rec_end = atoi (parbuffer + i + 2);
			if (rec_end==0) rec_end=32767;
		} else {
			rec_end = rec_start;
		}
	}
	else {
		rec_start = 1;
		rec_end = 32767;
	}
	

	if (parbuffer[i] != ':') {
		strupr (parbuffer);
		strupr (objectname);
		objectname[i] = 0;
		Dword matches = FindInStarmap (fh, starmap3Len, objectname, &sm3data);
		if (matches==1) {
			if (sm3data.retvalType==RETVAL_STAR) msg ("SUBJECT: STAR;");
			if (sm3data.retvalType==RETVAL_PLANET) msg ("SUBJECT: PLANET;");
			sprintf (outbuffer, "NAME: %s.20s", sm3data.name);
			msg (outbuffer);
			msg (divider);
			gh = fopen (guide, "r+b");
			if (gh == NULL) {
				msg ("DATABASE ERROR.");
				msg ("(ERROR CODE 1004)");
			} else {
				rec = 0;
				query = 0;
				tmessages = 0;
				rmessages = 0;
				Udword guide3Len = 0;
				fseek(gh, 0, SEEK_END);
				guide3Len = ftell(gh);
				fseek(gh, 0, SEEK_SET);
				Uword gfileFormatVersion;
				Udword gstarmap3VersionHalf;
				fread(&gfileFormatVersion, 2, 1, gh);
				fread(&gstarmap3VersionHalf, 4, 1, gh);
				fread(&gstarmap3VersionHalf, 4, 1, gh);
				
				fseek(gh, 10, SEEK_SET);
				Uchar e_flags;
				Dword e_sx, e_sy, e_sz;
				Uword e_pNum, e_mNum;
				Udword e_writer;
				//_read (gh, &guide_consolidated, 4);
				//while (_read (gh, &mblock_subject, 84) == 84) {
				//	if (mblock_subject > subject_id - idscale && mblock_subject < subject_id + idscale) {
				while (ftell(gh)<guide3Len) {
					fread(&e_flags, 1, 1, gh);
					fread(&e_sx, 4, 1, gh);
					fread(&e_sy, 4, 1, gh);
					fread(&e_sz, 4, 1, gh);
					fread(&e_pNum, 2, 1, gh);
					fread(&e_mNum, 2, 1, gh);
					fread(&e_writer, 4, 1, gh);
					fread(mblock_message, 76, 1, gh);
					if (!(e_flags&0x20) && e_sx==sm3data.sx && e_sy==sm3data.sy && e_sz==sm3data.sz && e_pNum==sm3data.pNum && e_mNum==sm3data.mNum) {
						tmessages++;
						rec++;
						if (rec >= rec_start && rec <= rec_end) {
							query = 1;
							Dword curpos = ftell(gh);
							fseek(gh, -97, SEEK_CUR);	//(76+4+2+2+4+4+4+1) = 97
							e_flags=e_flags|0x20;
							fwrite(&e_flags, 1, 1, gh);
							fseek(gh, curpos, SEEK_SET);
							rmessages++;
							/*
							round = tell(gh);
							round -= 84;
							if (round >= guide_consolidated) {
								rmessages++;
								lseek (gh, round, SEEK_SET);
								_write (gh, "Removed:", 8);
								round += 84;
								lseek (gh, round, SEEK_SET);
							}
							*/
						}
					}
				}
				if (!query) {
					msg ("THERE WERE NO RECORDS");
					msg ("THAT COULD BE DELETED");
				}
				else {
					sprintf (outbuffer, "TOTAL RECORDS: %d", tmessages);
					msg (outbuffer);
					sprintf (outbuffer, "REMOVED: %d", rmessages);
					msg (outbuffer);
					sprintf (outbuffer, "PROTECTED: %d", tmessages - rmessages);
					msg (outbuffer);
				}
				fclose (gh);
			}
		}
	}

	fclose (fh);
	#ifdef GALAXY2
	}
	#endif
}