/* Check program */

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

#define FNAME	"5check_LAM"
#define N_TM	20
#define REPEAT	1

#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("\t\n...clearing fifo...\n");
		::clr_fifo();
	}


	return nErr;
}

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

	CPacket pkt_LAMprep(BUF_SIZE);
	CPacket pkt_LAMScan(BUF_SIZE);
	
//==================<LAM scan preparation>========================
//puts("LAM-scan preparation Frames set!");
	if
	(
		pkt_LAMprep.AddFrame(nArg,0,0x11,0) ||		//All LAMs are cleared
		pkt_LAMprep.AddFrame(25,1,0x10,0xffffff) ||	//Set LAM mask
		pkt_LAMprep.AddFrame(25,1,0x1a,0)			//Set E-INT
	)
	return 2;

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

//==================<Command Frame Set>========================
	//-----WR-scan check----
//puts("LAM-scan Frames set!");
	unsigned long LAM;
	unsigned char wcnt=0;

unsigned long ErrAmount=0;
char szMsg[0xFF];
	
puts("comparing LAM pattern....");
	for ( LAM=1; LAM<0x800000; LAM<<=1 )
	{
		if ( pkt_LAMScan.AddFrame(nArg,0,0x11,LAM) )	return 2;

		if ( er=pkt_LAMScan.Go() )
		{
			printf("er=%d\n",er);
			return 3;
		}

		if ( er=pkt_LAMScan.WaitIntrFrm(0x000fffff,LAM) )
		{
			memset(szMsg, 0x00, sizeof(szMsg));
			sprintf(szMsg, "LAM(0x%06x) wait error : %d\n", LAM, er);
			create_logfile(FNAME, szMsg);
			ErrAmount++;
		}
	}



//==================<LAM scan termination>========================
//puts("LAM-scan finish Frames set!");
	if
	(
		pkt_LAMprep.AddFrame(25,1,0x10,0) ||	//Set LAM mask
		pkt_LAMprep.AddFrame(25,1,0x18,0) ||	//remove E-INT
		pkt_LAMprep.AddFrame(nArg,0,0x11,0)		//All LAMs are cleared
	)
	return 2;

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

