#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

CascadeClassifier face_cascade;

void detectFacialFeatures(Mat frame, Mat face_image, char* img_no)
{
  std::vector<Rect> faces;
  Mat frame_gray;
  

  cvtColor( frame, frame_gray, CV_BGR2GRAY );
  equalizeHist( frame_gray, frame_gray );

  //-- Detect faces
  face_cascade.detectMultiScale( frame_gray, faces, 1.2, 2, 0|CV_HAAR_SCALE_IMAGE);
  printf("\"count\":%i, \"faces\":[",faces.size());
  for( int i = 0; i < faces.size(); i++ )
  {
    if (i > 0)
    {
    printf(",");
    }
    printf("{ \"x\":%i, \"y\":%i, \"width\":%i, \"height\":%i }",faces[i].x, faces[i].y, faces[i].width, faces[i].height);
     ellipse( face_image,
           Point( faces[i].x + (faces[i].width / 2), faces[i].y + (faces[i].height / 2) ),
           Size( faces[i].width / 2, faces[i].height / 2 ),
           0,
           0,
           360,
           Scalar( 0, 0, 0, 255),
           -1,
           8 );

  }
  printf("]");
}

int main( int argc, char** argv )
{
    if (argc < 3)
    {
    	printf("Usage: %s <Path to OpenCV> <Path to image 1> ... <Path to image n>\n", argv[0]);
    	return 1;
    }
    Mat  img;
    std::string cascadeloc = std::string(argv[1]) + "/share/OpenCV/haarcascades/haarcascade_frontalface_alt2.xml";
           
	if( !face_cascade.load(cascadeloc) )
	{ printf("--(!)Error loading Face Cascade\n"); return -1; };
        printf("{");
        printf("\"count\":%i, \"files\":[",argc-2);
        for (int i = 2; i < argc; i++)
        {
        if (i > 2) { printf(",");}
   	printf ("{");       
        img = imread(argv[i], CV_LOAD_IMAGE_COLOR);
        printf("\"file\":\"%s\",",argv[i]);
     	if (!img.empty())
     	{
     	Mat face_image(img.rows, img.cols, CV_8UC4, Scalar(0,0,0,0));
        detectFacialFeatures(img, face_image, argv[i]);
        std::string s = argv[i];
        replace(s.begin(), s.end(), '.', '-');
        if (!face_image.empty())
        {
        	imwrite( s + std::string("-faces.png"), face_image );
        	std::string cmd = "composite " + s + "-faces.png " + argv[i] + " " + s + "-merged.jpg";
        	system(cmd.c_str());
	}
	else
	{
		fprintf(stderr, "File '%s' didn't seem to capture any faces... Not Saving Faces Image\n", argv[i]);
	}
        }
        else
        {
        printf("\"error\":\"File Doesn't exist, or isn't an image.\"");
        }
        printf("}");
        } 
        printf("]}");

    return 0;
}
