#include "../fileio/fileio.h"
#include "../fileio/fileglob.h"
#include "globals.h"
#include "pit.h"
#include "../machdr/machdr.h"
#include "crc.h"
#include "masks.h"

void pit_wrfile();
void read_tree();
void pit_skip();

void pit()
{
    struct pit_header filehdr;
    char pithdr[4];
    int decode;
    unsigned long data_crc, crc;

    updcrc = binhex_updcrc;
    crcinit = binhex_crcinit;
    while(1) {
	if(fread(pithdr, 1, 4, infp) != 4) {
	    fprintf(stderr, "Premature EOF\n");
	    exit(1);
	}
	if(strncmp(pithdr, "PEnd", 4) == 0) {
	    break;
	}
	if((strncmp(pithdr, "PMag", 4) != 0) &&
	    (strncmp(pithdr, "PMa4", 4) != 0)) {
	    fprintf(stderr, "File contains non PackIt info\n");
	    exit(1);
	}
	bytes_read = 0;
	bytes_written = 0;
	if(pithdr[3] == '4') {
	    read_tree();
	    decode = huffman;
	} else {
	    decode = nocomp;
	}
	if(pit_filehdr(&filehdr, decode) == -1) {
	    fprintf(stderr, "Can't read file header\n");
	    exit(1);
	}
	if(write_it) {
	    start_info(info, filehdr.rlen, filehdr.dlen);
	    start_data();
	    pit_wrfile(filehdr.dlen, decode);
	    data_crc = (*updcrc)(INIT_CRC, out_buffer, filehdr.dlen);
	    start_rsrc();
	    pit_wrfile(filehdr.rlen, decode);
	    data_crc = (*updcrc)(data_crc, out_buffer, filehdr.rlen);
	    if(verbose) {
		if(decode == nocomp) {
		    printf("\tNo compression\n");
		} else {
		    printf("\tHuffman compressed (%4.1f%%)\n",
			    100.0 * bytes_read / bytes_written);
		}
	    }
	    crc = (gethuffbyte(decode) & BYTEMASK) |
	     ((gethuffbyte(decode) & BYTEMASK) << 8);
	    if(crc != data_crc) {
		fprintf(stderr,
		    "CRC error in file: need 0x%04x, got 0x%04x\n",
		    crc, data_crc);
		exit(1);
	    }
	    end_file();
	} else {
	    pit_skip(filehdr.dlen);
	    pit_skip(filehdr.rlen);
	}
    }
}

