#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define WORD(x,y) (file[(x)+2*(y)] + (file[(x)+1+2*(y)] << 8))

#define COUNTRY(x) WORD(25+(x)*14, 1)
#define CODEPAGE(x) WORD(25+(x)*14, 2)
#define DATA(x) WORD(25+(x)*14, 5)
#define NBVARS(x) WORD(DATA(x), 0)
#define VARVER(x,y) WORD(DATA(x), y*4+1)
#define VARID(x,y) WORD(DATA(x), y*4+2)
#define VARVAL(x,y) WORD(DATA(x), y*4+3)


int codepage[]= { 437, 850, 852, 860, 863, 865 };

void main(int argc, char **argv)
{
    int i,j,k, base;
    unsigned char file[65536];
    int filesize;
    unsigned short records;
    int y;

    int country=0, codepage=0, id=0, offset=0, length=0;

    if(argc != 1 && argc != 6) {
	fprintf(stderr,"Usage: %s country codepage var-id offset length\n",
		argv[0]);
    }
    if(argc == 6) {
	country = strtoul(argv[1], 0, 10);
	codepage = strtoul(argv[2], 0, 10);
	id = strtoul(argv[3], 0, 0);
	offset = strtoul(argv[4], 0, 0);
	length = strtoul(argv[5], 0, 0);
    }

    filesize = read(0, file, 65536);
    if(filesize<0) {
	perror("read");
	exit(1);
    }
    
    records = WORD(23,0);

    /* first pass: gather minimum address */
    for(i=0; i<records; i++) {
	if(argc == 1) {
	
	    printf("record %d: (country=%03d, codepage=%d data=0x%04x)\n", i,
		   COUNTRY(i), CODEPAGE(i), DATA(i));
	    y=0;
	    for(y=0; y < NBVARS(i); y++)
		printf(" %d: version=%d id=%d val=%s\n", y,
		       VARVER(i, y), VARID(i, y), file + 1 + VARVAL(i,y));
	} else {
	    if(country == COUNTRY(i) && codepage == CODEPAGE(i)) {
		for(y=0; y < NBVARS(i); y++) {
		    if(id == VARID(i,y)) {
			base = VARVAL(i,y) + offset;
			j = base;
			while(j < length + base) {
			    for(k=0; k<16; k++)
				printf("%02x ", file[j + k]);
			    printf("  ");
			    for(k=0; k<16; k++) {
				if(file[j+k] > ' ')
				    printf("%c", file[j + k]);
				else
				    printf(".");
			    }
			    printf("\n");
			    j+= 16;
			}
		    }
		}
	    }
	}
    }
    exit(0);
}

