/* checker.cpp : checker program for assignment#1
 *		    Input : file to be checked
 *          - checks format (each record should be preceded by 2 byte length indicator)
 *			- checks if records are sorted by course code
 *          - displays first 10 records.
 */


#include <iostream>
#include <string>
#include <fstream>
using namespace std;

const int record_size = 10000;
const int records_to_print = 10;

// main method ... uses command line arguments
int main(int argc,char* argv[])
{
  char rec[record_size];     // to store a course records
 
  fstream input;                  
  
  if(argc!=2){
	  cerr << "USAGE: " << argv[0] << " <filename>" << endl;
	  return 1;
  }

  
  input.open(argv[1], ios::in|ios::binary);

  // Check to make sure that we could open properly!
  if (input.fail()) {
    cerr << "Could not open file ";
    cerr << argv[1];
    cerr << ".\n";
    return 1;
  }

  // read records
  short int n=0;
  int i=1,errc=0;
  bool sorted = true;
  string lastcode = "0000000";
  string record,code;
  while(input.peek()!=EOF && !input.fail()) {
	  	  input.read((char*)&n,2);
		  if(n <= 0 || input.fail())
			  cout <<"\nE"<< ++errc <<": Incorrect length indicator for Record "<< i << endl;
	      input.read(rec,n);
		  if(input.fail())
			  cout <<"\nE"<< ++errc <<": Error reading Record "<< i <<" (size="<<n<<")."<< endl;
		  rec[n]='\0';
		  record = rec;
		  code = record.substr(0,7);
		  if(code.compare(lastcode) < 0)
			  sorted = false;
		  if(i <= records_to_print) {
			  cout <<"\nRecord "<< i <<":"<< record << endl;
			  cout <<"Size of the record = "<< n << endl;
		  }
		  lastcode = code;
	      i++;
  }	

  if(!sorted)
	  cout <<"\nE"<< ++errc <<": Records are not sorted by code." << endl;
  
  cout << "\n " << --i << " Records read." << endl;
  cout << " " << errc << " Error(s) found."<< endl;
  input.close();
  return 0;
  
}