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


FILE	*fi;			/* input  File stream pointer	*/
FILE	*foASCII;		/* output ASCII file	*/

/*-----------------------------------------------------------------*/
/*		MAIN		MAIN		MAIN		   */
/*-----------------------------------------------------------------*/

int
main(int argc, char* argv[])
{
  char fnam[256];
  char *p;
  int i=0;
/* for ASCII file output only */
  char fnamASCII[256];
  unsigned char endoffile=0;
  unsigned char charnow, lastchar, firstnibble, secondnibble, ascii_first, ascii_second;
/* for ASCII file output only */

  if (argc != 2) {
    fprintf(stderr, "Please provide a JPEG file as argument.\n");
    exit(0);
  }

  /* Check for presence of .jpg file extension: */
  if ((p = strrchr(argv[1], '.')) && !strcmp(p, ".jpg"))
    /* Indeed such extension; remove it: */
    *p = '\0';
  sprintf(fnam, "%s.jpg", argv[1]);

  fi = fopen(fnam,"rb");
  if (fi == NULL) {
    fprintf(stderr, "Could not open input file %s.\n", fnam);
    exit(0);
  }

/* binary to ascii */
  sprintf(fnamASCII, "%s", "ASCII");
  foASCII=fopen(fnamASCII,"wb");
  while ( endoffile==0 ) {
	charnow = fgetc(fi);
    firstnibble=(charnow & 0xf0)>>4;
    secondnibble=(charnow & 0x0f);
	if (firstnibble <=0x09 ) ascii_first = 0x30 | firstnibble;
	else ascii_first= (0x40 | firstnibble)-0x09;
	if (secondnibble <=0x09 ) ascii_second = 0x30 | secondnibble;
	else ascii_second= (0x40 | secondnibble)-0x09;
	fprintf(foASCII, "%s","0x");
	fprintf(foASCII, "%c",ascii_first);
	fprintf(foASCII, "%c,",ascii_second);
	i++;
	if (i%8 ==0)	fprintf(foASCII, "\n");
	if ((lastchar == (unsigned char)0xff) && (charnow == (unsigned char)0xD9)) 
		endoffile=1;
    else 
		lastchar = charnow;
  }
  
  fclose(foASCII);
  fclose(fi);
}
