#include <v_lib.h>

/*
 * Yet another one example of LibV I/O.
 */

typedef struct
{
	u32_t	filepos;
	u32_t	size;
	char	name[8];
}	wadfile_entry_t;

int main(int argc,char *argv[])
{
	file_t	in, out;
	u8_t	id[4];
	u32_t	numlumps;
	u32_t	infotableoffs;
	wadfile_entry_t *dir;
	u8_t	*data=NULL;
	char	name[16];
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	
	if(argc != 2)
	{
		puts("Usage: unwad <file.wad>");
		return -1;
	}
	in=fileOpenRead(argv[1]);
	if(in == NULL)
	{
		printf("Unable to open %s.");
		return -1;
	}
	fileRead(in,id,4);
	if(id[1]!='W' || id[2]!='A' || id[3]!='D')
	{
		printf("%s: isn't WAD file");
		fileClose(in);
		return -1;
	}
	numlumps=fileGetLittleLong(in);
	infotableoffs=fileGetLittleLong(in);
	if(!fileControl(in,pctl_map_ispace,(void_p*)&data) || data == NULL)
	{
		printf("Unable to mmap() '%s'.");
		fileClose(in);
		return -1;
	}
	memZero(name,16);
	/* Determine address of WAD directory */
	dir = (wadfile_entry_t*)(data + infotableoffs);
	/* Unpack all resources */
	while(numlumps--)
	{
		if(dir->size > 0)
		{
			memcpy(name,dir->name,8);
			out=fileOpenWrite(name);
			fileWrite(out,data + dir->filepos,dir->size);
			fileClose(out);
		}
		dir++;
	}
	fileClose(in);
	return 0;
}
