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

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

int sit_filehdr(f, skip)
struct fileHdr *f;
int skip;
{
    register int i;
    unsigned long crc;
    int n;
    char hdr[FILEHDRSIZE];
    char ftype[5], fauth[5];

    for(i = 0; i < INFOBYTES; i++) {
	info[i] = '\0';
    }
    if(fread(hdr, 1, FILEHDRSIZE, infp) != FILEHDRSIZE) {
	fprintf(stderr, "Can't read file header\n");
	return -1;
    }
    crc = INIT_CRC;
    crc = (*updcrc)(crc, hdr, FILEHDRSIZE - 2);

    f->hdrCRC = get2(hdr + F_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[F_FNAME] & BYTEMASK;
    if(n > F_NAMELEN) {
	n = F_NAMELEN;
    }
    info[I_NAMEOFF] = n;
    copy(info + I_NAMEOFF + 1, hdr + F_FNAME + 1, n);
    transname(hdr + F_FNAME + 1, text, n);

    f->compRMethod = hdr[F_COMPRMETHOD];
    f->compDMethod = hdr[F_COMPDMETHOD];
    f->rsrcLength = get4(hdr + F_RSRCLENGTH);
    f->dataLength = get4(hdr + F_DATALENGTH);
    f->compRLength = get4(hdr + F_COMPRLENGTH);
    f->compDLength = get4(hdr + F_COMPDLENGTH);
    f->rsrcCRC = get2(hdr + F_RSRCCRC);
    f->dataCRC = get2(hdr + F_DATACRC);

    write_it = !skip;
    if(list && !skip) {
	if(f->compRMethod != efolder) {
	    for(i = 0; i < indent; i++) {
		(void) putchar(' ');
	    }
	}
	if(f->compRMethod == sfolder) {
	    printf("folder=\"%s\"", text);
	} else if(f->compRMethod != efolder) {
	    transname(hdr + F_FTYPE, ftype, 4);
	    transname(hdr + F_CREATOR, fauth, 4);
	    printf("name=\"%s\", type=%4.4s, author=%4.4s, data=%ld, rsrc=%ld",
		   text, ftype, fauth, f->dataLength, f->rsrcLength);
	}
	if(info_only) {
	    write_it = 0;
	}
	if(f->compRMethod != efolder) {
	    if(query) {
		write_it = do_query();
	    } else {
		(void) putchar('\n');
	    }
	}
    }


    if(write_it) {
	define_name(text);

	copy(info + I_TYPEOFF, hdr + F_FTYPE, 4);
	copy(info + I_AUTHOFF, hdr + F_CREATOR, 4);
	copy(info + I_FLAGOFF, hdr + F_FNDRFLAGS, 2);
	copy(info + I_DLENOFF, hdr + F_DATALENGTH, 4);
	copy(info + I_RLENOFF, hdr + F_RSRCLENGTH, 4);
	copy(info + I_CTIMOFF, hdr + F_CREATIONDATE, 4);
	copy(info + I_MTIMOFF, hdr + F_MODDATE, 4);
    }
    return 1;
}

