#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, mode;
	float			new_value;
	
	float *param = NULL;
	param = malloc(sizeof(float));
	
	ushort *id_channel = NULL;
	id_channel = malloc(sizeof(ushort));
	
	if (argC != 3) {
		printf("usage: SetTrip <trip> <mode>\n");
		exit(1);
	}
	
	new_value = atof(argv[1]);
        mode = atof(argv[2]);
	
	// CAEN SY1527 settings
	sprintf(userName,"%s","admin");	
	sprintf(passwd,"%s","admin");

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


        if (mode==1) {
           // Reading the Configuration file (it cointains the path file also)
           stream1=fopen("/srv/www/htdocs/conf.txt","r");
           fscanf(stream1,"%s\n",name);
           fscanf(stream1,"%s\n",address);
        }


        if (mode==2) {
           // Reading the Configuration file (it cointains the path file also)
           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 I0 VALUE
			sprintf(ParName,"%s","Trip");
			param[0] = new_value;
			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);             
	}
}

