/* Table.cpp defines various Table operations.
 * ...
 ******************************************************/

#include "Table.h"
#include <fstream.h>
#include <assert.h>

void Print(ostream & out, const Table & aTable)
{
  for (int row = 0; row < aTable.size(); row++)
  {
     for (int col = 0; col < aTable[row].size(); col++)
	 out << aTable[row][col] << '\t';
     out << '\n';
  }
}
void Fill(const string & fileName, Table & aTable)
{
  ifstream in(fileName.data());          // open stream to file
  assert(in.is_open());                  // verify

  int rows,                              // input variables
      cols;                              //  for dimensions
  in >> rows >> cols;                    // read dimensions
  
  Table locTable(rows, TableRow(cols));  // construct local table with
                                         // correct # rows and columns
  for (int r = 0; r < rows; r++)         // for each row
     for (int c = 0; c < cols; c++)      //   input cols values into row
        in >> locTable[r][c];
                                         // assign locTable to aTable so
  aTable = locTable;                     //   it has correct dimensions
  in.close();                            // close stream
}

void Load(const string & fileName, Table & aTable)
{
  ifstream in(fileName.data());          // open stream to file
  assert(in.is_open());                  // verify

  Table locTable;                        // empty local table
  double aValue;                         // input variable
  char separator;                        // to test for '\n'

  for (;;)                               // loop:
    {
      TableRow aRow;                      //   start w/ an empty row
      for (;;)                            //   loop:
	{
	  separator = in.peek();           //      peek at the next char
	  if (separator == '\n') break;    //      if at end of row, exit
	  in >> aValue;                    //      read a value
	  if (in.eof()) return;            //      if eof, quit
	  aRow.push_back(aValue);          //      append value to row
	}                                   //   end loop
      in.get(separator);                  //   consume the newline
      locTable.push_back(aRow);           //   append row to table
    }                                      // end loop

  aTable = locTable;                     // assign locTable to aTable
  in.close();                            // close stream
}

