#include "superPixel.h"
#include <string>
#include <iostream>
using namespace std;

#include <windows.h>
#include <tchar.h> 
#include <strsafe.h>

string in_folder;
string out_folder;
int nSuperpixel;
float location_ratio;
string sp_folder;
string par_folder;

bool create_folder(string dir)
{
	if (CreateDirectory(dir.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
		return true;
	else
		return false;
}

void generate_superpixels_rec(string dir, string sub_path)
{
	if(dir.size() > 4  && (dir.substr(dir.size()-4, 4) == ".png" || dir.substr(dir.size()-4, 4) == ".ppm" || dir.substr(dir.size()-4, 4) == ".bmp" || dir.substr(dir.size()-4, 4) == ".jpg") ) //an image
	{
		SuperPixel sPixel;
		sPixel.loadImage(dir);
		sPixel.setDecimateNum(nSuperpixel);
		sPixel.init();
		sPixel.decimate();
		sPixel.init_swap();
		sPixel.swap_always();
		sPixel.make_superpixel(sp_folder, par_folder, sub_path.substr(0, sub_path.size()-4));
	}
	else
	{
		HANDLE hFind;
		WIN32_FIND_DATA data;
		string source_files = dir + "\\*.*";
		hFind = FindFirstFile(LPCTSTR(source_files.c_str()), &data);
		if (hFind != INVALID_HANDLE_VALUE) {
			do {
				if(string(data.cFileName) == "." || string(data.cFileName) == "..")
					continue;
				string new_dir= dir + "\\" + string(data.cFileName);
				string new_sub_path = sub_path + "\\" + string(data.cFileName);
				if(new_sub_path.substr(new_sub_path.size()-4, 4) != ".png" && new_sub_path.substr(new_sub_path.size()-4, 4) != ".ppm" 
					&& new_sub_path.substr(new_sub_path.size()-4, 4) != ".bmp" && new_sub_path.substr(new_sub_path.size()-4, 4) != ".jpg")
				{
					if(!create_folder(sp_folder+new_sub_path))
					{
						cout << "unable to create superpixel folder" << endl;
						return;
					}
					if(!create_folder(par_folder+new_sub_path))
					{
						cout << "unable to create partition folder" << endl;
						return;
					}
				}
				generate_superpixels_rec(new_dir,  new_sub_path);			
			} while (FindNextFile(hFind, &data));
			FindClose(hFind);
		}
	}	
}

int main(int argc, char *argv[])
{
	//usage : in_folder out_folder num_voxels
	in_folder = string(argv[1]);
	out_folder = string(argv[2]);
	nSuperpixel = atoi(argv[3]);
	location_ratio = atof(argv[4]);

	sp_folder = out_folder + "\\" + "superpixels";
	par_folder = out_folder + "\\" + "partition_results";
	if(!create_folder(sp_folder))
	{
		cout << "unable to create superpixel folder" << endl;
		return -1;
	}
	if(!create_folder(par_folder))
	{
		cout << "unable to create partition folder" << endl;
		return -1;
	}
	
	generate_superpixels_rec(in_folder, "");
}
