#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <jpeglib.h>
#include <setjmp.h>


int main(int argc, char* argv[])
{
/******************************************************************************************************/
/*                                     Begin Variable Initialization                                  */
/******************************************************************************************************/

    FILE *ifp;
    u_int16_t *Amplitude,i;
    typedef struct eWavHead 
    {
	u_int64_t Channels;            /* number of channels stored in file */
	u_int64_t WFD_Offset;          /* Offset in bytes from beginning of file to first eWav File Directory */
    } eWavHead;                     /* 16 bytes */
    
    typedef struct ChannelHeader 
    {
	float ResX;                 /* Image resolution in dots/cm */
	float RexY;                 /* Image resolution in dots/cm */
	double Scale_mm_sec;
	double Scale_mv_cm;
	u_int32_t Samples;
   } ChannelHeader;

    eWavHead FileHeader;
    ChannelHeader ch;
    u_int16_t max,min;


    JSAMPLE * image_buffer;  /* Points to large array of R,G,B-order data */
    int image_height;        /* Number of rows in image */
    int image_width;         /* Number of columns in image */
    int image_float;
    
    /* This struct contains the JPEG compression parameters and pointers to
     * working space (which is allocated as needed by the JPEG library).
     * It is possible to have several such structures, representing multiple
     * compression/decompression processes, in existence at once.  We refer
     * to any one struct (and its associated working data) as a "JPEG object".
     */
    struct jpeg_compress_struct cinfo;
    /* This struct represents a JPEG error handler.  It is declared separately
     * because applications often want to supply a specialized error handler
     * (see the second half of this file for an example).  But here we just
     * take the easy way out and use the standard error handler, which will
     * print a message on stderr and call exit() if compression fails.
     * Note that this struct must live as long as the main JPEG parameter
     * struct, to avoid dangling-pointer problems.
     */
    struct jpeg_error_mgr jerr;
    /* More stuff */
    FILE * outfile;               /* target file */
    JSAMPROW row_pointer[1];      /* pointer to JSAMPLE row[s] */
    int row_stride;               /* physical row width in image buffer */
    int j,x,y;
    float xpixline,ypixline,xstep,ystep;
    int bottom, top, last;

/******************************************************************************************************/
/*                                      End Variable Initialization                                   */
/******************************************************************************************************/


    ifp = fopen(argv[1], "rb");
    fread(&FileHeader,sizeof(eWavHead),1,ifp);
    fread(&ch,sizeof(ChannelHeader),1,ifp);

    printf("Channels:%d, Offset:%d\n",(int)FileHeader.Channels,(int)FileHeader.WFD_Offset);
    printf("X resolution: %f, Y resolution: %f, cm/sec: %f, Millivolts/cm: %f, Samples:%d\n",
	   ch.ResX,ch.RexY,ch.Scale_mm_sec/10,ch.Scale_mv_cm,(int)ch.Samples);

    image_height=1.5*(max-min);
    if (4096>ch.Samples)
	image_width=ch.Samples;
    else
	image_width=4096;
    image_float=0.25*(max-min);

    Amplitude=(u_int16_t *)calloc(image_width,sizeof(u_int16_t));

    fread(Amplitude,sizeof(u_int16_t),image_width,ifp);

    fclose(ifp);
    max=min=Amplitude[0];
    for(i=0;i<image_width;i++)
    {
//	printf("X=%d, Y=%d\n",i,Amplitude[i]);
	if (Amplitude[i]>max)
	    max=Amplitude[i];
	if (Amplitude[i]<min)
	    min=Amplitude[i];

    }
    
    printf("Max amp=%d, Min amp=%d\n",max,min);
    printf("Pixels/sec:%f, Pixels/mVolt:%f\n",ch.ResX*ch.Scale_mm_sec/10,ch.RexY*ch.Scale_mv_cm);

    xpixline=(ch.ResX*ch.Scale_mm_sec/10)/5;
    ypixline=(ch.RexY*ch.Scale_mv_cm);

    printf ("xpixline=%f, ypixline=%f\n",xpixline,ypixline);
    /*===============================================*/

    xstep=image_width/xpixline;
    ystep=image_height/ypixline;
    printf("xstep=%f, ystep=%f\n",xstep,ystep);

    /* Generate image space */
    image_buffer=calloc(image_height*image_width,sizeof(u_int8_t));

    /* Clear image */
    for(x=image_width-1;x>=0;x--)
	for(y=image_height-1;y>=0;y--)
		image_buffer[y*image_width+x]=255;

    /* Draw vertical grid lines */
    for (x=0;x<=(int)(xstep);x++)
	for (y=0;y<image_height;y++)
	{
	    image_buffer[y*image_width+((int)floor(x*xpixline))]=200;
	    image_buffer[y*image_width+((int)floor(x*xpixline))+1]=200;
	}

    /* Draw horizontal grid lines */
    for (y=0;y<=(int)(ystep);y++)
	for (x=0;x<image_width;x++)
	{
	    image_buffer[(int)floor(y*ypixline)*image_width+x]=200;
	    image_buffer[((int)floor(y*ypixline)+1)*image_width+x]=200;
	}

    /* Draw Signal */
    
    last=Amplitude[0];
    for (x=1;x<image_width-1;x++)
    {
	bottom=-2;
	top=2;

        /* This makes the line at least 5 pixels wide. */
	/* if the datapoints are seperated by more than 2 pixels, the line is made */
	/* wider by the corresponding number of pixels. */
	if (last-Amplitude[x]<bottom) 
	    bottom=last-Amplitude[x]-2;
	if (last-Amplitude[x]>top)
	    top=last-Amplitude[x]+2;
//	printf("Last=%d, current=%d, Bottom=%d, Top=%d\n",last,Amplitude[x],bottom,top);
	last=Amplitude[x];
	for (y=bottom;y<=top;y++)
	    for (j=-1;j<=1;j++)
		image_buffer[(image_height-(Amplitude[x]-min+image_float+y))*image_width+x+j]=0;
    }
		
    /*===============================================*/
    /* Step 1: allocate and initialize JPEG compression object */
    
    /* We have to set up the error handler first, in case the initialization
     * step fails.  (Unlikely, but it could happen if you are out of memory.)
     * This routine fills in the contents of struct jerr, and returns jerr's
     * address which we place into the link field in cinfo.
     */
    cinfo.err = jpeg_std_error(&jerr);
    /* Now we can initialize the JPEG compression object. */
    jpeg_create_compress(&cinfo);
    
    /* Step 2: specify data destination (eg, a file) */
    /* Note: steps 2 and 3 can be done in either order. */
    
    /* Here we use the library-supplied code to send compressed data to a
     * stdio stream.  You can also write your own code to do something else.
     * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
     * requires it in order to write binary files.
     */
    if ((outfile = fopen(argv[2], "wb")) == NULL) {
	fprintf(stderr, "can't open %s\n", argv[2]);
	exit(1);
    }
    jpeg_stdio_dest(&cinfo, outfile);
    /* Step 3: set parameters for compression */
    
    /* First we supply a description of the input image.
     * Four fields of the cinfo struct must be filled in:
     */
    cinfo.image_width = image_width;      /* image width and height, in pixels */
    cinfo.image_height = image_height;
    cinfo.input_components = 1;           /* # of color components per pixel */
    cinfo.in_color_space = JCS_GRAYSCALE;       /* colorspace of input image */
    /* Now use the library's routine to set default compression parameters.
     * (You must set at least cinfo.in_color_space before calling this,
     * since the defaults depend on the source color space.)
     */
    jpeg_set_defaults(&cinfo);
    /* Now you can set any non-default parameters you wish to.
     * Here we just illustrate the use of quality (quantization table) scaling:
     */
    jpeg_set_quality(&cinfo, atoi(argv[3]), TRUE /* limit to baseline-JPEG values */);
    
    /* Step 4: Start compressor */
    
    /* TRUE ensures that we will write a complete interchange-JPEG file.
     * Pass TRUE unless you are very sure of what you're doing.
     */
    jpeg_start_compress(&cinfo, TRUE);
    
    /* Step 5: while (scan lines remain to be written) */
    /*           jpeg_write_scanlines(...); */
    
    /* Here we use the library's state variable cinfo.next_scanline as the
     * loop counter, so that we don't have to keep track ourselves.
     * To keep things simple, we pass one scanline per call; you can pass
     * more if you wish, though.
     */
    row_stride = image_width * 1; /* JSAMPLEs per row in image_buffer */
    
    while (cinfo.next_scanline < cinfo.image_height) {
	/* jpeg_write_scanlines expects an array of pointers to scanlines.
	 * Here the array is only one element long, but you could pass
	 * more than one scanline at a time if that's more convenient.
	 */
	row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
	(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
    }
    
    /* Step 6: Finish compression */
    jpeg_finish_compress(&cinfo);
    /* After finish_compress, we can close the output file. */
    fclose(outfile);
    
    /* Step 7: release JPEG compression object */
    
    /* This is an important step since it will release a good deal of memory. */
    jpeg_destroy_compress(&cinfo);
    
    /* And we're done! */



    exit(0);
}