/***************************** 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 *************************************/

/*

B.Raoult
ECMWF Mar 95

*/


#include "Metview.h"
#include "LLMatrixToGRIB.h"

class ToGrib : public MvService {
public:
	ToGrib(char *c) : MvService(c) {}
	void serve(MvRequest&,MvRequest&);
protected:
       //	err  llmatrix_to_grib(const char *in,const char *out);
       //	void do_swap( fortfloat& s1, fortfloat& s2 )
       //	            { fortfloat t; t=s1; s1=s2; s2=t; }
};

class ToGeo : public MvService {
public:
	ToGeo(char *c) : MvService(c) {}
	void serve(MvRequest&,MvRequest&);
};

void ToGrib::serve(MvRequest& in,MvRequest& out)
{
	const char *path = in("PATH");
	char *tmp  = marstmp();

	if( LLMatrixToGRIB( path, tmp ) )
	{
		setError(1,"Convertion from LLMatrix to GRIB failed");
		return;
	}

	MvRequest grib    = "GRIB";
	grib("PATH")      = tmp;
	grib("TEMPORARY") = 1;

	out = grib;
}
		 

err grib_to_llmatrix(const char*, const char* ) //-- (const char *g,const char *m)
{
	return -1;
}


//_______________________________________________________________________
//
void ToGeo::serve(MvRequest& in,MvRequest& out)
{
	char *tmp     = marstmp();
	MvRequest geo = "GEOPOINTS";

	FILE *f = fopen(tmp,"w");
	if(!f)
	{
		setError(1,"Cannot open %s",tmp);
		return;
	}

	fprintf(f,"#GEO\n#DATA\n");

	while(in)
	{
		double lat = in("LATITUDE");
		double lon = in("LONGITUDE");
		const char *name = in("NAME");
		int  ident = in("IDENT");

		in.print();

		fprintf(f,"%g %g 0 0 0 %d %s\n",lat,lon,ident,name);

		in.advance();
	}
	fclose(f);

	geo("PATH")      = tmp;
	geo("TEMPORARY") = 1;

	out = geo;
}

int main(int argc,char **argv)
{
	MvApplication theApp(argc,argv);
	ToGrib  x("LLMATRIX");
	ToGeo   y("STATION");
	theApp.run();
}
