#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 != 5) {
		printf("usage: SetTrip  <slot> <channel> <trip> <mode>\n");
		exit(1);
	}
	slot = atoi(argv[1]);
	id_channel[0] = atoi(argv[2]);
	new_value = atof(argv[3]);
        mode = atof(argv[4]);

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

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

	// 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 ) {

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

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

