/*
 *  TestCapture.cpp
 *  OpenCV
 *
 */



#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <iostream>


using namespace std;

const char  * WINDOW_NAME  = "Playback" ;

int usingCamera; 

int main (int argc, char * const argv[]) 
{	
	int key=0;
	CvCapture* camera = NULL; 
	
	if (argc < 2) {
		cout << "Getting Camera " << CV_CAP_ANY << endl; 	
		camera = cvCreateCameraCapture (CV_CAP_ANY);
		usingCamera = 1; 
	} else {
		if (argv[1][0] == '-') {
			cout << "An simple program to display a video or camera output." << endl << endl
			<< "Usage: " << endl << "    >> TestCapture [optional-path-to-movie-file]" << endl << endl 
			<< "If no optional path to a movie file is provided, attempts to use an attached" << endl 
			<< "    camera for input. Otherwise, attempts to use the movie file for input." << endl << endl; 
			return 0; 
		}
		cout << "Getting Movie " << argv[1] << endl; 
		camera = cvCreateFileCapture(argv[1]); 
		usingCamera = 0; 
	}
	
    if (! camera) {
		cout << "Failed to get input from a video capture source." << endl << endl
		<< "Usage: " << endl << "    >> TestCapture [optional-path-to-movie-file]" << endl << endl 
		<< "If no optional path to a movie file is provided, attempts to use an attached" << endl 
		<< "    camera for input. Otherwise, attempts to use the movie file for input." << endl << endl; 
		return 0; 
	}
	
    cvNamedWindow (WINDOW_NAME, CV_WINDOW_AUTOSIZE); 
    
    IplImage *  current_frame = cvQueryFrame (camera);
	
	while (key != 'q' && key != 'Q') { //Loop until user enters 'q'
    
		
		current_frame = cvQueryFrame (camera); 
		
		if (current_frame==NULL) { //implies reached camera end
			cvSetCaptureProperty(camera, CV_CAP_PROP_POS_FRAMES, 0); //reset camera to beginning
			current_frame = cvQueryFrame (camera) ; 
			if (current_frame==NULL) //shouldn't happen
				break; 
		}		
		
		cvShowImage(WINDOW_NAME, current_frame);
	}
	cvReleaseCapture(&camera);
	cvReleaseImage(&current_frame); 
}
