/**
* Visão Computacional e Realidade Aumentada
*
* CornerDetector
* Aluno: Daniel Ribeiro Trindade
*/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "cvcam.h"
#include "cv.h"
#include "highgui.h"

//double quality_level = 0.00001;
double min_distance = 0.01;
double k = 0.04;
//int int_quality_level = 50000;
//int int_k = 4;

//void qualityLevelCallback( int i ) {
//	quality_level = ( int_quality_level + 1 ) / 1000000.0;
//}
//
//void kCallback( int i ) {
//	k = ( int_k + 1 ) / 100.0;
//}
/************************************************************************
 * 
 ************************************************************************/
int main( int argc, char** argv )
{
  IplImage* in_frame = 0;
  IplImage* gray_image = 0;
  IplImage* eig_image = 0;
  IplImage* temp_image = 0;
  CvCapture* capture = 0;
  CvPoint2D32f corners[150];
  int corner_count = 150;
  int i = 0;
  double width, height;

  // Inicia a captura do video e cria imagens auxiliares
  capture = cvCaptureFromAVI( argv[1] ); 
  in_frame = cvQueryFrame( capture );
  width = cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH );
  height = cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT );
  gray_image = cvCreateImage( cvSize( width, height ), IPL_DEPTH_8U, 1 );
  eig_image = cvCreateImage( cvSize( width, height ), IPL_DEPTH_32F, 1 );
  temp_image = cvCreateImage( cvSize( width, height ), IPL_DEPTH_32F, 1 );

  if( !capture )
  {
    fprintf(stderr,"Could not initialize capturing...\n");
    return -1;
  }

  cvNamedWindow( "in", 0 );
  /*cvCreateTrackbar( "quality_level" , "in", &int_quality_level, 1000000, qualityLevelCallback );
  cvCreateTrackbar( "k" , "in", &int_k, 10, kCallback );*/

  for(;;)
  {
    // Pega um frame do video
    if(!cvGrabFrame(capture)) 
      break;
    in_frame = cvRetrieveFrame(capture);

    // Converte para tons de cinza
    cvCvtColor( in_frame, gray_image, CV_BGR2GRAY );

    // Corner Detection
    cvGoodFeaturesToTrack(  gray_image, eig_image, temp_image, 
                            corners, &corner_count, 
                            atof( argv[2] ), min_distance, 
                            NULL, 3, 1, k );

    // Desenha Cantos
    for(i=0;i<corner_count;i++)
		  cvCircle( in_frame, cvPointFrom32f( corners[i] ), 1, CV_RGB( 255, 255, 0 ), 1, 8, 0 );

    // Mostra a imagem final
    cvShowImage("in", in_frame );

    if( cvWaitKey(10) >= 0 )
      break;
  }

  // Libera a memoria
  cvReleaseCapture( &capture );
  cvReleaseImage( &gray_image );
  cvReleaseImage( &eig_image );
  cvReleaseImage( &temp_image );
  cvDestroyWindow("in");

  return 0;
}