// Remove empty lines, comments from C/C++ code files.
// By Ben a.k.a DreamVB

#include <iostream>
#include <fstream>
using namespace std;
using std::cout;
using std::endl;

fstream fs;

string sTemp = "";
string sLine = "";
bool BlankLine = false;

string TrimWhite(string src){
	int i = 0;
	int idx = -1;

	//Remove any white space from a string.
	while (i < src.length()){
		if (!iswspace(src[i])){
			idx = i;
			break;
		}
		i++;
	}
	if (idx != -1){
		return src.substr(idx);
	}
	return "";
}

void GetALine(){
	char Line[220];
	//Read in a line
	fs.getline(Line, 220);
	//Set lines
	sLine = Line;
	sTemp = TrimWhite(Line);
}

int main(int argc, char *argv[]){
	char Line[196];
	char c = '\0';
	char flag = '\0';
	int Index = 0;
	bool isblank = true;
	bool RemoveEmpty = false;
	bool RemoveComments = false;
	bool RemoveIndent = false;

	//Check file args
	if (argc < 2){
		cout << "Usage: " << argv[0] << " <Filename> [options]" << endl;
		exit(1);
	}

	Index = 2;

	//Deal with options.
	while (Index < argc){
		if (argv[Index][0] == '/'){
			flag = toupper(argv[Index][1]);
			//
			if (flag == 'E'){
				//Remove empry lines.
				RemoveEmpty = true;
			}
			if (flag == 'C'){
				RemoveComments = true;
			}
			if (flag == 'I'){
				RemoveIndent = true;
			}
		}
		Index++;
	}

	//Open the source file.
	fs.open(argv[1]);

	if (!fs.good()){
		cout << "IO/Error, Cannot open file" << endl;
		exit(1);
	}

	//Read to the end of the file.
	while (!fs.eof()){
		isblank = false;
		//Get a line.
		GetALine();

		if (sLine.length() == 0){
			isblank = true;
		}

		//Check for simple comments 1
		if ((sTemp.substr(0, 2) == "//") & RemoveComments){
			sTemp.clear();
			//Check for mulitline comments
		}
		else if ((sTemp.length() == 2) & (sTemp.substr(0, 2) == "/*") & RemoveComments){
			//While not end of comment get a new line
			while (sTemp != "*/"){
				GetALine();
			}
			GetALine();
			//Get simple comments 2
		}
		else if ((sTemp.substr(0, 2) == "/*") & RemoveComments){
			sTemp.clear();
		}
		else{
			if (isblank){
				//Check if need to remove empry lines.
				if (!RemoveEmpty){
					//Append line break.
					cout << endl;
				}
			}
			else
			{
				if (sTemp.length() > 0){
					if (RemoveIndent){
						sLine = TrimWhite(sLine);
					}
					//Write out line.
					cout << sLine.c_str() << endl;
				}
			}

		}
	}

	//Close file
	fs.close();
	//Return
	return 0;
}