#include "usart.h"

#define txBufferLen 32 
#define rxBufferLen 32 


unsigned char put = NOTTRANSMITTING ;

char txBuffer[txBufferLen]  ; 


unsigned char txRearEnd = 0 ; 
unsigned char txFrontEnd = 0 ; 


char rxBuffer[rxBufferLen] ; 

unsigned char rxRearEnd = 0 ; 
unsigned char rxFrontEnd = 0; 


void usartInit(unsigned int baudRate)
{
        /* Set Baud Rate here */
        UBRRH = ( unsigned char ) ( baudRate >> 8 ) ;
        UBRRL = ( unsigned char ) ( baudRate ) ;
        /*Enable Transmit and Receive */
        UCSRB = ( 1 << RXEN ) | ( 1 << TXEN )  /* | (1 << RXCIE ) | ( 1 << TXCIE ) */ ;
        /* 8 bit and 1 stop bit */
        UCSRC = (1<<URSEL) | (3<<UCSZ0);
}

void txChar_poll ( char data ) 
{
	while ( ! ( UCSRA  & ( 1 << UDRE )  ) ) ;
	UDR = data  ; 
}
char rxChar_poll ( void ) 
{
	while ( ! ( UCSRA & ( 1 << RXC ) ) ) ;
	return UDR ; 

}	
int rxChar( void )
{
	int  val ; 
	if ( rxFrontEnd == rxRearEnd )
		return  -1 ; 
	val = (int) rxBuffer[rxRearEnd] ;
	rxRearEnd = ( rxRearEnd + 1 ) & ( rxBufferLen - 1 ) ; 
	return val ; 
}

void txString (char *string)
{
	while ( *string != '\0' )
	{
		txBuffer[txRearEnd] = *string ;
		txRearEnd = ( txRearEnd + 1 ) & ( txBufferLen -1 ) ;
		*string++;
	}
	if ( put == NOTTRANSMITTING ) 	
	{
		put = TRANSMITTING ; 
		UDR  = txBuffer[txFrontEnd];
	}	

}

void txChar (  char data )
{
        txBuffer[txRearEnd]  =  data ; 
	txRearEnd = ( txRearEnd + 1 ) & ( txBufferLen - 1 );
	if ( put == NOTTRANSMITTING ) 
	{
		put = TRANSMITTING ; 
		UDR = txBuffer[txFrontEnd] ; 								
	}
}
/*
ISR( SIG_USART_RECV )
{
	rxBuffer[rxFrontEnd] = UDR ; 
	sei();	
	rxFrontEnd =  ( rxFrontEnd + 1 ) & ( rxBufferLen - 1 ) ;  
	
}

ISR( SIG_USART_TRANS )
{
	sei();
	txFrontEnd = ( txFrontEnd + 1 ) & ( txBufferLen - 1 ) ;
	if ( txFrontEnd == txRearEnd ) 
		
		put = NOTTRANSMITTING  ;
		
	else 
		UDR = txBuffer[txFrontEnd] ; 
} 
*/
