/* mergefile.c - It merges the content of two sorted files. 
	We assume that the files contain any number of integers per line 
	(including no integers at all). It stores the result into a third file.
	The names of the files are passed as command line parameters.
*/

#include <stdio.h>
#include <stdlib.h>

/* Merge the two sorted files filename 1 and filename2 into finename.
   Return 0 in case of success, != 0 in case of failure */
int merge(const char *filename1, const char *filename2, const char *filename) {
   FILE *fin1 = fopen(filename1, "r");	
   if (fin1 == NULL) return -1;
   FILE *fin2 = fopen(filename2, "r");	
   if (fin2 == NULL) return -1;
   FILE *fout = fopen(filename, "w");
   if (fout == NULL) return -1;

   int val1, val2; // Respectively, last values read from fin1, fin2
   int have1 = 0;  // if != 0, val1 is defined
   int have2 = 0;  // if != 0, val2 is defined
   while ( 1 ) {
	if (have1 == 0) {
		if ( fscanf(fin1, "%d", &val1) > 0 ) {
		    have1 = 1;
		}
	}
	if (have2 == 0) {
		if (fscanf(fin2, "%d", &val2) > 0 ) {
		    have2 = 1;
		}
	}
	if (have1 + have2 < 2) break;
	if ( val1 <= val2) {
		fprintf(fout, "%d\n", val1);
		have1 = 0;
	} else {
		fprintf(fout, "%d\n", val2);
		have2 = 0;
	}
   }
   if (have1 == 1) {
	do 
		fprintf(fout, "%d\n", val1);
	while (fscanf(fin1, "%d", &val1) > 0);
   }
   if (have2 == 1) {
	do
		fprintf(fout, "%d\n", val2);
	while (fscanf(fin2, "%d", &val2) > 0);
   }
   fclose(fin1);
   fclose(fin2);
   fclose(fout);
   return 0;
}

int main(int argc, char *argv[]) {

   if (argc != 4) {
	printf("usage: %s filename1 filename2 filename\n", argv[0]);
	return 0;
   }

   if (merge(argv[1], argv[2], argv[3]) != 0) {
	printf("merge failed\n");
   }

   return 0;
}

