#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

static unsigned long parseint(unsigned char *p) {
	return    (unsigned long)p[0]
		| (unsigned long)p[1] << 8
		| (unsigned long)p[2] << 16
		| (unsigned long)p[3] << 24;
}

int main(int argc, char **argv) {
    FILE * wad;
    unsigned char header[12];
    unsigned long entries,doffset;

    if(argc != 2) {
        fprintf(stderr,"usage: %s wadfile\n",argv[0]);
        return 1;
    }
    if(NULL == (wad = fopen(argv[1], "rb"))) {
        fprintf(stderr,"cannot open %s: %s\n",argv[1],strerror(errno));
        return 1;
    }
    if(1 != fread(header,12,1,wad)) {
        fprintf(stderr,"failed to read 12 bytes from %s\n", argv[1]);
        return 1;
    }
    if(strncmp((const char *)header+1,"WAD",3)) {
        fprintf(stderr,"%s is not a WAD file\n",argv[1]);
        return 1;
    } else switch(header[0]) {
        case 'I':
        case 'P':
            printf("%s: %cWAD ",argv[1],header[0]);
            break;
        default:
            fprintf(stderr,"%s is not a WAD file\n",argv[1]);
            return 1;
    }

    entries = parseint(header+4);
    doffset = parseint(header+8);

    printf("containing %lu entries, directory at offset %lu\n",
	    entries,doffset);

    fclose(wad);
    return 0;
}
