/* filemerge.cpp */

/*
  This program reads lines from the two files,
  and appends any lines from the second file that
  are not found in the first file are appended to
  the first file.
*/


#include <stdio.h>
#include "stringlist.h"

#define BUFLEN 200

int main ( int argc, char * argv [] ) {
  FILE * infile;
  FILE * outfile;
  StringList * slIn;
  StringList * slOut;
  int iIndex;
  int iCount;
  int iPos;
  char * psz;
  char pszBuf [BUFLEN];

  if ( argc != 3 ) {
	  printf ( "%s requires two arguments\n", argv [0] );
	  return 1;
  }

  outfile = fopen ( argv [1], "r+" );
  if ( ! outfile ) {
	printf ( "File '%s' not found\n",
			   argv [1] );
	return 2;
  }

  infile = fopen ( argv [2], "r" );
  if ( ! infile ) {
	printf ( "File '%s' not found\n",
			   argv [2] );
	return 3;
  }

 // read file 2 into memory
  printf ( "Reading file '%s'\n", argv [2] );
  slIn = new StringList;
  while ( ! feof ( infile ) ) {
//	  printf ( "Reading line from file2\n" );
	  fgets ( pszBuf, BUFLEN - 1, infile );
	  slIn->Add ( pszBuf );
  }
  fclose ( infile );

 // read file 1 into memory
  printf ( "Reading file '%s'\n", argv [1] );
  slOut = new StringList;
  while ( ! feof ( outfile ) ) {
	  fgets ( pszBuf, BUFLEN, outfile );
	  slOut->Add ( pszBuf );
  }


// Iterate through outfile to find lines also
// found in infile
// If found, delete from Infile list
  printf ( "Removing duplicate lines from '%s'\n", argv [2] );
  iCount = slOut->Count ();
  for ( iIndex = 0; iIndex < iCount; iIndex++ ) {
	  psz = slOut->Strings ( iIndex );
	  iPos = slIn->IndexOf ( psz );
	  if ( iPos < 0 ) continue;
	  slIn->Delete ( iPos );
  }

// Append lines remaining from infile to outfile
// and save outfile
  iCount = slIn->Count ();
  printf ( "Appending %d lines to '%s'\n", iCount, argv [1] );
  for ( iIndex = 0; iIndex < iCount; iIndex++ ) {
	psz = slIn->Strings ( iIndex );
	fputs ( psz, outfile );
  }

// release objects and files
  fclose ( outfile );
  delete slIn;
  delete slOut;
}
