#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>

int mano=1;

FILE *fmano;
FILE *fnomano;

CvRect box;
bool drawing_box = false;

void draw_box( IplImage* img, CvRect rect ) {
	if(mano)
		cvRectangle( img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0xfe,0x00,0x00));
	else
		cvRectangle( img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0x00,0x00,0xfe));
}

void my_mouse_callback(int event, int x, int y, int flags, void* param) {
	IplImage* image = (IplImage*) param;
	switch( event ) {
		case CV_EVENT_MOUSEMOVE: {
			if( drawing_box ) {
				box.width = x-box.x;
				box.height = y-box.y;
			}
		}
			break;
		case CV_EVENT_LBUTTONDOWN: {
			drawing_box = true;
			box = cvRect(x, y, 0, 0);
			if(mano==1){
				fprintf(fmano,"\t(%d,%d)  ",x,y);
			}
			if(mano==0){
				fprintf(fnomano,"\t(%d,%d)  ",x,y);
			}
		}
			break;
		case CV_EVENT_LBUTTONUP: {
			drawing_box = false;
			if(box.width<0) {
				box.x+=box.width;
				box.width *=-1;
			}
			if(box.height<0) {
				box.y+=box.height;
				box.height*=-1;
			}
			if(mano==1){
				fprintf(fmano,"(%d,%d)\n",x,y);
			}
			if(mano==0){
				fprintf(fnomano,"(%d,%d)\n",x,y);
			}
			draw_box(image, box);
		}
			break;
	}
}

void switcher(int position){	
}




int main(int argc, char* argv[]) {

	if(argc!=2){
		printf("Error en la llamada\nFormato: biblotecario.exe <nombre_de_imagen con extension>\n");
		exit(0);
	}
	fopen_s(&fmano,"MANO.txt","a");
	if(fmano==NULL){
		printf("Error en el fichero MANO.txt\n");
		exit(0);
	}

	fopen_s(&fnomano,"NoMANO.txt","a");
	if(fnomano==NULL){
		printf("Error en el fichero NoMANO.txt\n");
		exit(0);
	}

	box = cvRect(-1,-1,0,0);
	//char ext[]=".jpg";
	char name[30];
	strcpy(name,argv[1]);
	//strcat(name,ext);
	IplImage* img = cvLoadImage(name,1);
	if( img==NULL) return (0);
	IplImage* temp = cvCloneImage( img );
	
	fprintf(fmano,"%s\n",name);
	fprintf(fnomano,"%s\n",name);

	uchar *data;
	int height,width;
	int step,channels;					

	
	// Create a window in which the captured images will be presented
	cvNamedWindow( "ventana", CV_WINDOW_AUTOSIZE );
	cvCreateTrackbar("NoMANO/MANO/EXIT","ventana",&mano,2, switcher);

	cvSetMouseCallback("ventana",my_mouse_callback,(void*) img);
		
	// get the image data
	height    = img->height;
	width     = img->width;


	// Show the image captured from the camera in the window and repeat
	while( 1 ) {
		
		cvCopyImage( img, temp );
		if( drawing_box ) draw_box( temp, box );
		cvShowImage("ventana",temp);

		if( (cvWaitKey(10) & 255) == 27  || mano==2) break;
	}

	fclose(fmano);
	fclose(fnomano);
	// Release the capture device housekeeping
	cvReleaseImage(&img);
	cvDestroyWindow( "ventana" );
}

