#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "CAENHVWrapper.h"

int main() {
    
	// VARIABLES DECLARATION
	char   address[30], userName[20], passwd[30], name[64], buffer[80], ParName[8], channelname[30], filetoread[80];
	int    link, is, n, NrOfCh=1, pw, status, slot_c, channel_c, slot, channel, modify=0;
    float  dew, pressure=0,rainlast,rainday,rainmonth,rainyear,heat,temp1=0,temp2=0,rh1=0,rh2=0,wind,gust,dir;
    int    day,month,year,hour,min,pressurezero=990, mode, ongoinscan = 0;
    float  alfat = 1, alfap = 1, effectivewritten, new_value, temporary_effective, appliedhv, vmon, imax, imon;
    
	float *param = NULL;
	param = malloc(sizeof(float));
    
	ushort *id_channel = NULL;
	id_channel = malloc(sizeof(ushort));
    
    FILE *stream1;
	FILE *stream3;
    FILE *stream4;
    FILE *stream5;
    
    // Reading GAP conf file
    stream1=fopen("/srv/www/htdocs/conf_sm.txt","r");
    fscanf(stream1,"%s\n",name);
    fscanf(stream1,"%s\n",address);
	fflush(stream1);
	fclose(stream1);

	// Reading latest values from the weather station
	stream3=fopen("/home/user/meteolog3","r");
	while (!feof(stream3)) {
		fscanf(stream3,"%d %d %d %d %d %f %f %f %f %f %f %f %f %f %f %f %f\n",&day,&month,&year,&hour,&min,&temp1,&rh1,&dew,&pressure,&wind,&gust,&dir,&rainlast,&rainday,&rainmonth,&rainyear,&heat);
	}
	fflush(stream3);
	fclose(stream3);
    

    
    if ( ongoinscan == 0 ) {
        
        // CAEN SY1527 settings
        sprintf(userName,"%s","admin");
        sprintf(passwd,"%s","admin");
        
        // Preparing connection to the mainframe
        CAENHVRESULT  ret_init,ret;
        link = LINKTYPE_TCPIP;
        ret_init =  CAENHVInitSystem(name, link, address, userName, passwd);
        
        // Connection OK!
        if ( ret_init == CAENHV_OK ) {
            
            // Reading effective file
            FILE *stream3=fopen("/home/user/dump_sm","r");
            while (!feof(stream3)) {
                fscanf(stream3,"%d %d %f %f %f %f %d %d\n", &slot, &id_channel[0], &appliedhv, &vmon, &imax, &imon, &pw, &status);
                
                
                // Reading HV_eff file
                strcpy( filetoread, "/home/user/temp/qc42_" );
                sprintf(buffer,"%d",slot);
                strcat( filetoread, buffer );
                strcat( filetoread, "_" );
                sprintf(buffer,"%d",id_channel[0]);
                strcat( filetoread, buffer );
                stream4=fopen( filetoread, "r");
                //printf("%s %s\n","Opening ", filetoread);

                if (stream4 != NULL) {
                    //printf("%s\n","File exist!");
                    
                    while (!feof(stream4)) {
                        fscanf(stream4,"%f %d %d\n", &effectivewritten, &slot_c, &channel_c);
                        
                        // Check if HV_appl is ok
                        temporary_effective = appliedhv * (pressurezero / pressure) * alfat * alfap;
                        if ( ( abs( temporary_effective - effectivewritten ) ) > 7 ) {
                            modify = 1;
                            //printf("%s %f %f\n","Correction is NEEDED!!!! Because: ", temporary_effective, effectivewritten);
                        }
                        else {
                            //printf("%s %f %f\n","Correction not necessary because: ", temporary_effective, effectivewritten);
                        }
                    }
                    fflush(stream4);
                    fclose(stream4);
                }
                else {
                    //printf("%s\n","File does not exist!");
                }
                
                // Setting a new HV value
                if ( modify == 1 ) {
                    //printf("%s\n","Applying new value");
                    sprintf(ParName,"%s","V0Set");
                    new_value = effectivewritten * pressure / pressurezero;
                    new_value = (int)new_value;
                    param[0] = new_value;
                    ret = CAENHVSetChParam(name, slot, ParName, NrOfCh, id_channel, param);
                    modify = 0;
                    
                    // Info printing
                    {
                        if (ret == CAENHV_OK) {
                            //printf("\nNwe V0 value set.");
                        }
                        else {
                            //printf("\nCAEN1527: %s (num. %d)\n Paramenter Name %s \n", CAENHVGetError(name), ret, ParName);
                        }
                    }
                }
            }
            fflush(stream3);
            fclose(stream3);
            
            ret_init = CAENHVDeinitSystem(name);
            //printf("\nDisconnecting from caen on %s \n",name);
        }
        else {
            //printf("Error connecting to the caen %s (num %d) \n",CAENHVGetError(name),ret_init);
        }
    }
}

