/*
 * Copyright (C) 1996 by Chris Johnson.  All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that copyright notice and this permission
 * notice appear in supporting documentation.  If more than a few
 * lines of this code are used in a program which displays a copyright
 * notice or credit notice, the following acknowledgment must also be
 * displayed on the same screen: "This product includes software
 * developed by Chris Johnson for use in the QuakeDef Tools package."
 * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESSED OR IMPLIED
 * WARRANTY.
 *
 * (Thanks to Raphael Quinet for this nifty disclaimer!)
 */

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

#include "qdimport.h"
#include "fileutil.h"
#include "qdfunct.h"

int main(int argc, char *argv[])
{
	FILE *	old_bsp;
	FILE *	new_bsp;
	FILE *	qdf;
	long *	addr = NULL;
	long	diff;

	if (argc < 4)
	{
		show_help();
		exit(ERROR);
	}

	if (! fexist(argv[1]))
		exit(ERROR);

	if ((old_bsp = safeopen(argv[2], "rb")) == NULL)
		exit(ERROR);

	if ((new_bsp = safeopen(argv[3], "wb")) == NULL)
		exit(ERROR);

	// Get old bsp header
	if ((addr = grab_addresses(old_bsp)) == NULL)
		exit(ERROR);

	// Copy pre-QuakeDef portion
	if (copy(new_bsp, old_bsp, addr[BH_QD_ELEM]) == EOF)
	{
		fprintf(stderr, "\nError during copy process.\n");
		exit(ERROR);
	}

	// Uhhhhh... In case of freak accident....  :)
	if ((qdf = safeopen(argv[1], "rt")) == NULL)
		exit(ERROR);

	// Copy QuakeDef portion
	import_quake_def(qdf, new_bsp);

	fclose(qdf);

	// Calculate size difference between new and old QuakeDefs
	diff = ftell(new_bsp) - addr[BH_POSTQD_ELEM];

	// Copy post-QuakeDef portion
	fseek(old_bsp, addr[BH_POSTQD_ELEM], SEEK_SET);
	if (copy(new_bsp, old_bsp,
			 filelength(fileno(old_bsp)) - ftell(old_bsp)) == EOF)
	{
		fprintf(stderr, "\nError during copy process.\n");
		exit(ERROR);
	}

	// Fix BSP Header info
	fix_bsp_hdr(new_bsp, addr, diff);

	// Tidy up
	free(addr);

	fclose(old_bsp);
	fclose(new_bsp);

	fprintf(stderr, "\nImport of QuakeDef file successful!\n");

	return (OKAY);
}

void show_help(void)
{
	printf("\nQuakeDef Importer v1.0.  Copyright 1996 by Chris Johnson.");
	printf("\n\nUsage:");
	printf("\n\nqdimport <drive:><\\path\\><deffile.def> "
			"<drive:><\\path\\><old_map.bsp>");
	printf("\n         <drive:><\\path\\><new_map.bsp>");
	printf("\n\n<drive:> and <\\path\\> unnecessary if "
			"current directory is adequate.");
	printf("\n<deffile.def> is the filename of the QuakeDef ASCII file.");
	printf("\n<old_map.bsp> is the filename of the .BSP "
			"file that deffile.def");
	printf("\n              came from.");
	printf("\n<new_map.bsp> is the filename of the new .BSP "
			"file to create.\n");
}