#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

/** update statistics with new data point xi */
void update_stats( double xi, double& sum,
		double& theMin, double& theMax,
		int& N )
{
	N++;
	sum += xi;
	if( xi > theMax ) theMax = xi;
	if( xi < theMin ) theMin = xi;
}

void display_block_data( string lastmonth, int N, double tempSum, 
		double wndDirSum, double maxWndDir, double minWndDir )
{
	cout << "== " << lastmonth << " " << N << " datapoints ==" << endl;
	cout << "          average temp: " << tempSum/N << endl;
	cout << "    min wind direction: " << minWndDir << endl;
	cout << "average wind direction: " << wndDirSum/N << endl;
	cout << "    max wind direction: " << maxWndDir << endl;

}

void init_block_data( int &N,
		double& tempSum, 
		double& wndDirSum, 
		double& maxWndDir, double& minWndDir )
{
	N = 0;
	tempSum = wndDirSum = 0;
	minWndDir = 1e308;
	maxWndDir = -1e308;
}

int main()
{
	// open file
	ifstream infile( "weather.dat" );
	if( !infile ) {
		cout << "Error opening file." << endl;
		exit(1);
	}

	string junk;
	// read in column labels 
	getline( infile, junk, '\n' );
	
	// init block data
	int N;
	double tempSum, wndDirSum, maxWndDir, minWndDir;

	// vars for each record of data
	string month;
	int day;
	double xTemp, nTemp, aTemp; // max, min, avg temp
	double windDir, windSpeed;

	// to detect change of month
	string lastmonth;           

	// prepare to read in data
	init_block_data( N, tempSum, wndDirSum, maxWndDir, minWndDir );

	// MANTRA MANTRA MANTRA!
	while( infile >> month >> day >> xTemp >> nTemp >> aTemp >> windDir >> windSpeed ) {
		// detect a change of month but ignore on the first data record
		if( N && month != lastmonth ) {
			// display monthly stats
			display_block_data( lastmonth, N, tempSum, wndDirSum, maxWndDir, minWndDir );

			// init block data
			init_block_data( N, tempSum, wndDirSum, maxWndDir, minWndDir );
			
			// we still hold the 1st day of the new month's data, so we
			// need to run update_stats() below...
		}

		update_stats( windDir, wndDirSum, minWndDir, maxWndDir, N );

		// Don't increment N again!  Send an ignored int variable instead (day).
		// We aren't tracking max and min of the average temp, so just send
		// two ignored doubles instead,
		update_stats( aTemp, tempSum, xTemp, nTemp, day );

		// always remember this
		lastmonth = month;
	}
	// don't forget to display the last month we read in!
	if( N ) {
		// only if we have a data point!
		display_block_data( lastmonth, N, tempSum, wndDirSum, maxWndDir, minWndDir );
	}
	
	infile.close();
	return 0;
}

