/*******************************************************************************
 *	TmsDataClient2.cpp	TMS API example code for a Data Client
 *			T.Barnaby,	BEAM Ltd,	2007-09-19
 *******************************************************************************
 *
 *	This is a very basic example of using the TmsApi from a clients perspective.
 *	It is designed to give an overview of using the API.
 *	This example fetches the Sigma/DeltaX/DeltaY levels from all
 *	pickups for the first bunch.
 */
#include <iostream>
#include <stdio.h>
#include <TmsD.h>
#include <TmsC.h>

using namespace Tms;
using namespace std;


// Function to reads some data
BError tmsTest(TmsProcess& tmsProcess){
	BError			err;
	DataInfo		dataInfo;
	UInt32			cn = 0;
	BString			ct;
	UInt32			n;
	Data			data;
	UInt32			chan;
	
	// Find out the current cycle number and type
	if(err = tmsProcess.getCycleInfo(cn, ct)){
		return err.set(1, BString("Error: Getting Cycle Number: ") + err.getString());
	}
	
	printf("Getting data from all pick-ups for cycle: %u\n", cn);

	// Setup dataInfo
	dataInfo.cycleNumber	= cn;
	dataInfo.channel	= 0;
	dataInfo.cyclePeriod	= CyclePeriodEvent0;
	dataInfo.startTime	= 0;
	dataInfo.orbitNumber	= 0;
	dataInfo.bunchNumber	= 1;
	dataInfo.function	= DataFunctionRaw;
	dataInfo.argument	= 0;
	dataInfo.numValues	= 1024;
	dataInfo.beyondPeriod	= 1;

	if(err = tmsProcess.getData(dataInfo, data)){
		printf("Error: Getting Data: %d %s\n", err.getErrorNo(), err.getString().retStr());
		for(chan = 0; chan < data.errors.size(); chan++){
			printf("Chan: %d ErrorNo: %d ErrorStr: %s\n", chan + 1, data.errors[chan].getErrorNo(), data.errors[chan].getString().retStr());
		}
		return err.set(1, BString("Error: Getting Data: ") + err.getString());
	}
	
	return err;
}

int main(int argc, char** argv){
	BError			err;
	BString			host = "localhost";
	TmsProcess		tmsProcess;

	if(argc == 2)
		host = argv[1];

	// Connect to the Process service
	if(err = tmsProcess.connectService(BString("//") + host + "/tmsProcess1")){
		cerr << "Error: " << err.getString() << "\n";
		return 1;
	}
	
	// Run a normal data gathering cycle as a normal client would.
	if(err = tmsTest(tmsProcess)){	
		cerr << "Error: " << err.getString() << "\n";
		return 1;
	}
		
	return 0;
}
