
/* Get a port value from the circuit */

#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>

#define MAX_PORT_BYTES	4096

char data[MAX_PORT_BYTES];

main(argc, argv)
	int argc;
	char *argv[];
	{
	int port, value, nbits, portbytes, i;

	if(argc != 2) {
		fprintf(stderr, "usage: tmgetvar name\n");
		exit(1);
		}

	tm_init("");

	if((port = tm_open(argv[1], "r")) < 0) {
		printf("tmgetvar: Can't open port %s\n", argv[1]);
		exit(1);
		}

	if((nbits = tm_get_port_width(argv[1])) < 0) {
		printf("tmgetvar: Can't get width of port %s\n", argv[1]);
		exit(1);
		}

	portbytes = (nbits + 7) / 8;

	if(portbytes > MAX_PORT_BYTES) {
		printf("tmgetvar: port too wide\n");
		exit(1);
		}

	if(tm_read(port, data, portbytes) != portbytes) {
		fprintf(stderr, "tmgetvar: error in reading from port\n");
		exit(1);
		}

	if(portbytes > 4) {
		for(i=0; i<portbytes; i++) {
			printf("%2X ", data[i] & 0xFF);
			}
		printf("\n");
		tm_close(port);
		exit(0);
		}

	value = 0;

	if(htons(1) == 1) {
		/* This machine is big-endian */

		for(i=0; i<portbytes; i++) {
			value = (value << 8) | (data[i] & 0xFF);
			}
		}
	else {
		/* This machine is little-endian */

		for(i=0; i<portbytes; i++) {
			value = (value << 8) | (data[portbytes - 1 - i] & 0xFF);
			}
		}

	printf("%d 0x%x\n", value, value);

	tm_close(port);
	exit(0);
	}
