#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include<string.h>
#include "qcam.h"
#include "qcamip.h"
#include <jpeglib.h>
#include "writejpeg.h"

#include <vga.h>
#include <vgamouse.h>
#include <vgakeyboard.h>

#define DIM_X 320
#define DIM_Y 200

/*
with libqcam.a and libqcamip.a files in
current working directory
gcc -O2 -o view vfj.c writejpeg.c -L. -lqcam -lqcamip -lvga -ljpeg

*/

void main (int argc, char* argv[]) {

  scanbuf *scanBuf;
  struct qcam *q;
  extern int image_width, image_height, image_quality;
  int j, shift, gridsize;
  int qbright,qwbal;
  char *video_buff;
  int i;
  int k; /* k is frame counter */
  char filename[ 80 ];
  int mousex,mousey;
  FILE *fpSnapShot;

  /* set decent image quality for JPEG compression */
  image_quality = 50;
  if(argc ==1) k = 0;
  else if(argc == 2){
      k = atoi(argv[1]);
  }
  else{printf("useage: viewthing [framenumber]\n");}
  /* SVGAlib mouse init */
  vga_setmousesupport( 1 );

  /* configure SVGAlib */
  vga_init();
  vga_setmode( G320x200x256 );
  video_buff = vga_getgraphmem();

  /* set up greyscale palette */
  vga_waitretrace();
  for( i = 0; i < 64; i++ ) {
    vga_setpalette( i, i, i, i );
  }
  for( i = 64; i < 128; i++ ) {
    vga_setpalette( i, i, 0, 0 );
  }
  for( i = 128; i < 192; i++ ) {
    vga_setpalette( i, 0, i, 0 );
  }
  for( i = 192; i < 255; i++ ) {
    vga_setpalette( i, 0, 0, i );
  }


  q = qc_init ();		/* set built in defaults, init qcam pointer */
  qc_initfile (q, NULL);	/* read defaults from file */

  /* Dimensions of our image- useful later */
  image_width = qc_getwidth(q) / qc_gettransfer_scale(q);
  image_height = qc_getheight(q) / qc_gettransfer_scale(q);
  gridsize = image_width * image_height;
  shift = BITS_IN_JSAMPLE - qc_getbitdepth(q);

  /* Prevent segmentation fault if qcam is on an unsupported resolution */
  if ((image_width < 320) || (image_height < 200)) {
    fprintf (stderr, "QCAM resolution must be set to at least 320X200 - change /usr/local/etc/qcam.conf\n");
    fprintf (stderr, "QCAM resolution is currently set to %i X %i\n",image_width,image_height);
    exit (-1);
  }
	  
  if (qc_open (q)) {	/* locking QCAM device */
    fprintf (stderr, "An error occured opening QCAM.\n");
    exit (-1);
  }
  mouse_update();
  mousex = mouse_getx();
  mousey = mouse_gety();
  qbright = qc_getbrightness(q);
  qwbal = qc_getwhitebal(q);

  while(1) {

    /* check if mouse button pressed */
    mouse_update(); /* check to see if mouse pressed */
    if((mousex - mouse_getx()) < 0){
	    qc_setbrightness(q, qbright +5);
	    qbright += 5;
    }
    else if((mousex - mouse_getx()) > 0){
	    qc_setbrightness(q, qbright - 5);
	    qbright -= 5;
    }

    if((mousey - mouse_gety()) < 0){
	    qc_setwhitebal(q, qwbal +5);
	    qwbal += 5;
    }
    else if((mousey - mouse_gety()) > 0) {
	   qc_setwhitebal(q, qwbal -5);
	   qwbal -= 5;
    }
    mouse_setposition(mousex = 100, mousey = 100);
    qc_set (q);		/* reset, set SendFrameMode, init QCAM */
    scanBuf = qc_scan (q);	/* get a frame from QCam */

    /* check if mouse button pressed */
    /* moved up before frame grabbing   mouse_update(); */
    if( 0 != mouse_getbutton ) {
      if( ( mouse_getbutton() & MOUSE_LEFTBUTTON ) && ! ( mouse_getbutton() & MOUSE_RIGHTBUTTON ) ) {
        sprintf( filename, "./e%04d.jpg", k );
        fpSnapShot = fopen( filename, "w" ); 

	/*  Correction to prevent dark pictures (I think) */
        for (j=0;j<gridsize;j++) {
          scanBuf[j] = (scanBuf[j] << shift)|scanBuf[j];
        }

        write_JPEG_file((JSAMPLE *) scanBuf, fpSnapShot);	
        fclose( fpSnapShot );
        k++ ; /* increment frame counter */
        }
      if( ( mouse_getbutton() & MOUSE_RIGHTBUTTON ) && ! ( mouse_getbutton() & MOUSE_LEFTBUTTON ) ) {
	system("./sendPics &");
      }
    }
	

/* By using the modified scanBuf (corrected to prevent dark pictures), we get a bit of a flash on the screen whenever a picture is taken.  This could be prevented by using a separate scanbuf for the screen, but I kind of like the feedback of a "flash" */

/* WARNING: This line causes a segmentation fault if the qcam is not set to 320X200 or greater resolution.  We should copy line by line and add black to the end of each line if it doesn't fill the whole screen.  Maybe later.  Once I have time to see if there's a performance hit.. (probably not since the parallel port is so slow..) */

    memcpy( video_buff, scanBuf, DIM_X * DIM_Y );

    free (scanBuf);		/* release memory */

  }


  qc_close (q);		/* clear locks */
}

