#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <io.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <malloc.h>
#include <fcntl.h>

#define PWAD 0x44415750

struct header
{	long	magic;
	long	numentries;
	long	diroff;	};

struct dirent
{	long	offset;
	long	length;
	char	name[8];	};

int	fhw;
long	offset;

void error(char *errstr)
{	printf(errstr);
	exit(1);	}

void addlumpdirent(pfind,lump)
struct find_t *pfind;
unsigned int lump;
{
	struct dirent dire;
	char lname[20], fname[20];
	unsigned long dsize;
	int i;
	
	dire.offset=offset;
	dsize=pfind->size;
	dire.length=dsize;
	strcpy(fname, pfind->name);
	strcpy(lname, "\0");
	strncat(lname, fname, strlen(fname)-4);
	for (i=0; i<strlen(lname); i++)
		if ((lname[i]>='a') && (lname[i]<='z'))
			lname[i] &= 0xdf;
	strncpy(dire.name, lname, 8);
	printf("%lx\t%lx\t%s\n",dire.offset,dire.length,lname);

	write(fhw,&dire,16);

	dsize += 3;
	dsize &= 0xfffffffc;
	offset+=dsize;
}

void addlump(pfind)
struct find_t *pfind;
{
	unsigned long dsize;
	char fname[20];
	char *data;
	int fh;
	
	dsize=pfind->size;
	strcpy(fname, pfind->name);
	if ((data=(char *)malloc(dsize))==NULL)
		error("Lump too big for this shite program.\n");
	if (!(fh=open(fname,O_BINARY|O_RDONLY)))
		error("Bizarre problem opening lump.\n");
	read(fh,data,dsize);
	close(fh);
	
	dsize += 3;
	dsize &= 0xfffffffc;
	write(fhw,data,dsize);
	offset += dsize;
	free(data);
}


main(argc,argv)
int argc;
char *argv[];
{
	struct find_t find;
	char lname[20], wname[20];
	struct header head;
	unsigned int lump, lumpnum;
	
	if (argc != 3)
		error("Usage: lmp2wad <wadname> <wildfilespec>\n"
			"\t(no file extensions)");
	
	strcpy(wname, argv[1]);
	strcat(wname, ".wad");
	strcpy(lname, argv[2]);
	strcat(lname, ".lmp");
	
	//	Count number of entries in directory
	if (!_dos_findfirst(lname, _A_NORMAL, &find))
		lumpnum=1;
	else	error("Nothing to put in wad!\n");
	while (!_dos_findnext(&find))
		lumpnum++;
	printf("Number of lumps in directory: %d\n", lumpnum);
	if (lumpnum>4095)
		error("Max lumps is 4095. Sorry.\n");
	
	head.magic=PWAD;
	head.numentries=lumpnum;
	head.diroff=0;
	
	if (!(fhw=open(wname,O_CREAT|O_BINARY|O_WRONLY,S_IREAD|S_IWRITE)))
		error("Can't create WAD.\n");
	write(fhw,&head,12);
	offset=12;
	
	lump=0;
	_dos_findfirst(lname, _A_NORMAL, &find);
	addlump(&find);
	while(!_dos_findnext(&find))
		addlump(&find);
		
	head.diroff=offset;
	
	lump=0;
	offset=12;
	_dos_findfirst(lname, _A_NORMAL, &find);
	addlumpdirent(&find, lump++);
	while (!_dos_findnext(&find))
		addlumpdirent(&find, lump++);

	lseek(fhw,0,SEEK_SET);
	write(fhw,&head,12);
	close(fhw);
	
	exit(0);
}