/*=========================================================================
    Copyright 2000 James Bruce
    Example program to capture and save images using the capture library
  -------------------------------------------------------------------------
    REVISION HISTORY:
      2000-05-20:  Initial release version - ugly, adapted from
                   something I needed really quickly at some point (JRB)
  =========================================================================*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// CMVision capture library
#include <capture.h>

// The printf format string for output filenames
#define FILE_NAME_STYLE "images/image%03d.ppm"


struct rgb{
  unsigned char red,green,blue;
};

rgb black = {0,0,0};


// These should really be parameters, but aren't yet.
int width  = 320;
int height = 240;
int fmt = V4L2_PIX_FMT_BGR24;
int num = 60;


rgb *buf,*cur,*back;
char file[32];


void swap_rgb(rgb *buf,int len)
{
  int i;
  rgb r;

  for(i=0; i<len; i++){
    r = buf[i];
    buf[i].red  = r.blue;
    buf[i].blue = r.red;
  }
}


int main()
{
  capture cap;
  int i,size;

  char filename[32];
  FILE *file;

  cap.initialize("/dev/video",width,height,fmt);
  size = width*height;
  buf = new rgb[size*num];
  if(!buf) printf("Not enough memory");

  // Initialize mem to bring into core memory
  // Could use mlock, but its the simple 1-thread method for now
  memset(buf,0,size*num*sizeof(rgb));

  // Wait a bit
  printf("Waiting four seconds"); fflush(stdout);
  for(i=0; i<4; i++){
    sleep(1);
    printf("."); fflush(stdout);
  }
  printf("\n");

  // Capture the frames
  printf("Capturing\n");
  for(i=0; i<num; i++){
    cur = (rgb*)cap.captureFrame();
    memcpy(buf + size*i,cur,size*sizeof(rgb));
    // memset(buf + size*i,i*4,size*sizeof(rgb));
    printf("."); fflush(stdout);
  }
  printf("done.\n");

  // Most capture cards are BGR for some reason
  swap_rgb(buf,size*num);

  // Save files to image dir as ppm's
  printf("Writing\n");
  for(i=0; i<num; i++){
    sprintf(filename,FILE_NAME_STYLE,i);
    if(file = fopen(filename,"w")){
      fprintf(file,"P6\n%d %d\n255\n",width,height);
      fwrite(buf + size*i,sizeof(rgb),size,file);
      fclose(file);
      printf("."); fflush(stdout);
    }
  }
  printf("done.\n");

  return(0);
}