/***
****  QuBE --- BSP tree manipulation routine.
***/

#include "qube.h"
#include "tree.h"

static char HeaderInfo[][128] = {
       "List of entities (type, placement, info, etc.)",
       "The map planes (split planes, 28 bytes each)",
       "Pointers to pictures",
       "Map vertices (12 bytes each, floating point)",
       "PVS lists (bit masks)",
       "Hull BSP nodes (32 bytes each)",
       "Map surfaces (24 bytes each)",
       "Wall lighting maps (mip arrays)",
       "Hull-bounding BSP tree (8 bytes each)",
       "Hull BSP leaves (56 bytes each)",
       "List of surfaces (2 bytes each)",
       "Original surface edges (4 bytes each)",
       "List of surface edges (2 bytes each)",
       "List of hulls (56 bytes each)",
};

/*
**  ShowHeader.  Display file header and relevant information.
*/

void ShowHeader(void)
{
	long int *hdptr;
	int i;

	printf("\nNo. Offset   Size       Description\n");
	printf(  "--- -------- ---------- -----------\n");
	printf(" 0. %08lX            Identifier tag - should be 17\n", header.id);

	for (hdptr = (long int *)(&header) + 1, i = 0; i < 14; i++, hdptr += 2)
		printf("%2d. %08lX (%08lX) %s\n", i+1, *hdptr, *(hdptr+1), HeaderInfo[i]);
}

/*
**  XtractAll.	Extract everything to separate files.  Messy.
*/

void XtractAll(int argnum, char **argv)
{
	long int *hdptr;
	long int i, j, k, readsize;
	FILE *fo;
	char tempname[1024];
	char *temp;

	temp = Qmalloc(32768);

	for (hdptr = (long int *)(&header) + 1, i = 0; i < 14; i++, hdptr += 2) {
		fseek(fi, *hdptr, SEEK_SET);
                sprintf(tempname, "%s.%d", argv[argnum+1], i+1);
                fo = fopen(tempname, "wb");
                for (j = 0L; j < *(hdptr+1); j += 32768L) {
			if (*(hdptr+1) - j >= 32768) k = 32768;
			else k = *(hdptr+1) - j;
			readsize = fread(temp, sizeof(char), k, fi);
			fwrite(temp, sizeof(char), readsize, fo);
		}
		fclose(fo);
        }

	Qfree(temp);
}

/*
**  TreeList.  Not a lot, but it does the job.
*/

void TreeList(void)
{
	short int i, j, k;
	unsigned long readcount;

	struct {
		unsigned long int line;       /* What is this?	A polygon pointer? */
		short int left;
		short int right;
	} tree;

	if (header.id != 0x17)
		Error("Not a valid .BSP file");

        fseek(fi, header.tree, SEEK_SET);

	for (i = 0, readcount = 0L; readcount < header.treelen; readcount += 8, i++) {
                fread(&tree, 8, 1, fi);
		printf("%4d:  %4d  %4d   (%ld)", i, tree.left, tree.right, tree.line);
		printf("\n");
        }
}

