/*
   x = scion_read();
   
   This function will return a grabbed 640 * 480 image in the
   return variable x.  It is largely derived from the example file
   test-lg3.c that came with the linux driver.
   
   Matlab 5.2 Linux MEX file

   Naveen, 4/18/03
*/

#define DEBUG 0

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <linux/ioctl.h>
#include <unistd.h>
#include "scionlg3.h"
#include "mex.h"

#define DEVICE_NAME "/dev/lg3-0"
#define IMAGE_WIDTH 640
#define IMAGE_HEIGHT 480

static int dev;
static char buffer[IMAGE_WIDTH * IMAGE_HEIGHT];
static int *sec,*usec;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  /* int rgbdims[3]; */
  int rgbdims[2]; 
  unsigned char *rgbbuf;
  int image_size = IMAGE_WIDTH * IMAGE_HEIGHT;


  /* Make sure we got the right number of parameters ---------- */
  if (nrhs > 0)
    mexErrMsgTxt("Huh? I'm supposed to grab a frame. What do you want\n me to do with these parameters?");
  if (nlhs == 0)
    mexErrMsgTxt("Where should I grab the frame to? You need a variable name on the left hand side.");


  /* Now we try to open the camera. --------------------------- */

  if (dev = (open(DEVICE_NAME, O_RDONLY)) < 0)
    mexErrMsgTxt("Couldn't open video device.");

#if DEBUG
 fprintf(stderr, "Scion: Device opened OK\n");
#endif

  /* grab the next available frame */
  ioctl(dev,LG3_GRAB,NON_TRIG);

#if DEBUG
 fprintf(stderr, "Scion: Grab OK\n");
#endif

  /* read and close the device */
  read(dev, buffer, image_size);
#if DEBUG
 fprintf(stderr, "Scion: Read OK\n");
#endif
  close(dev);
#if DEBUG
 fprintf(stderr, "Scion: Close OK\n");
#endif


  /*  At this point the acquired image is in the "buffer"    *
   *  array.  All we have to do is to get it back to matlab  *
   *  We set up rgbbuf to point to the array that the user   *
   *  had sent to us on the left hand side from matlab.      */

 rgbdims[0] = IMAGE_WIDTH;
 rgbdims[1] = IMAGE_HEIGHT;
 /*  rgbdims[2] = 3; */
 plhs[0] = mxCreateNumericArray(2,rgbdims,mxUINT8_CLASS,mxREAL);
 rgbbuf = (unsigned char *) mxGetPr(plhs[0]);

  /* Now all we have to do is to copy buffer into rgbbuf.  *
   * We're  trying out color image return, so we have to   *
   * copy the acquired B&W image into all three buffers    */

#if DEBUG
 fprintf(stderr, "Scion: memcpy start..\n");
#endif

  memcpy (rgbbuf, buffer, image_size);

  /* This stuff if we want to return a color image 
  rgbbuf += image_size;
  memcpy (rgbbuf, buffer, image_size);
  rgbbuf += image_size;
  memcpy (rgbbuf, buffer, image_size);
  */

#if DEBUG
 fprintf(stderr, "Scion: memcpy done.\n\n");
#endif

 return;

}

/* ------------------------------------------------------------- */
