#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char uchar;
typedef unsigned short int mot;	//(16 bits suffisent)
#define MAX 0xFF		// taille de la memoire
mot memoire[MAX];
mot co;

// une procedure pour tester :
// ./a.out -t produit un fichier binaire test
// observer le contenu avec hexdump -x test
// verifier la formation des mots avec
// ./a.out test

void mktest(void)
{
    FILE *dst;
    char prog[] = "\x01\x23\x45\x67\x89\xAB\xCD\xEF";
    // ici, il faudrait ecrire un vrai programme !
    dst = fopen("test", "w");
    fwrite(prog, sizeof(char), strlen(prog), dst);
    fclose(dst);
    exit(0);
}

mot chargement(FILE * src)
{
    uchar octet;
    mot w = 0;
    int nbo = 0, nbw = 0;
    mot co;
    int flag = 0;
    while (!feof(src)) {
	if (flag == 0) {
	    fread(&octet, 1, sizeof(uchar), src);
	    w = octet;
	    nbo++;
	    fread(&octet, 1, sizeof(uchar), src);
	    w = (w << 4) + (octet >> 4);
	    nbo++;
	} else {
	    w = octet & 0xF;
	    fread(&octet, 1, sizeof(uchar), src);
	    w = (w << 8) + octet;
	    nbo++;
	}
	flag ^= 1;
	if (nbw > 1)
	    memoire[nbw - 1] = w;
	else
	    co = w;
	printf("\nadresse %3d: %X %X %X", nbw, (w & 0xF00) >> 8,
	       (w & 0x0F0) >> 4, w & 0xF);
	nbw++;
    }
    // juste un controle :
    printf("\nNombre d'octets lu : %d", nbo);
    printf("\nNombre de mots     : %d", nbw);
    printf("\nPoint d'entree     : %d", co);

    return co;
}

void run(void)
{
}

int main(int argc, char *argv[])
{
    FILE *src;
    int opt;
    while ((opt = getopt(argc, argv, "ht")) >= 0) {
	switch (opt) {
	case 'h':
	    fprintf(stderr, "usage %s :", argv[0]);
	    fprintf(stderr, "\n -h filename");
	    exit(0);
	case 't':
	    mktest();
	}
    }
    if (optind == argc) {
	fprintf(stderr, "source ?");
	exit(1);
    }
    src = fopen(argv[optind], "r");
    if (!src) {
	fprintf(stderr, "fichier introuvable!");
	exit(1);
    }

    bzero(&(memoire[0]), MAX);
    co = chargement(src);
    fclose(src);

    run();

    return 0;
}
