#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, status, station;
	int  new_value, mode;


	unsigned int *param = NULL;
	param = malloc(sizeof(ushort));

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

	if (argC != 5) {
		printf("usage: SetI0 <slot> <channel> <POWER> <mode> \n");
                //mode=0 -> gaps /// mode=1 -> chambers /// mode=2 -> supermodules
		exit(1);
	}
	slot = atoi(argv[1]);
	id_channel[0] = atoi(argv[2]);
	new_value = atoi(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/sm_caenaddress.txt","r");
           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 POWER
			sprintf(ParName,"%s","Pw");
			param[0] = new_value;
			ret = CAENHVSetChParam(name, slot, ParName, NrOfCh, id_channel, param);

			if (ret==CAENHV_OK) {
				//printf("\n Power applied");
			}
			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);
	}
}

