/*********************************************************
 *
 * Captures images from a CANON IXUS in remote control mode.
 * Written January 2004 by Nick Fankhauser.
 *
 * Based on CARMEN Canon module by Mike Montemerlo
 *
 ********************************************************/
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <termios.h> 
#include "canon.h" 
#define MAXDIG 6 
static struct termios orig, new;
static int peek = -1;

int main(int argc, char *argv[]) {
	usb_dev_handle *ixus;FILE *ifile;
	unsigned char **image;int *image_length;
	unsigned char **thumb;int *thumb_length;
	int run=1,err,cnt=0,ch=0,interval,k;
	char fn[30],zahl[10],comm[50],zahlo[10];
	if (argc<3) {printf("Syntax: ixus_capture <prefix> <interval [s]>\n");exit(1);}
	interval=atoi(argv[2]);printf("Interval: %d\n",interval);
	printf("-> Press q to quit!\n");
	ixus=canon_open_camera();if (ixus==NULL) {exit(1);}
	canon_initialize_camera(ixus);canon_rcc_init(ixus);
	canon_initialize_capture(ixus,FULL_TO_PC,FLASH_OFF);
	tcgetattr(0,&orig);new=orig;new.c_lflag&=~ICANON;
  	new.c_lflag&=~ECHO;new.c_lflag&=~ISIG;
  	new.c_cc[VMIN]=1;new.c_cc[VTIME]=0;
  	tcsetattr(0, TCSANOW, &new);
	mkdir(argv[1],0777);
	while (run) {
		image=malloc(1000000);thumb=malloc(100000);
		image_length=malloc(sizeof(int));thumb_length=malloc(sizeof(int));
		err=canon_capture_image(ixus,thumb,thumb_length,image,image_length);
		if (!err==0) {run=0;interval=0;}
		cnt++;strcpy(fn,argv[1]);strcat(fn,"/");strcat(fn,argv[1]);
		sprintf(zahl,"%d",cnt);strcpy(zahlo,"");
		for (k=0;k<MAXDIG-strlen(zahl);k++) {strcat(zahlo,"0");}
		strcat(zahlo,zahl);strcat(fn,zahlo);strcat(fn,".jpg");
		ifile=fopen(fn,"w");
		if (ifile==NULL) {printf("Failed to create %s!\n",fn);exit(1);}
		printf("Writing %d bytes to %s (E%d)...\n",*image_length,fn,err);
		fwrite(*image,*image_length,1,ifile);fclose(ifile);
		free(image);free(image_length);free(thumb);free(thumb_length);
		for (k=0;k<interval;k++) {
			sleep(1);
			if(kbhit()) {
				ch=readch();
				if (ch=='q') {k=interval;run=0;}
				
			}
		}
	}
	tcsetattr(0,TCSANOW, &orig);
	canon_stop_capture(ixus);canon_rcc_exit(ixus);
	canon_close_camera(ixus);return 0;
}

int kbhit() {
  char ch;int nread;
  if(peek!=-1) return 1;
  new.c_cc[VMIN]=0;tcsetattr(0,TCSANOW,&new);
  nread=read(0,&ch,1);new.c_cc[VMIN]=1;
  tcsetattr(0,TCSANOW,&new);
  if(nread==1) {peek=ch;return 1;}
  return 0;
}

int readch(void) {
	char ch;
	if(peek!=-1) {ch=peek;peek=-1;return ch;}
  	read(0,&ch,1);return ch;
}