#include <iostream>
#include <string>
using namespace std;

void Abort(int id, char*msg){

	std::cout << "Bin2Asc By Benjamin George\n\n";

	switch(id){
		case 0:
			std::cout << "Syntax: InputFile OutputFile\n";
			std::cout << " bin2asc.exe sample.txt output.asc\n";
			break;
		case 1:
			std::cout << "Error reading source filename:\n ";
			std::cout << msg;
			break;
		case 2:
			std::cout << "Error writeing output filename:\n ";
			std::cout << msg;
			break;
	}
	std::cout << endl;
}

int main(int argc, char *argv[]){

	FILE *fp,*fo;
	int ch = 0;
	char sInt[6];
	string sNum = "";
	string sLine = "";

	//Check number of params
	if(argc != 3){
		//Abort and exit.
		Abort(0,"");
		return 0;
	}

	//Open input file.
	fp = fopen(argv[1],"rb");

	//Check if input file was opened.
	if(!fp){
		//Abort and exit.
		Abort(1,argv[1]);
		return 1;
	}

	//Create output file.
	fo = fopen(argv[2],"wb");

	//Check if can create output file.
	if(!fo){
		//Abort and exit.
		Abort(2,argv[2]);
		return 2;
	}

	//Read and convert binary to decimal lines.
	while((ch = fgetc(fp)) != EOF){
		//Convert int to string.
		itoa(ch,sInt,10);
		//Set string to sInt
		sNum = sInt;

		//Check the length of the string must be 3
		//Add zero's to the left iif we need them.
		switch(sNum.length()){
			case 1:
				sNum = "00" + sNum;
				break;
			case 2:
				sNum = "0" + sNum;
				break;
			default:
				break;
		}

		//Append decimal number to line and seperator ,
		sLine+= sNum;
		sLine+=",";

		if(sLine.length() >= 63){
			//Remove last ,
			sLine.erase(sLine.length()-1,1);
			//Add line breaks.
			sLine+= "\r\n";
			//Put line to the output file.
			fputs(sLine.c_str(),fo);
			//Clear line buffer.
			sLine.clear();
		}
	}

	//If at the end of the file append the remaining left over pices.
	if(feof(fp)){
		//remove last ,
		if(sLine.length() > 0){
			//Erase , from end of string.
			sLine.erase(sLine.length()-1,1);
		}
		//Put line to the output file.
		fputs(sLine.c_str(),fo);
	}

	//Close output file.
	fclose(fo);
	//Close input file.
	fclose(fp);

	//Return goog result.
	return 3;
}