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

struct collegeInfo {
  char name[51] ;
  char city[21] ;
  int enrollment ;
} ;

int main (int argv, char **argc) {
  struct collegeInfo uncColleges[1001] ;
  FILE *inFile, *outFile ;
  int usageProblem = 0 ;
  char *outFileName = "cp-out.txt" ;

  // Check number of arguments
  if (argv < 2) {
    fprintf(stderr, "Usage: %s infile [outfile]\n", argc[0]) ;
    return 1 ;
  }

  // open input file
  inFile = fopen(argc[1], "r") ;
  if (inFile == NULL) {
    fprintf(stderr, "Unable to read %s: %s\n", argc[1], strerror(errno)) ;
    return 1 ;
  }

  // open output file
  if (argv == 3) {
    outFileName = argc[2] ;
  }
  outFile = fopen(outFileName, "w") ;
  if (outFile == NULL) {
    fprintf(stderr, "Unable to write %s: %s\n", outFileName, strerror(errno)) ;
    return 1 ;
  }
    
  int numColleges = 0 ;
  int numRead ;
  while ((numRead = fscanf(inFile,
			   "%[^,],%[^,],%d",
			   uncColleges[numColleges].name,
			   uncColleges[numColleges].city,
			   &uncColleges[numColleges].enrollment)) == 3) {
    numColleges++ ;
    // Skip to end of line...
    int eolMarker = ' ' ;
    while (eolMarker != '\n' && eolMarker != EOF) {
      eolMarker = fgetc(inFile) ;
    }
  }
  if (numRead!=0 && ferror(inFile)) {
    fprintf(stderr, "Input error reading %s: %s\n", argc[1], strerror(errno)) ;
    return 1;
  }
  fclose(inFile) ;
  for (int i=0; i<numColleges; ++i) {
    fprintf(outFile, "%-50.50s %-20.20s %10d\n",
	    uncColleges[i].name,
	    uncColleges[i].city,
	    uncColleges[i].enrollment) ;
  }
  fclose(outFile) ;
  return EXIT_SUCCESS ;
}
