/** \file main.c
 * \brief Program Template
 * 
 * $Id: avr_auto.c 40 2006-10-28 17:27:51Z robocon2006 $
 */
/**
 * Hong Kong Univerisity Of Science and Technology, Copyright (c) 2005-2007
 * Code for Robocon Electronics Quickstart Course
 */

// These are two very basic definition
// F_CPU specify the CPU Frequency, which is used in <util/delay.h>
#define F_CPU 14745600
// This one will give you access to the SFR
#include <avr/io.h>
#include <util/delay.h>

int main( void )
{
    char buf[200];
    char cnt = 0;

    // 115200 8-N-1
    UBRR0H = 0;
    UBRR0L = 15;
    UCSR0A = _BV(U2X0);
    UCSR0B = _BV(RXEN0) | _BV(TXEN0);
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

    while (1) {
        char c;
        cnt = 0;
        do {
            // Wait till we have got something
            while (! (UCSR0A & _BV(RXC0)));
            c = UDR0;
            buf[cnt++] = c;
            // Is this the end of line?
        } while (!(c == 13 || c == 10));
        for (uint8_t i = 0; i < cnt; i++)
        {
            UDR0 = buf[i];
            // Wait until we have finished sending
            while (! (UCSR0A & _BV(TXC0)) );
            // Clear the completion flag
            UCSR0A |= _BV(TXC0);
        }
        // Print an new line
        UDR0 = 10;
        while (! (UCSR0A & _BV(TXC0)) );
        UCSR0A |= _BV(TXC0);
        UDR0 = 13;
        while (! (UCSR0A & _BV(TXC0)) );
        UCSR0A |= _BV(TXC0);
    }
}