#include <stdio.h>
#include <stdlib.h>
#include <fcntl.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

/*
gcc -O2 -o view vf.c -L../drv -lqcdrv -L../gfx -lqcgfx -lvga
or if you put
/home/wearcomp/viewFinder/src/qcam-0.9pre6/src/gfx and drv .a files in
current working directory
gcc -O2 -o view vf.c -L. -lqcdrv -lqcgfx -lvga

Not used anymore:
include "qcam_gfx.h"
*/

void main (void) {

  scanbuf *scanBuf;
  struct qcam *q;
  extern int image_width, image_height, image_quality;
  int j, shift, gridsize;

  char *video_buff;
  int i;
  int k = 0; /* k is frame counter */
  char filename[ 80 ];

  FILE *fpSnapShot;

  /* set decent image quality for JPEG compression */
  image_quality = 50;

  /* 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);

	  
  if (qc_open (q)) {	/* locking QCAM device */
    fprintf (stderr, "An error occured opening QCAM.\n");
    exit (-1);
  }



  while(1) {

    /* check if mouse button pressed */
    mouse_update(); /* check to see if mouse pressed */
 
    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, "./v%03d.jpeg", k );
        fpSnapShot = fopen( filename, "w" ); 
        /*      qc_writepgm( q, fpSnapShot, buf ); */

        for (j=0;j<gridsize;j++) {
          scanBuf[j] = scanBuf[j] << shift;
        }

        write_JPEG_file((JSAMPLE *) scanBuf, fpSnapShot);	
        fclose( fpSnapShot );
        k++ ; /* increment frame counter */
        }
    }
    memcpy( video_buff, scanBuf, DIM_X * DIM_Y );

    free (scanBuf);		/* release memory */

  }


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