/*******************************************************/
/* file: ports.c                                       */
/* abstract:  This file contains the routines to       */
/*            output values on the JTAG ports, to read */
/*            the TDO bit, and to read a byte of data  */
/*            from the prom                            */
/*                                                     */
/*******************************************************/
#include "ports.h"
#include "stdio.h"

int JTAG_ReadWrite(unsigned int, unsigned int, unsigned int *pReadValue, int);
void VIB_Wait2(int Timer, int us);

unsigned int ReadByte_index;
extern unsigned char *fwUpdateBuffer;

unsigned int myTMS;
unsigned int myTDI;
unsigned int myTDO;

void JTAGInit()
{
	myTMS = 0;
	myTDI = 0;
	myTDO = 0;
	ReadByte_index = 0;
}

/* if in debugging mode, then just set the variables */
void setPort(short p, short val)
{
	static unsigned int oldTCK = 0;

	switch(p)
	{
	case TMS:
		myTMS = (unsigned int)val;
		break;
	case TDI:
		myTDI = (unsigned int)val;		
		break;
	case TCK:
		if(oldTCK == 0 && val == 1)
		{
			JTAG_ReadWrite(myTMS, myTDI, &myTDO, 1);
			myTDO >>= 31;
		}
		oldTCK = val;
		break;
	}
}


/* toggle tck LH */
void pulseClock()
{
    setPort(TCK,0);  /* set the TCK port to low  */
    setPort(TCK,1);  /* set the TCK port to high */
}


/* read in a byte of data from the prom */
void readByte(unsigned char *data)
{
	*data = fwUpdateBuffer[ReadByte_index];
	ReadByte_index++;
}

/* read the TDO bit from port */
unsigned char readTDOBit()
{
	return (unsigned char)myTDO;
}


/* Wait at least the specified number of microsec.                           */
/* Use a timer if possible; otherwise estimate the number of instructions    */
/* necessary to be run based on the microcontroller speed.  For this example */
/* we pulse the TCK port a number of times based on the processor speed.     */
void waitTime(long microsec)
{
    setPort( TCK, 0 );
	VIB_Wait2(0, microsec);
}
