// main.cpp
// Aren Jansen
// CS152 Homework #5 Solution
// Purpose: Given a master file and a transaction log, produce
//          an updated master file.

#include <iostream>
#include <fstream>
#include <vector>
#include "Record.h"

using namespace std;

typedef vector<Record> RecordList;
typedef RecordList::iterator RecordIter;

bool findRecord( RecordList & aList, RecordIter & iter, int acctnum );

int main( void )
{
   fstream is_old( "oldmast.dat", ios::in );
   fstream is_trans( "trans.dat", ios::in );
   fstream os_new( "newmast.dat", ios::out | ios::trunc );

   RecordList accountList;

   // Read in the old master file
   while( is_old.peek() != EOF )
   {
      Record current;
      is_old >> current;
      accountList.push_back( current );
   }

   // Loop through the transaction file updating the 
   // appropriate record each time
   while( is_trans.peek() != EOF )
   {
      Record trans;
      is_trans >> trans;

      RecordIter iter;
      bool success = findRecord( accountList, iter, trans.getAcctNum() );

      if ( success )
      {
	 iter->updateBalance(trans.getBalance());
      }
      else
      {
	 cout << "Record not found: " << trans;
      }
   }


   // Write the new master file
   RecordIter iter;
   for ( iter = accountList.begin(); iter != accountList.end(); iter++ )
   {
      os_new << *iter;
   }
   
   return 0;
}


// ----------------------------------------------------------------------
// Loops of the record list and returns true if it finds the account
// number and false otherwise.  The proper value record will be stored in
// the iterator iter.
// ----------------------------------------------------------------------

bool findRecord( RecordList & aList, RecordIter & iter, int acctnum )
{
   for ( iter = aList.begin(); iter != aList.end(); iter++ )
   {
      if ( iter->getAcctNum() == acctnum )
      {
	 return true;
      }
   }

   return false;
}
