#include <fstream>
#include <FL/Fl.H>
#include <FL/Fl_Shared_Image.H>
#include "EdgeDetection.h"
#include "PROJECT1UI.h"
#include "PROJECT1Doc.h"

PROJECT1UI *ui;
PROJECT1Doc *doc;


int mainEdgeDetection(int argc, char **argv) {
	if ((argc!=3) && (argc !=4)) {
		printf("usage: %s inputfile outputfile [step]\n", argv[0]);
		return -1;
	}

	int step = 4;
	if(argc == 4) {
		step = atoi(argv[3]);		
	}

	//Load the query image.
	Fl_Shared_Image *queryImage = Fl_Shared_Image::get(argv[1]);
		
	if (queryImage == NULL) {
		printf("couldn't load query image\n");
		return -1;
	}

	CFloatImage srcimg, dstimg;
	// Convert the image to the CImage format.
	if (!convertImage(queryImage, srcimg)) {
		printf("couldn't convert image to RGB format\n");
		return -1;
	}
	// Perform Edge Detection
	performEdgeDetection(srcimg,dstimg,step);

	CByteImage udstimg;
	convertToByteImage(dstimg, udstimg);
	//WriteFile(udstimg,argv[2]);
	writeByteImageToBMP(udstimg,argv[2]);

	return 0;
}


int main(int argc, char **argv) {
	// This lets us load various image formats.
	fl_register_images();

	if (argc > 1) {
		mainEdgeDetection(argc, argv);	
	}
	else {
		// Use the GUI.
		doc = new PROJECT1Doc();
		ui = new PROJECT1UI();
		ui->set_document(doc);
		doc->set_ui(ui);
		Fl::visual(FL_DOUBLE|FL_INDEX);
		ui->show();
		return Fl::run();
	}
}