.include "nios_macros.s"

.text

.equ	JTAG_UART_BASE_ADDR,	0x00088000
.equ	MY_DEVICE_BASE_ADDR,	0x00000000
.equ	STACK_BASE_ADDR,		0x00088000

/*****************************************************************************/
/* Main Program                                                              */
/*   Reads in characters from a JTAG UART and sends them through memory to   */
/*  another processor. Receives characters from another processor and prints */
/*  them to a JTAG UART.                                                     */
/*                                                                           */
/* r8  - JTAG UART Address                                                   */
/* r9  - The address of outgoing text                                        */
/* r10 - The address of incoming text                                        */
/* r16 - Character to be displayed or that was received                      */
/* r17 - Data from the memory                                                */
/* r18 - Data from the JTAG UART                                             */
/*****************************************************************************/
.global _start
_start:
	movia	sp,  STACK_BASE_ADDR
	mov	fp,  sp

	movi	r2,  1

	movia	r8,  JTAG_UART_BASE_ADDR
	movia	r9,  MY_DEVICE_BASE_ADDR
	addi	r10, r9, 8

	stwio	r16, 0(r9)				/* Clear memory locations                */
	stwio	r16, 4(r9)
	stwio	r16, 0(r10)
	stwio	r16, 4(r10)

CHECK_INPUT:
	ldwio	r17, 4(r9)				/* Check to see if I can pass data to    */
	bne	r17, r0, CHECK_OUTPUT		/*   other processor.                    */

	ldwio	r18, 0(r8)				/* Checks if UART has new data           */
	andi	r16, r18, 0x00FF
    andi  r18, r18, 0x8000			/* Check if character was read           */
	beq	r18, r0, CHECK_OUTPUT

	stwio	r16, 0(r9)				/* Write the character to the memory     */
	stwio	r2,  4(r9)				/* Set the send data status flag         */

ECHO_CHAR:
	ldwio	r18, 4(r8)				/* Echo characters to the terminal       */
	andhi r18, r18, 0xffff
	beq		r18, r0, CHECK_INPUT
	stbio	r16, 0(r8)


CHECK_OUTPUT:
	ldwio	r18, 4(r8)				/* Checks if UART is ready for data      */
	andhi r18, r18, 0xffff			/* Check for write space                 */
	beq   r18, r0, CHECK_INPUT		/* Go to inputting if no write space     */

	ldwio	r17, 4(r10)				/* Check to see if the other processor   */
	beq	r17, r0, CHECK_INPUT		/*   has sent any data.                  */

	ldwio	r16, 0(r10)				/* Load character                        */
	stbio	r16, 0(r8)				/* Write the character to the JTAG UART  */
	stwio	r0,  4(r10)				/* Clear the receive data status flag    */

	br	CHECK_INPUT

END:
	br	END
	
.end

