/* Check program */

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

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

#define BUF_SIZE	16000

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

	
//------Clear fifo
	while ( ::get_ircnt() )
	{
//		printf("...clearing fifo...\r");
//		printf("\t\n...clearing fifo...\n");
		::clr_fifo();
	}


	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(0) )
	{
		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 long wcnt;



puts("Waiting for TRG...");
for ( i=0; i<REPEAT; /*i++*/ )
{
	if ( pkt_TRGprep.AddFrame(1) )	return 2;	//Clear BsyOut
	if ( pkt_TRGprep.Go(0) )		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++;
		return 5;
	}
	
//	wcnt=0x000fff;
//	while ( wcnt--)printf("\t%2d\r",i);//wait for watching LED of TM.
	printf("\t%2d\r",i);
}
puts("");

//==================<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(0) )
	{
		printf("er=%d\n",er);
		return 3;
	}
	if ( ErrAmount )	return 4;
	return nErr;
}

