#include <stdlib.h>
#include <stdio.h>
#include <avr/io.h>

#ifndef F_CPU
#warning "F_CPU not defined, using default 16000000UL"
#define F_CPU 16000000UL
#endif

#ifndef BAUD
#warning "BAUD not defined, using default 9600"
#define BAUD 9600
#endif

void console_init(void) __attribute__((naked)) __attribute__((section (".init8")));
int console_putchar(char c);
int console_getchar(void);

void console_init(void)
{
	UBRRL = (F_CPU / (BAUD * 16L) - 1)      & 0xFF;
	UBRRH = (F_CPU / (BAUD * 16L) - 1) >> 8 & 0x0F;
	UCSRB = _BV(RXEN) | _BV(TXEN);
	fdevopen(console_putchar, console_getchar, 0);
}

int console_putchar(char c)
{
	if (c == '\n')
		console_putchar('\r');
	loop_until_bit_is_set(UCSRA, UDRE);
	UDR = c;
	return 0;
}

int console_getchar(void) 
{
	loop_until_bit_is_set(UCSRA, RXC);
	return UDR;
}

