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

unsigned long get4();
unsigned short get2();
void copy();

int pit_filehdr(f, compr)
struct pit_header *f;
int compr;
{
    register int i;
    unsigned long crc;
    int n;
    char hdr[HDRBYTES];
    char ftype[5], fauth[5];

    for(i = 0; i < INFOBYTES; i++)
	info[i] = '\0';

    if(compr == DECODE) {
	for(i = 0; i < HDRBYTES; i++) {
	    hdr[i] = gethuffbyte(compr);
	}
    } else {
	if(fread(hdr, 1, HDRBYTES, infp) != HDRBYTES) {
	    return -1;
	}
    }
    crc = INIT_CRC;
    crc = (*updcrc)(crc, hdr, HDRBYTES - 2);

    f->hdrCRC = get2(hdr + H_HDRCRC);
    if(f->hdrCRC != crc) {
	fprintf(stderr, "Header CRC mismatch: got 0x%04x, need 0x%04x\n",
		f->hdrCRC & WORDMASK, crc);
	return -1;
    }

    n = hdr[H_NLENOFF] & BYTEMASK;
    if(n > H_NAMELEN) {
	n = H_NAMELEN;
    }
    info[I_NAMEOFF] = n;
    copy(info + I_NAMEOFF + 1, hdr + H_NAMEOFF, n);
    transname(hdr + H_NAMEOFF, text, n);
    text[n] = '\0';

    f->rlen = get4(hdr + H_RLENOFF);
    f->dlen = get4(hdr + H_DLENOFF);

    write_it = 1;
    if(list) {
	transname(hdr + H_TYPEOFF, ftype, 4);
	transname(hdr + H_AUTHOFF, fauth, 4);
	printf("name=\"%s\", type=%4.4s, author=%4.4s, data=%ld, rsrc=%ld",
		text, ftype, fauth, f->dlen, f->rlen);
	if(info_only) {
	    write_it = 0;
	}
	if(query) {
	    write_it = do_query();
	} else {
	    (void) putchar('\n');
	}
    }


    if(write_it) {
	define_name(text);

	copy(info + I_TYPEOFF, hdr + H_TYPEOFF, 4);
	copy(info + I_AUTHOFF, hdr + H_AUTHOFF, 4);
	copy(info + I_FLAGOFF, hdr + H_FLAGOFF, 2);
	copy(info + I_LOCKOFF, hdr + H_LOCKOFF, 2);
	copy(info + I_DLENOFF, hdr + H_DLENOFF, 4);
	copy(info + I_RLENOFF, hdr + H_RLENOFF, 4);
	copy(info + I_CTIMOFF, hdr + H_CTIMOFF, 4);
	copy(info + I_MTIMOFF, hdr + H_MTIMOFF, 4);
    }
    return 1;
}

