/*
 *  IVCCLIB: Intel Video Capture Card Library
 *  by Jeff Norris, jnorris@alum.mit.edu
 *  
 *  File: writer.c
 *
 *  Description: This is a very simple C observer file.  It 
 *  takes frames and writes them to disk, in ppm format, one 
 *  after another.  One way to start writing C observers is 
 *  to copy this file and start editing it.
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <fstream.h>
#include <unistd.h>
#include "c_ivccsetup.h"
#include "grabber.h"

/* This function simply writes frames to disk in ppm format as
   quickly as possible */
void gotframe(int signum, char* mmbuf)
{
  static long i=0;
  unsigned char *src;
  unsigned char *dest;
  unsigned int count;
  
  count = NUM_ROWS*NUM_COLS*PIXELSIZE;
  int size = NUM_ROWS*NUM_COLS;
  dest =(unsigned char *) malloc(NUM_ROWS*NUM_COLS*PIXELSIZE*sizeof(unsigned char));
  memcpy(dest, mmbuf, count);
  
  char buf[30];
  static int p = 0; p++;
  sprintf(buf,"%dimage%d", signum,p);
  fstream fout;
  fout.open(buf, ios::out); 
  fout << "P6\n" << NUM_COLS << " " << NUM_ROWS << "\n255\n";
  int j = 0;
  for (i = 0,j=0 ; i<size; i++)
    {
      
      j+=1;
      fout.write(&dest[j+1],1); 
      fout.write(&dest[j],1); 
      fout.write(&dest[j-1],1); 
      j+=3;
	
    }
  fout.close();
  
}

void main()
{
  observersetup();
  attachgrabber(0,&gotframe);
  while(1)
    pause;
}
  

