#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include "calomysqlstruct.h"


short int readmy(char *db, const char *myquery, struct Mystruct *mystruct){   
    //
    int debug = 0;
    if ( debug ) printf("Connecting to database... \n"); 
    MYSQL *pConnection;
    MYSQL_RES *pResult;
    MYSQL_ROW Row;
    short int retval = 0;
    int t;
    int r;
    pConnection = mysql_init(NULL);
    if( !pConnection ) return(1);
    //
    int connect = (int)mysql_real_connect(pConnection,"srv-g2-01.ts.infn.it","pamela","CaloMyC@l1brati0n",db,0,NULL,0);    
    //
    if( !connect ) return(2);    
    if ( debug ) printf("...connected! \n\n");
    if ( debug ) printf("The query is:\n              \"%s\" \n",myquery);
    int errqu = mysql_query(pConnection,myquery);
    if ( !errqu ) {
	pResult = mysql_store_result(pConnection);
	mystruct->obtjump = 0;
	mystruct->fromtime = -1;	
	mystruct->totime = -1;	
	mystruct->calibtime = -1;
	mystruct->calcalibfile = "";
	for( r=0; r < mysql_field_count(pConnection); r++){ 
	    Row = mysql_fetch_row(pResult);
	    if( Row == NULL ) break;
	    int section = 0;
	    for( t = 0; t < mysql_num_fields(pResult); t++){
		if ( t == 1 ) section = atoi(Row[t]);
		if ( t == 2 ) mystruct->obtjump = atoi(Row[t]);
		if ( t == 3 ) mystruct->fromtime = atoi(Row[t]);
		if ( t == 4 ) mystruct->totime = atoi(Row[t]);
		if ( t == 5 ) mystruct->calibtime = atoi(Row[t]);
		if ( t == 6 ) mystruct->calcalibfile = Row[t];
	    };
	    if ( debug ) printf(" section %i from time %i to time %i use calibration at time %i from file %s ",section,mystruct->fromtime,mystruct->totime,mystruct->calibtime,mystruct->calcalibfile);
	    if ( debug ) printf("\n");
	};
	mysql_free_result(pResult);
	retval = 0;
    } else {
	if ( debug ) printf(" errqu = %i \n",errqu);
	retval = 3;
    };
    if ( debug ) printf("\nClose the connection... \n");
    mysql_close(pConnection);    
    if ( debug ) printf("...connection terminated!\n"); 
    return(retval);
}
