#include <stdio.h>
#include "hps.types.h"
#include "hps.iocb.h"
#include "hps.ioctl.h"
#include "hps.onb.h"
#include "hps.net.h"
#include "hps.asynch.h"
#include "hps.swap.h"

#define SUCCESS	0				/* sucess for ioctl() */

extern char hps_intel;

/*
 * xlogsub():
 *		returns  0 for success
 *				-1 if unable to open device raw_device
 *				-2 if unable to get xbyte information
 */
char  hps_intel    = 0;			/* host byte ordering	*/
char RAW_DEV[]	= RAW_DEVNAME;

main(argc, argv)
int argc;
char **argv;
{
	int hpsfd;  			/* file descriptor for the rew device */
	int res;
	int i;
	A_IOCB iocb;   			/* the IOCB */
	bit32 ltmp;
	short clear = GETT_NCLEAR;
	short tmp;
	A_TALLY tally;
	char *raw_device;
	short chan = 0;

	tmp = 0x0001;
	hps_intel = *(char *)&tmp;


	/* Open HPS interface (raw device) */
	raw_device = RAW_DEV;
	if ((hpsfd = open(raw_device, 2)) < 0)
	{
		fprintf(stderr, "xlogsub: Open failed on %s\n", raw_device);
		return (-1);
	}

	chan = atoi(argv[1]);
	/* Format the iocb */
	iocb.hdr.len = sizeof(A_IOCB);
	iocb.hdr.maj_dev = ASYNCH_DEV;			/* TCS */
	iocb.hdr.min_dev = chan;
	iocb.hdr.int_enab = ENABLED;
	iocb.hdr.return_msg.hps_addr = (bit32)&iocb;
	iocb.hdr.data_len = sizeof(A_TALLY);
	iocb.hdr.data.hps_addr = (bit32)&tally;
	iocb.hdr.data_dir = FROM_HPS;  			/* data comes FROM the HPS */
/* 	iocb.hdr.mode = not used; */
	iocb.hdr.mail.hps_addr = 0xFFFFFFFF; 
/* 	iocb.hdr.next = not used; */
/* 	iocb.hdr.finished = not used; */
	if (hps_intel)
	{
		iocb.command = (IOCTL<<8)|(IOCTL>>8);
		iocb.cmd_modifier = (AIOC_GETT<<8)|(AIOC_GETT>>8);
		ltmp = clear ? GETT_CLEAR : GETT_NCLEAR;
		SWAP_4BYTE(&iocb.cmd_param, &ltmp);
	}
	else
	{
		iocb.command = IOCTL;
		iocb.cmd_modifier = AIOC_GETT;
		if (clear)
			iocb.cmd_param = GETT_CLEAR;		/* clear info */
		else
			iocb.cmd_param = GETT_NCLEAR;		/* do not clear info */
	}
	iocb.link = NULL;

	/* send iocb on its way to the hps */
	res = ioctl(hpsfd, DO_IOCB, &iocb);

	if ((res != SUCCESS) || ((iocb.hdr.mail.hps_addr>>16) != 0))
	{
		fprintf(stderr, "xlogsub() error: ioctl result=%d  iocb mail=%d\n", 
				res, iocb.hdr.mail.hps_addr>>16);
		close(hpsfd);	/* close raw device */
		return (-2);	/* ioctl xbytes request failed */
	}
	else
	{
		if (hps_intel)
		{
			for (i=0; i<sizeof(tally)/4; ++i)
			{
				SWAP_4BYTE(&ltmp,&((bit32 *)&tally)[i]);
				((bit32 *)&tally)[i] = ltmp;
			}
		}
		printf("TCS tally info:\n");
		printf("\tNumber reads: %d\n",  tally.read);
		printf("\tNumber writes: %d\n",  tally.write);
		printf("\tNumber framing: %d\n",  tally.framing);
		printf("\tNumber parity: %d\n",  tally.parity);
		printf("\tNumber overrun: %d\n",  tally.overrun);
		printf("\tNumber breaks: %d\n",  tally.tbreak);
		printf("\tNumber DTR: %d\n",  tally.dtr);
		printf("\tNumber RTS: %d\n",  tally.rts);
		printf("\tNumber CD: %d\n",  tally.cd);
		printf("\tNumber FAILED: %d\n",  tally.failed);
		printf("\tNumber ONLINE: %d\n",  tally.online);
	}
}

