/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <inc_iostream.h>
#include <math.h>
#include <Metview.h>
#include <MvTimeSerie.h>
#include <Cached.h>


const int SC_RMS = 1;
const int SC_CORRELATION = 2;

class Scores : public MvService {
protected:
	Scores(char* a) : MvService(a)			{};
	void   do_one(MvRequest&, double*, MvTimeSerie&);
public:
	Scores() : MvService("SCORES") 		{};
	void serve(MvRequest&,MvRequest&);
};

	
void Scores::serve(MvRequest& in,MvRequest& out)
{
	MvRequest grib1     = (request*) in("FIELD_1");
	MvRequest grib2     = (request*) in("FIELD_2");
	double area[4];

	const char *p = in("AREA");
	int i;

	area[0] =   90;
	area[1] = -180;
	area[2] =  -90;
	area[3] =  180;

	switch(*p)
	{
		case 'N':
			area[2] =  20;
			break;

		case 'S':
			area[0] = -20;
			break;

		case 'E':
			area[0] =    75;
			area[1] = -12.5;
			area[2] =    35;
			area[3] =  42.5;
			break;

		case 'G':
			break;

		default:
			for(i = 0 ; i< 4; i++)
				area[i] = in("AREA",i);
			break;
	}

	int    styp = SC_CORRELATION;
	if( Cached( (const char*)in( "SCORE" ) ) == Cached( "RMS" ) )
		styp = SC_RMS;
	
	in.print();

	MvTimeSerie serie;


	char		ref[1024];
	char		legend[1024];
	int   		param = -1;
	int   		level = -1;
	int   		number = -1;
	

	MvFieldSet          fs1(grib1);
	MvFieldSet          fs2(grib2);

	if(fs1.countFields() != fs2.countFields())
	{
		 setError(1,"Field 1 has %d fields, Field 2 has %d fields",
			fs1.countFields(),fs2.countFields());
		 return;
	}

	MvFieldSetIterator  iter1(fs1);
	MvFieldSetIterator  iter2(fs2);

	/* iter1.sort("STEP");  */
	iter1.sort("LEVELIST"); 
	iter1.sort("NUMBER"); 
	iter1.sort("PARAM"); 


	/* iter2.sort("STEP");  */
	iter2.sort("LEVELIST"); 
	iter2.sort("NUMBER"); 
	iter2.sort("PARAM"); 


	MvField f1;
	MvField f2;

	int first = 1;
	long base;

	while((f1 = iter1()) && (f2 = iter2()))
	{
		MvFieldExpander ex1(f1);
		MvFieldExpander ex2(f2);
		/* double min = field[0];  */
		/* double max = field[0];  */

		// Here, we should check the time constistency

		MvRequest r = f1.getRequest();

		int       p = r("PARAM");
		int       l = r("LEVELIST");
		int       n = r("NUMBER");

		int    t = r("TIME");
		int    s = r("STEP");
		int    d = r("DATE");

		t /= 100;

		d = mars_date_to_julian(d);
		t = t + s;

		while(t >= 24)
		{
			d++;
			t -= 24;
		}

		long x = d * 24 + t;

		d = mars_julian_to_date(d,false);

		if(first)
		{
			base = x;
			serie.setDate(d,t*100);
			first = 0;
		}

		printf("base = %d x = %d d = %d t = %d\n",
			base,x,d,t);


		if (p != param || l != level || n != number) {
			param  = p;
			level  = l;
			number = n;

			{
				// should add area

				sprintf(ref,    "%d/%d/%d",    param, level,number);
				sprintf(legend, "%s %d Level=%d", 
						(const char*)in("SCORE"), param, level);
				serie.createNewGroup(ref, legend);

				// It this the right thing to do????!!!

		    	serie.addIconInfo(ref, "DATA", grib1);
		    	serie.addIconInfo(ref, "DATA", grib2);

	//				serie.addIconInfo(ref, "AREA", area);

				// should add area

				if(level)
					serie.setTitle(ref, "%s of %d level %d", 
						(const char*)in("SCORE"), p, l);
				else
					serie.setTitle(ref, "%s of %d", 
						(const char*)in("SCORE"), p);

			}
		}

		if(f1.countValues() != f2.countValues())
		{
		 	setError(1,"Scores: some fields have not the same number of points");
			return;
		}
		
		sprintf(ref, "%d/%d/%d", p, level,number);

		switch( styp )
		{
		 case SC_RMS:
			{
				for(int i = 0; i < f1.countValues(); i++)
				{
					f1[i]  = f1[i] - f2[i];
					f1[i] *= f1[i];
				}
				double  y = f1.integrate(area[0],area[1],area[2],area[3]);

        		serie.addPoint(ref, x - base, sqrt(y));
			}
			break;

		 case SC_CORRELATION:
			{
				double cov12  = f1.covar( f2, area[0],area[1],area[2],area[3]);
				double stdev1 = f1.stdev( area[0],area[1],area[2],area[3]);
				double stdev2 = f2.stdev( area[0],area[1],area[2],area[3]);

				double y = 0;
				if( stdev1 != 0 && stdev2 != 0 )
					y = cov12 / ( stdev1*stdev2 );

				cout << y
				     << " = " << cov12 << " / (" << stdev1 << " * " << stdev2 << ")"
				     << endl;
        		serie.addPoint(ref, x - base, y );
			}
			break;
		}
			
	}

	out = serie.getRequest();
	out.print();
}


int main(int argc,char **argv)
{
	MvApplication theApp(argc,argv);
	Scores     scores;

	scores.addModeService("GRIB", "DATA");
	theApp.run();
}
