/* -------------------------------------------- */
/* Hexdump-Generator V.1.0            19.12.96  */
/* -------------------------------------------- */
/* Usage: convert sourcefile [destfile]         */
/*												*/
/* Klaus Schmitt: k_schmit@informatik.uni-kl.de */
/* -------------------------------------------- */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* #include <conio.h> */

#define MAX_FNAME_LENGTH 132


static void FatalError (char *identifier)
{
  fprintf(stderr, "Fatal Error: %s\n",identifier);
  /* getch(); */
  exit(-1);
}

int main(int argc, char* argv[])
{
	long num_write=0;
	long size=0;
    unsigned char buffer;
	char fname_s[MAX_FNAME_LENGTH];         /* Source  */
    char fname_d[MAX_FNAME_LENGTH];         /* Destination */
    FILE *fp_s, *fp_d;

    if (argc < 2)
	{
		printf("Usage: %s infile [outfile]\n", argv[0]);
		/* getch(); */
		return 0;
	}

	if (argc = 2)
	{
		strcpy(fname_s, argv[1]);
		strcpy(fname_d, "hexdump.txt");
	}
	else
	{
		strcpy(fname_s, argv[1]);
		strcpy(fname_d, argv[2]);
	}
	
	printf("Converting: %s to %s ...\n", fname_s, fname_d);
 
	if ((fp_s = fopen(fname_s,"rb")) == NULL)
        FatalError("ERROR: could not open Source");    
	if ((fp_d = fopen(fname_d,"wt")) == NULL)
        FatalError("ERROR: could not create Destination-File");

    /* Schreibe Sampledatei als Hexdump in das File */
	fseek(fp_s,0l,SEEK_END) ;
    size = ftell(fp_s) ;
    fseek(fp_s,0l,SEEK_SET) ;
	
	for(num_write=0; num_write < size; num_write++)
    {
		fread(&buffer, 1, 1, fp_s);
						
		if (num_write%16 == 0)
        {
			if (num_write < size - 1)
            {
				if (fprintf(fp_d, "	dc.b	0x%02X,",buffer) < 0)
					FatalError("write failed");
            }
            else
            {
				if (fprintf(fp_d, "	dc.b	0x%02X",buffer) < 0)
					FatalError("write failed");
            }
		}
        else if (num_write%16 == 15)
        {
			if (fprintf(fp_d, "0x%02X\n",buffer) < 0)
				FatalError("write failed");
        }
        else
        {
			if (num_write < size - 1)
            {
				if (fprintf(fp_d, "0x%02X,",buffer) < 0)
					FatalError("write failed");
            }
            else
            {
	            if (fprintf(fp_d, "0x%02X",buffer) < 0)
			        FatalError("write failed");
            }
        }
    }
    printf("%li Bytes written\n", num_write);    

	if ((fclose(fp_s)==0) && (fclose(fp_d)==0))
		printf("Hexdump created!\n");
	else
		FatalError("Closing failed!");
    
}



