process_ssurgo2ss.cc [tools/Rusle2SoilsXMLCreator/pg/rusle2_from_ssurgo_build_newbackup] Revision:   Date:
#include <cstdlib>
#include <iostream>
#include "dirent.h"
#include "errno.h"
#include <string>
#include <sys/types.h>
#include "rusle2_from_ssurgo.h"
#include "libpq-fe.h"



using namespace std;


/*
 *
 */
bool 
confirmAreaSupported ( PGconn *conn, string areasymbol )
{

#ifndef NDEBUG
	cout << "confirmAreaSupported()" << endl;
#endif

	const char * paramValues[1];
	paramValues[0] = areasymbol.c_str();
	PGresult *res;
	res = PQexecParams( conn,
			"SELECT count(*) FROM ssurgo.legend WHERE areasymbol ILIKE $1",
			1,
			NULL,
			paramValues,
			NULL,
			NULL,
			0);
	if( PQresultStatus(res) != PGRES_TUPLES_OK ){
		PQclear(res);
		exit_nicely(conn);
	}

	int _res = atoi( PQgetvalue( res, 0, 0 ) );

	if( VERBOSE )
		cout << "isAreaSupoorted ? " << _res << endl;

	PQclear(res);

	/* We found the area */
	if( _res > 0 )
		return true;

	/* Area has not been entered yet. */
	return false;
}
	

/*
 *
 */
int 
process_ssurgo2ss ( char* dir, char* service, char* areasymbol )
{

#ifndef NDEBUG
	cout << "process_ssurgo2ss()" << endl;
#endif

	string _areaSym(areasymbol);
	string dir_out( dir );

	PGconn *conn;
	PGresult *res;

	string pg_service("service="); 
	pg_service += service;

	const char * conninfo = pg_service.c_str();
	conn = PQconnectdb( conninfo );

	if ( PQstatus(conn) != CONNECTION_OK ){
                cout << "db connection failure!" << endl;
		cerr << "Connection failed to " << service << ": " << PQerrorMessage(conn) << endl;
                cerr << "connection info='" << conninfo << "'" << endl;
		cerr << "pg_service='" << pg_service << "'" << endl; 
                cerr << "PQstatus(conn)=" << PQstatus(conn) << endl;
           
		exit_nicely(conn);
	}

	bool isSupArea = _areaSym == "ALL" ? true : false;

	if( _areaSym != "ALL")
		isSupArea = confirmAreaSupported(conn, areasymbol);

	if( isSupArea ){	
		const char * paramValues[1];
		paramValues[0] = areasymbol;
		int numParams = 1;
		PGresult *res;
		string Query = "SELECT areasymbol, areaname, lkey FROM ssurgo.legend WHERE areasymbol ILIKE $1";
		/* Erase the WHERE clause if we're doing all...*/
		if( _areaSym == "ALL" ){
			Query.erase( Query.find("WHERE") );
			paramValues[0] = NULL;
			numParams = 0;
		}
		
		res = PQexecParams( conn,
				Query.c_str(),
				numParams,
				NULL,
				paramValues,
				NULL,
				NULL,
				0);
		if( PQresultStatus(res) != PGRES_TUPLES_OK ){
			PQclear(res);
			exit_nicely(conn);
		}

		int i_area = 0;
		while( processArea( conn, res, dir_out, i_area ) == true ){
#ifndef NDEBUG
			cout << "Processing " << PQgetvalue(res, i_area, 0) << " - " << PQgetvalue(res, i_area, 1) << endl;
#endif
			i_area++;
		}


		PQclear(res);
	}
	
#ifndef NDEBUG
	cout << "leaving process_ssurog2ss()" << endl;
#endif

	return 0;
}