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

int main(int argC, char* argv[]) {

	// VARIABLES DECLARATION
	char			address[30], userName[20], passwd[30], name[64], ParName[8], channelname[30];
	int				link, is, n, slot, NrOfCh=1, channel, pw, status, station;
	float			new_value;
    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;;

	float *param = NULL;
	param = malloc(sizeof(float));

	ushort *id_channel = NULL;
	id_channel = malloc(sizeof(ushort));

	if (argC != 2) {
		printf("usage: SetV0 <V0> (note that <V0> is the effective voltage\n");
		exit(1);
	}

	new_value = atof(argv[1]);

	// Reading latest values from the weather station
	FILE *stream3;
	stream3=fopen("/home/user/meteolog","r");
	//fgets(header,sizeof(header),stream3);
	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);

	// CAEN SY1527 settings
	sprintf(userName,"%s","admin");
	sprintf(passwd,"%s","admin");


	// Reading the Configuration file (it cointains the path file also)
	FILE *stream1;
	stream1=fopen("/srv/www/htdocs/conf_sm.txt","r");
	fscanf(stream1,"%s\n",name);
	fscanf(stream1,"%s\n",address);

	/*
	 // Useful informations
	 printf("Configuration file correctly read\n");
	 printf("IP address: %s \n", address);
	 printf("%s\n", "");
	 */

	// Preparing connection to the mainframe
	CAENHVRESULT  ret_init,ret;
	link = LINKTYPE_TCPIP;
	ret_init =  CAENHVInitSystem(name, link, address, userName, passwd);
	//printf("\nCAENHVInitSystem: %s (num. %d)\n\n", CAENHVGetError(name), ret_init);

	// Reading values from the Mainframe
	if ( ret_init == CAENHV_OK ) {




		while (!feof(stream1)) {

			// READING THE CONFIGURATION FILE
			fscanf(stream1,"%s %d %d %d\n",channelname, &slot, &id_channel[0], &station);



			// CALCULATING THE SLOT AND ID CHANNELS ON THE CAEN1527
			//slot = (channel/6);
			//id_channel[0] = (channel%6);
			//printf("Slot: %d Channel in the slot = %d \n", slot,id_channel[0]);




			// SETTING THE NEW V0 VALUE
			sprintf(ParName,"%s","V0Set");
			//param[0] = new_value * pressure / pressurezero;
			ret = CAENHVSetChParam(name, slot, ParName, NrOfCh, id_channel, param);

			if (ret==CAENHV_OK) {
				//printf("\nNwe I0 value set.");
			}
			else {
				//printf("\nCAEN1527: %s (num. %d)\n Paramenter Name %s \n", CAENHVGetError(name), ret, ParName);
			}



		}
		// CLOSING THE CONFIGURATION FILE
		fflush(stream1);
		fclose(stream1);

		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);
	}
}

