/*
 * 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 <stdio.h>
#include <stdlib.h>

#include "qdfunct.h"

long *grab_addresses(FILE *bsp)
{
	long *	hdr_ptr;
	long	loc_sav;

	hdr_ptr = (long *)malloc(sizeof(long) * BH_NELEM);

	if (hdr_ptr == NULL)
	{
		fprintf(stderr,
				"\nFatal error: Out of memory at grab_addresses()\n");

		return (NULL);
	}

	loc_sav = ftell(bsp);
	rewind(bsp);

	fread(hdr_ptr, sizeof(long), BH_NELEM, bsp);

	fseek(bsp, loc_sav, SEEK_SET);

	return (hdr_ptr);
}

// Returns: EOF on premature EOF
//			0 otherwise
int export_quake_def(FILE *bsp, FILE *qdf, unsigned long len)
{
	int		cur_char;
	int		prev_char = 0;

	// Make it so
	for (; len > 0; len--)
	{
		if ((cur_char = fgetc(bsp)) == EOF)
			return (EOF);

		// Normally a terminating character
		if (cur_char == 0x00)
			break;

		// Should we indent?
		if (prev_char == 0x0A && cur_char != '{' && cur_char != '}')
			fputc(' ', qdf);

		// Put it... IN....
		fputc(cur_char, qdf);

		// Should we put an extra <CR>?
		if (cur_char == '}')
			fputc('\n', qdf);

		// Keep track of last character
		prev_char = cur_char;
	}

	return (0);
}

void import_quake_def(FILE *qdf, FILE *new_bsp)
{
	char 	buffer[BUFSIZ];
	int 	cur_char;
	int 	prev_char = 0;
	int		ctr;

	for (ctr = 0; ((cur_char = fgetc(qdf)) != EOF);)
	{
		if (ctr >= BUFSIZ)
		{
			fwrite(buffer, sizeof(char) * BUFSIZ, 1, new_bsp);
			ctr = 0;
		}

		if (cur_char == ' ' && prev_char == '\n')
			continue;

		if (cur_char == '\n')
		{
			if (prev_char != '\n')
			{
				buffer[ctr] = 0x0A;
				ctr++;

				prev_char = cur_char;
			}

			continue;
		}

		buffer[ctr] = cur_char;
		ctr++;

		prev_char = cur_char;
	}

	// Any unwritten data?
	if (ctr)
		fwrite(buffer, sizeof(char) * ctr, 1, new_bsp);
}

void fix_bsp_hdr(FILE *bsp, long *ara, long diff)
{
	long loc_sav;

	loc_sav = ftell(bsp);
	rewind(bsp);

	ara[BH_POSTQD_ELEM] += diff;
	ara[BH_QDSIZE_ELEM] =
		ara[BH_POSTQD_ELEM] - ara[BH_QD_ELEM] - 1;

	fwrite(ara, sizeof(long), BH_NELEM, bsp);

	fseek(bsp, loc_sav, SEEK_SET);
}