/* filemerge.cpp - Merging two sorted files into a third.
		The names of the files are passed as command line 
		parameters.
 */

#include <iostream>
#include <fstream>

// Merge the sorted files filename1 filename2 into filename3.
// Return 0 in case of success, -1 otherwise
int merge (const char *filename1, const char *filename2, 
	const char *filename3)
{
	ifstream fin1(filename1);
	if (!fin1) {
	   cout << "Sorry, cannot open " << filename1 << endl;
	   return -1;
	}
	ifstream fin2(filename2);
	if (!fin2) {
	   cout << "Sorry, cannot open " << filename2 << endl;
	   return -1;
	}
	ofstream fout(filename3);
	if (!fout) {
	   cout << "Sorry, cannot open " << filename3 << endl;
	   return -1;
	}

	int a, b;	// Values read respectively from first and
			// second file
	bool fa = false;// true iff a is defined and not yet in output file
	bool fb = false;// true iff b is defined and not yet in output file

	// Output elements until either fin1 or fin2 are at end of file
	for ( ; ; ) 
	{
	    if (!fa)
		if (!(fin1 >> a))
		   break;
		else
		   fa = true;
	    if (!fb)
		if (!(fin2 >> b))
		   break;
		else
		   fb = true;
	    if (a <= b) {
		fout << a << endl;
		fa = false;
	    } else {
		fout << b << endl;
		fb = false;
	    }
	}
	// Output remaining elements of file 1
	if (fa || (fin1 >> a) )
	    do {
		fout << a << endl;
	    } while (fin1 >> a);
	// Output remaining elements of file 2
	if (fb || (fin2 >> b) )
	    do {
		fout << b << endl;
	    } while (fin2 >> b);
	fin1.close();
	fin2.close();
	fout.close();
	return 0;
}

int main(int argc, char *argv[])
{
	if (argc != 4) {
	   cout << "Usage: " << argv[0] << " filefrom1 filefrom2 fileto\n";
	   return 0;
	}
	if (merge(argv[1], argv[2], argv[3]) != 0)
	   cout << "Cannot merge the files\n";
	else
	   cout << "The merge is done\n";
	return 0;
}