
#include <stdio.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>

#define LOCAL
#include "uart_getchar.h"

#define TRUE 1
/********************************************
This is just a place-holder 
*******************************************/
int uart_getchar(char c, FILE *stream) {
    return 0;
}


SIGNAL (SIG_UART_RECV) {
        unsigned char temp;
        temp = UDR;
        switch(rx_state) {
          case DBA: // Data Bufer Available
            {
            int i;
            rx_ptr = rx_buffer;
            // clean out the buffer
            for (i=0; i< sizeof(rx_buffer); ++i) rx_buffer[i]=0;
                if(temp != '\r' && temp !='\n'){
                    *rx_ptr++ = temp;
                    rx_state = DRIP;
                }
            }
            break;
        case DRIP: // Date Receive In Progress
            if(rx_ptr < &rx_buffer[RX_BUFFER_SZ]){
                // bufer is not full
                if(temp == '\r' || temp =='\n'){
                    if(rx_ptr > rx_buffer){
                        new_auto_bearing = TRUE;
                        rx_state = WFDBA;
                    }
                }
                else {
                    *rx_ptr++ = temp;
                }
            }
            break;
        case WFDBA: // Wait For Data Buffer to be Available
            if(!new_auto_bearing){
                // mainline has processes data
                {
                int i;
                rx_ptr = rx_buffer;
                // clean out the buffer 
                for (i=0; i< sizeof(rx_buffer); ++i) rx_buffer[i]=0;
                *rx_ptr = temp;
                rx_state = DRIP;
                }
            }
            else{
                rx_state = WFNR; // Wait For Next Record
            }
            break;
        case WFNR: // overflow - Wait For Next Record to start again
            if(temp == '\r' || temp =='\n'){
                rx_state = DBA;
            }

            break;
        }
}
