// P-1 MCS 360 due Wed 15 Sep 2010 : tornadoes.cpp

/* The input file for this program is "2009_torn.csv" or a file
   in similar format downloaded from NOAA's National Weather Service,
   at http://www.spc.noaa.gov/wcm/#data.

This file is a comma separated file with data for each tornado
that happened in the US in 2009.

Each line represents one tornado: the 8-th field is the state
and the 11-th field is the magnitude of the tornado.

When and where did the strongest tornado happen?

If the flag "v" defined below is set to a value > 0,
then extra information will be printed. */

#include <iostream>
#include <fstream>
#include <string>

#define v 0

using namespace std;

int value ( string s );
// given in s a number, returns its value

void state_magnitude ( string line, char *s, int *m );
/* finds the state s and magnitude m of a tornado,
   given one line of the data file in csv format */

int main()
{
   string input_file_name;

   cout << "Give name of input file : ";
   cin >> input_file_name;

   ifstream ins(input_file_name.c_str());

   string buffer;
   char state[3];
   int count = 0;
   int max_magnitude = -1;
   char max_state[3];
   int magnitude;

   state[2] = '\0';
   max_state[2] = '\0';

   while(!ins.eof())
   {
      getline(ins,buffer,'\n');
      if(ins.eof()) break;
      state_magnitude(buffer,state,&magnitude);
      if(magnitude > max_magnitude)
      {
         // cout << "state : " << state
         //      << " magnitude : " << magnitude << endl;
         max_magnitude = magnitude;
         max_state[0] = state[0];
         max_state[1] = state[1];
      }
      // cout << buffer << endl;
      count = count + 1;
   }

   cout << "Counted " << count
        << " tornadoes, " << endl;

   cout << "the tornado of maximal magnitude " << max_magnitude
        << " occurred in " << max_state << "." << endl;

   ins.close();

   return 0;
}

int value ( string s )
{
   int n = 0;

   for(int i=0; i<s.length(); i++)
      n = n*10 + int(s[i]) - int('0');

   return n;
}

void state_magnitude ( string line, char *s, int *m )
{
   int p,q; // two consecutive positions in the line

   p = 0;   // start at beginning of line

   for(int i=0; i<8; i++)
   {
      q = line.find(",",p);
      if(v) if(i<7) cout << "skipping column " << i+1 << endl;
      if(i<7) p = q + 1;
   }
   string state = line.substr(p,q-p);
   if(v) cout << "extracted state " << state << " from column 8" << endl;
   p = q + 1;
   for(int i=0; i<3; i++)
   {
      if(v) if(i<2) cout << "skipping column " << 8 + i + 1 << endl;
      q = line.find(",",p);
      if(i<2) p = q+1;
   }
   string magnitude = line.substr(p,q-p);

   *m = value(magnitude);
   s[0] = state[0];
   s[1] = state[1];
}

