///////////////////////////////////////////////////////////
// BDP-S390 Firmware Modification Code:
//    Binary Version and Date Modification
//--------------------------------------------------------
// Copyright (C) 2013 Malcolm Stagg
///////////////////////////////////////////////////////////

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>

using namespace std;

int main(int argc, char * argv[]) {
	fstream infile;
	ofstream outfile;
	
	bool version;
	
	if (argc != 4) {
		cout << "Usage: modversion [file to modify] [(D)ate/(V)ersion] [text string]" << endl;
		exit(1);
	}
	char * infilename = argv[1];
	char * datevers = argv[2];
	char * newstring = argv[3];
	if (strcasecmp(argv[2], "D")==0)
		version = false;
	else if (strcasecmp(argv[2], "V")==0)
		version = true;
	else {
		cout << "Usage: modversion [file to modify] [(D)ate/(V)ersion] [text string]" << endl;
		exit(1);
	}
	
	infile.open(infilename, fstream::in | fstream::out | fstream::binary);
	
	if (!infile) {
		cout << "cannot open input file" << endl;
		exit(1);
	}
	
	//read header
	char binheader[0xf0];
	
	infile.read(binheader, 0xf0);
	
	char mainversion[16];
	char subversion[16];
	char verdate[16];
	char notsure1[16];
	char notsure2[16];
	int notsure3;
	int binfilesize;
	char ifconver[16];
	int notsure4;
	int notsure5;
	int notsure6;
	int notsure7;
	char microbever[16];
	strcpy(mainversion, binheader+0);
	strcpy(subversion, binheader+0x10);
	strcpy(verdate, binheader+0x20);
	strcpy(notsure1, binheader+0x30);
	strcpy(notsure2, binheader+0x38);
	notsure3 = *((int *)(binheader+0x50));
	binfilesize = *((int *)(binheader+0x5C));
	strcpy(ifconver, binheader+0x70);
	notsure4 = *((int *)(binheader+0x80));
	notsure5 = *((int *)(binheader+0x84));
	notsure6 = *((int *)(binheader+0x88));
	notsure7 = *((int *)(binheader+0x8C));
	strcpy(microbever, binheader+0x90);
	
	cout << "Version: " << mainversion << endl;
	cout << "Subversion: " << subversion;
	if (version)
		cout << " <-- " << newstring << endl;
	else
		cout << endl;
	cout << "Date: " << verdate;
	if (!version)
		cout << " <-- " << newstring << endl;
	else
		cout << endl;
	cout << "File size: " << binfilesize << endl;
	cout << "IFCON ver: " << ifconver << endl;
	cout << "Microbe ver: " << microbever << endl << endl;
	
	char yn;
	cout << "\n\nContinue? (y/n)" << endl;
	cin >> yn;
	if (yn != 'y' && yn != 'Y') exit(1);
	
	if (version) {
		memset(subversion, 0, 16);
		strcpy(subversion, newstring);
		infile.seekp(0x10, ios::beg);
		infile.write(subversion, 16);
	} else {
		memset(verdate, 0, 16);
		strcpy(verdate, newstring);
		infile.seekp(0x20, ios::beg);
		infile.write(verdate, 16);
	}
	
	infile.close();
}

