//ICC-AVR application builder : 2012-02-21 오후 3:48:58
// Target : M128
// Crystal: 16.000MHz

#include <iom128v.h>
#include <macros.h>
#include <stdio.h>

#define SIZE	   100

volatile unsigned char data[100]={0,};
volatile int come=0, go=0;

// printf 함수 사용시 추가할 것. 
int putchar(char c) 
{ 
    while (((UCSR0A>>UDRE0)&0x01) == 0) ;  // UDRE, data register empty 
        
    UDR0 = c; 
    return c; 
} 



void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0x00;
 PORTB = 0x00;
 DDRB  = 0x00;
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x00;
 PORTE = 0x00;
 DDRE  = 0x00;
 PORTF = 0x00;
 DDRF  = 0x00;
 PORTG = 0x00;
 DDRG  = 0x00;
}

//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart0_init(void)
{
 UCSR0B = 0x00; //disable while setting baud rate
 UCSR0A = 0x00;
 UCSR0C = 0x06;
 UBRR0L = 0x67; //set baud rate lo
 UBRR0H = 0x00; //set baud rate hi
 UCSR0B = 0x98;
}

#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
 //uart has received a character in UDR
 data[come++] = UDR0;
 if(come >= SIZE){
 	come = 0;
 }
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 XDIV  = 0x00; //xtal divider
 XMCRA = 0x00; //external memory
 port_init();
 uart0_init();

 MCUCR = 0x00;
 EICRA = 0x00; //extended ext ints
 EICRB = 0x00; //extended ext ints
 EIMSK = 0x00;
 TIMSK = 0x00; //timer interrupt sources
 ETIMSK = 0x00; //extended timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}

int check(void){
	if(come!=go){
		return 1;
	}else{
		return 0;
	}
}

//
void main(void)
{
 init_devices();
 //insert your functional code here...
 come = go = 0;
 
 while(1){
 	if(check()){
		putchar(data[go++]);
	}
	if(go >= SIZE){
		 go = 0;
	}
 }
}

