#include <iostream>
#include <string>
using namespace std;

bool IsAllDigits(string s){
	int x = 0;
	bool isInt = true;

	//Just check to see if a string s is all digits.
	while(x < s.length()){
		//Check for digits only.
		if(!isdigit(s.c_str()[0])){
			//Looks like a none number set flag to false
			isInt = false;
			//Exit loop
			break;
		}
		//INC counter.
		x++;
	}
	//Return flag.
	return isInt;
}

void Abort(int id, char*msg){

	std::cout << "Asc2Bin By Benjamin George.\n\n";

	switch(id){
		case 0:
			std::cout << "Syntax: InputFile OutputFile\n";
			std::cout << " asc2bin.exe sample.asc output.txt\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;
	int oByte = 0;
	string sNum = "";

	//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 decinal values to binary.
	while((ch = fgetc(fp)) != EOF){

		//Skip over line break.
		if(ch == 13){
			continue;
		}
		//Only get data if char , and 10 is not found.
		if((ch != ',')&& (ch != 10)){
			//Build the decimal number.
			sNum+=ch;
		}else{
			//Check if the string is all decimal.
			if(IsAllDigits(sNum)){
				//Convert number string to int
				oByte = atoi(sNum.c_str());
				//Write int to output file.
				fputc(oByte,fo);
				//Clear number string.
				sNum.clear();
			}
		}
	}

	//Check if we hit the end of the file.
	if(feof(fp)){
		//Check if the string is all decimal.
		if(IsAllDigits(sNum)){
			//Convert number string to int
			oByte = atoi(sNum.c_str());
			//Write int to output file.
			fputc(oByte,fo);
			//Clear number string.
			sNum.clear();
		}
	}

	//Close output file.
	fclose(fo);
	//Close input file.
	fclose(fp);
	//Return good result.
	return 3;
}