#include<iostream.h>
#include<fstream.h>
// for strlen and strcpy
#include<strings.h>

// SereverSenil.C (LinesReverse, spelt backwards)
//   burton rosenberg
//   3/31/1997

// Introduces NEW, dynamic varaible creation.
// Also, more practice with arrays of pointers and the 
// string library.

// Maximum lengths of things ...
const int LINES_N = 100 ;
const int BUFFER_N = 500 ;

char * reverseString( char * s ) 
{
   int l, i ;

   // set l to the last index in array
   l = strlen(s)  ;
   if ( l<2 ) return s ;

   char t ;
   for ( i=0; i < l/2; i++ ) // integer divide, so 
      // middle item is not swapped with itself
   {
      t = s[i] ;
      s[i] = s[l-i-1] ;
      s[l-i] = t ;
   }
   return s ;

}


int main( int argc, char * argv[] ) 
{
   ifstream ifs ;
   char * lines[LINES_N] ; // array of strings ( array of char* )
   int nLines ;
   char buffer[BUFFER_N] ;

   // helper variables
   int i ;
   char * s ;

   // check for correct invocation
   if ( argc < 2 ) 
   {
      cout << "Usage: " << argv[0] << " filename" << endl ;
      return -1 ;
   }

   // read the input
   ifs.open(argv[1]) ;
   i = 0 ;
   // LOOP INVARIANT: i points to next open slot in lines array
   while ( ifs.getline(buffer, BUFFER_N ) && i < LINES_N ) 
   {
      // set aside memory to coyp buffer into
      s = new char[strlen(buffer)+1] ;

      // The next statment:
      //   1) copys buffer into the char array pointed to by s,
      //   2) assigns the value of s, returned by strcpy, to lines[i],
      //   3) then updates i.
      lines[i++] = strcpy(s, buffer) ;
   }
   // remember the final value of i
   nLines = i ;
   ifs.close() ;

   // print out in reverse
   for ( i=nLines-1; i>=0 ; i-- ) {
      cout << reverseString(lines[i]) << endl ;
   }
}

