#include <avr/io.h>
#include "uart.h"

static int uart_putchar(char c, FILE *stream);

FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);

void uart_init()
{
    DDRD |= 1 << 1; // TX
    UART_BAUD_REGH  = UBRRH_VALUE;//(BAUDRATE>>8);
    UART_BAUD_REGL  = UBRRL_VALUE;//BAUDRATE;               // set baud rate

#if USE_2X
    UART_CTRL_REGA |= (1 << USE_2X);
#else
    UART_CTRL_REGA &= ~(1 << USE_2X);
#endif

    UART_CTRL_REGB |= (1<<UART_TXEN_BM)
                     //|(1<<UART_RXEN_BM)
                     |(1<<UART_RXCIE_BM);     // enable receiver and transmitter

    UART_CTRL_REGC |= (1<<UART_URSEL_BM)
                     |(1<<UART_UCSZ0_BM)
                     |(1<<UART_UCSZ1_BM);             // 8bit data format

    stdout = &uart_output;
}

static int uart_putchar(char c, FILE *stream) {
    if (c == '\n') {
        uart_putchar('\r', stream);
    }
    loop_until_bit_is_set(UART_CTRL_REGA, UART_UDRE_BM);
    UART_DATA_REG = c;
    return 0;
}

void read_sync(char buffer[], uint8_t buffersize, uint8_t * bufferindex){
    for(int i=0; i < buffersize; i++){
        buffer[i]=0;
    }
    *bufferindex=0;

    char input;
    do{
        while ((UART_CTRL_REGA & (1 << UART_RXC_BM)) == 0);
        input = UART_DATA_REG;

        putchar(input); //echo
        buffer[*bufferindex]=input;
        *bufferindex=*bufferindex+1;
    }while(!(input == '\n' || input == '\r'));
    buffer[*bufferindex]=0;
    putchar('\n');
}


