/*
	STDECHO.C:

	STDIO device echo program. This program demonstrates how to use the
	stdio window as an AASC device.
*/

#use aascdio.lib			//	include the driver for the stdio device

main() {
	char rBuf[0x400];
	char wBuf[0x400];
	auto char localBuf[0x400];
	auto unsigned count;
	auto CHANNEL chan;
	auto char *pCur;
	auto unsigned remaining;

	_GLOBAL_INIT();	
	chan = aascOpen(DEV_STDIO,						//	open the stdio device
		0,
		0,
		NULL);
	aascSetReadBuf(chan,rBuf,sizeof(rBuf));	//	assign read buffer
	aascSetWriteBuf(chan,wBuf,sizeof(wBuf));	//	assign write buffer
	aascTxSwitch(chan,1);							//	turn on the receiver
	aascRxSwitch(chan,1);							//	turn on the transmitter

	aascPrintf(chan,"Type something!\n\r");	//	simple prompt
	while (1) {											//	echo for ever
		_dioServer();									//	this needs to be executed
															//	periodically
		hitwd();											//	hit watchdog

		remaining =										//	remember how many we got
			aascReadBlk(								//	from reading the channel
				chan,										//	chan
				localBuf,								//	to local buffer
				sizeof(localBuf),						//	up to this size
				0);										//	but read as many as possible
		pCur = localBuf;								//	starting point of transmission

		while (remaining) {							//	while there is more to transmit
			_dioServer();								//	call this periodically
			count =										//	remember how many we sent this
				aascWriteBlk(							// time
					chan,									//	to channel "chan"
					pCur,									//	starting at pCur
					remaining,							//	send this many bytes
					0);									//	as many as possible
			pCur += count;								//	increment the starting point
			remaining -= count;						//	decrement remaining
			hitwd();										//	hit watchdog
		}
	}
}
