/* Check program */

#include <stdio.h>
#include <stdlib.h>
#include "Packet.h"
#include "ErrCode.h"

#define FNAME	"6check_TRG"
#define N_TM	20
#define REPEAT	20

#define BUF_SIZE	16000

//------Error String------
char* pszErrString[] =
{
/*	0	*/	"\t\x1b[34m....Done with No-problems....\x1b[0m\n",
/*	1	*/	"\x1b[33mYou should be 'root' to run this program.\x1b[0m\n",

/*	2	*/	"\x1b[33mThere are no Space to store data.\x1b[0m\n",
/*	3	*/	"\x1b[33mExecution faild...\x1b[0m\n",
/*	4	*/	"\x1b[33mComparison faild\x1b[0m\n",

/*	5	*/	"\x1b[33mThis Chcek rootin FAILED.....\x1b[0m\n",
/*	4	*/	"\x1b[33mRx Timeout occured.\x1b[0m\n"
};
//------function prototype------
int MyProc(int nArg);


//=======================================
int main(int argc, char *argv[])
{
	int nErr;
	int nArg = N_TM;

	//-----<argument>-----
	if ( argc==2 )	nArg = atoi(argv[1]);
	
	//-----<operation>-----
	nErr = MyProc(nArg);
	
	//-----<operation result>-----
	puts(FNAME);
	printf( pszErrString[nErr] );
	
	return nErr;
}

//=======================================
int MyProc(int nArg)
{
	int nErr=0;
	unsigned long er;

	CPacket pkt_TRGprep(BUF_SIZE);
	CPacket pkt_TRGScan(BUF_SIZE);
	
//==================<TRG action preparation>========================
puts("TRG action preparation Frames set!");
		if
		(
			pkt_TRGprep.AddFrame(4)	||		//Disable TRG
			pkt_TRGprep.AddFrame(1) ||		//Clear BusyOut
			pkt_TRGprep.AddFrame(2) ||		//Clear Event Counter
			pkt_TRGprep.AddFrame(3)			//Enable TRG
		)
		return 2;

//puts("Cycle Go!");
	if ( er=pkt_TRGprep.Go() )
	{
		printf("er=%d\n",er);
		return 3;
	}
	

//==================<Command Frame Set>========================
puts("Waiting for TRG...");
unsigned long i, dmy, ev_cnt;
unsigned long ErrAmount=0;
char szMsg[0xFF];
unsigned short wcnt=0;

for ( i=0; i<REPEAT; /*i++*/ )
{
	if ( pkt_TRGprep.AddFrame(1) )	return 2;	//Clear BsyOut
	if ( pkt_TRGprep.Go() )		return 3;

	if ( pkt_TRGScan.WaitIntrFrm(0x000fffff, ++i) )
	{
		memset(szMsg, 0x00, sizeof(szMsg));
		sprintf(szMsg, "waiting # %d\tTimeOut or Mismatch!\n", i);
		create_logfile(FNAME, szMsg);
		ErrAmount++;
	}
	
	while ( ++wcnt);	//wait for watching LED of TM.
}

//==================<TRG action termination>========================
puts("TRG action finish Frames set!");
		if
		(
			pkt_TRGprep.AddFrame(4)	||	//Disable TRG
			pkt_TRGprep.AddFrame(1) ||	//Clear BusyOut
			pkt_TRGprep.AddFrame(2)		//Clear Event Counter
		)
		return 2;

//puts("Cycle Go!");
	if ( er=pkt_TRGprep.Go() )
	{
		printf("er=%d\n",er);
		return 3;
	}
	
	if ( ErrAmount )	return 4;
	return nErr;
}

