#include <stdio.h>
#include <io.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

#include "memory.h"
#include "typedefs.h"
#include "filehandle.h"

extern wadinfo_t wad;
extern lumpinfo_t* lump;
extern char lmpFiles[256];

static int W_GetNumForName(char* name)
{
	int i = 0;
	char fillName[9];
	strncpy(fillName, name, 8);
	fillName[8] = 0;
	for(i = 0; i < wad.numlumps; i++)
	{
		if(!strncmp(fillName, lump[i].name, 8))
		{
			return i;
		}
	}
	return -1;
}

int main(int argc, char**argv)
{
	int numlumps = 0, i, handle, size, mainFile, sprHandle = 0;
	char filePath[256];
	byte* data;
	FILE* f;
	char* lumpName;
	bool isSpr = false;
	char* base = argv[0];

	KillFileName(base);

	printf("__________________________________________________________\n");
	printf("_________GBADMAKE: Iwad linking tool for GBADoom__________\n");
	printf("_By Samuel 'Kaiser' Villarreal..Email: svkaiser@gmail.com_\n");
	printf("__________________________________________________________\n");

	if(!argv[1])
	{
		printf("Main: no input file specified\n");
		printf("How to use: GBADMAKE.exe [input .dat file]\n");
		printf("The input file is a binary file that holds the filepath to each\n");
		printf("individual lump file. Data file is created with the utility included\n");
		printf("with GBADMAKE.exe\n");
		exit(1);
	}
	//create path
	sprintf(filePath, "%s/GBADOOM.WAD", base);
	f = fopen(filePath, "wb");

	//count how many files are there.
	mainFile = open(argv[1], FBIN);
	lseek(mainFile, 0, SEEK_END);
	size = tell(mainFile);

	numlumps = size / 256;

	//setup wad header
	wad.identification[0] = 'I';
	wad.identification[1] = 'W';
	wad.identification[2] = 'A';
	wad.identification[3] = 'D';
	wad.numlumps = numlumps;
	wad.infotableofs += sizeof(wadinfo_t);

	lump = (lumpinfo_t*)M_MakeAlloc(sizeof(lumpinfo_t) * numlumps);

	//calculate when the directory structure will be read at. Also setup directory as well
	for(i = 0; i < numlumps; i++)
	{
		//read from dat file
		lseek(mainFile, i*256, SEEK_SET);
		read(mainFile, lmpFiles, sizeof(lmpFiles));
		//scan though and remove any garbage.. especially spaces which vb loves doing..
		lumpName = CleanString();

		if(lumpName[0] > 32)
		{
			handle = open(lumpName, FBIN);
			if(!handle)
			{
				printf("Main: Error opening file %s\n", lumpName);
				exit(1);
			}
			lseek(handle, 0, SEEK_END);
			size = tell(handle);
			lump[i].size = (size - (size % 4));
			if(size % 4)
				lump[i].size += 4;

			size = FileSizeAdjust(size);

			lump[i].filepos = wad.infotableofs;
			//pointer to the directory is usually the sum of all data combined..
			wad.infotableofs += size;
			ExtractFileBase(lumpName, lump[i].name);
			lump[i].name[8] = '\0';
			if(strstr(lumpName, "_data.lmp") && isSpr == true)
			{
				//memset(lump[i].name, 0, 8);
				sprintf(lump[i].name, "%c%c%c%cDATA", lump[i].name[0],
					lump[i].name[1], lump[i].name[2], lump[i].name[3]);
			}
			printf("Saving %s..\n", lump[i].name);
			close(handle);
			if(!strncmp(lump[i].name, "S_START", 8))
				isSpr = true;
			if(!strncmp(lump[i].name, "S_END", 8))
				isSpr = false;
		}
	}

	//write header
	fwrite(&wad, sizeof(wadinfo_t), 1, f);

	//gather files again and write data
	for(i = 0; i < numlumps; i++)
	{
		//read from dat file
		lseek(mainFile, i*256, SEEK_SET);
		read(mainFile, lmpFiles, sizeof(lmpFiles));
		lumpName = CleanString();

		if(lumpName[0] > 32)
		{
			handle = open(lumpName, FBIN);
			lseek(handle, 0, SEEK_END);
			size = tell(handle);

			size = FileSizeAdjust(size);

			data = (byte*)M_MakeAlloc(size);
			memset(data, 0xDD, size);	//extra bytes are 0xDD
			lseek(handle, 0, SEEK_SET);
			read(handle, data, size);
			fwrite(data, size, 1, f);
			free(data);
			close(handle);
		}
	}

	/*Should have at least one blank entry left. Use it for the endofwad marker*/
	if(lump[numlumps - 1].name[0] == 0)
		strncpy(lump[numlumps - 1].name, "ENDOFWAD", 8);

	//write directory
	fwrite(lump, sizeof(lumpinfo_t)*numlumps, 1, f);

	//delete any allocated stuff and close all files..
	lump = (lumpinfo_t*)M_Clear(lump, sizeof(lumpinfo_t) * numlumps, true);
	fclose(f);
	close(mainFile);

	printf("Linking %s..\n", filePath);
	printf("%i Lumps saved\n", numlumps);

	return 1;
}