#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string removeExtension(const std::string &filename) {
    size_t lastdot = filename.find_last_of(".");
    if (lastdot == std::string::npos) return filename;
    return filename.substr(0, lastdot); 
}


int main(int argc, char* argv[])
{
  char buffer[1];
  int count = 0;
  int inSize;
  string inFilename;
  if (argc != 2){
    cout<<"Specify filename of original rom to split.\nusage: "<< argv[0] <<" <filename>\n";
  }
  else {
	inFilename = argv[1];

	cout << "Looking for file named \"" << inFilename << "\" as input.\n";
	ifstream inFile(inFilename.c_str(), ios::in|ios::binary|ios::ate);
	if(inFile.is_open()){
		cout << "Original dump opened, so far so good!\n";
		inSize = (int) inFile.tellg();
		inFile.seekg (0, ios::beg);
		if(inSize != 262144){
		  cout << "Original dump size mismatch!!\nYou do not have a proper ROM dump.\n";
			return -1;
		}
	}
	else {
		cout << "Error opening original GameShark dump file, aborting.\n";
		return -1;
	}

	string LSB_FN = removeExtension(inFilename) + "_LSBs.bin";
	string MSB_FN = removeExtension(inFilename) + "_MSBs.bin";
	ofstream LSBSFile (LSB_FN.c_str(), ios::out | ios::binary);

	ofstream MSBSFile (MSB_FN.c_str(), ios::out | ios::binary);
	if(LSBSFile.is_open() && MSBSFile.is_open()){
		cout << "Both output files are created.\nSplitting of the original dump will now begin.\n";
	}
	else{
		cout << "Could not create the 2 splitted rom files, aborting.\n";
		return -1;
	}
	 
	for(count = 0; count < (262144/2); count++){

	inFile.read(buffer, 1);
	MSBSFile.write(buffer, 1);

	inFile.read(buffer, 1);
	LSBSFile.write(buffer, 1);

	}
	cout << "\"" << LSB_FN <<"\" and \"" << MSB_FN <<"\" created.\nEnjoy!\n";
	LSBSFile.close();
	MSBSFile.close();
	inFile.close();
  }
return 0;
}

