/**************************************************

 * File: serial.c       Project by: David Hodgdon *

 * Class: ECE476        Instructor: Bruce Land    *         

 *************************************************/
#ifdef ATMEL
#include "serial.h"   
#include "lcd.h"
#include <Mega32.h>     
#include <stdio.h>
static char charReceived;
static char pointerOnCode=1;



void initialize_uart() {
  int i;           
#if 0
  //set up timer 0  

  TIMSK=0x12;		//turn on timer 0 cmp match ISR 

  OCR0 = 250;  	//set the compare re to 250 time ticks

  	//prescalar to 64 and turn on clear-on-match

  TCCR0=0b00001101;  // prescalar 


  // set up timer 1

  // 2^24

  OCR1A	    = 0;//65536-15625;    // 2^24 / 2^10 = 2^14

  TCCR1A	= 0b10000000; // 1024 prescalar      

  TCCR1B  = 0b00000100;
  TCNT1 = 0;
#endif

  //crank up the ISRs

  #asm

  	sei
  #endasm    
  UCSRB = 0x10 + 0x08 ;	// set up uart

  UBRRL = 103;                 
}
                           




char SerialUseCode() {
	pointerOnCode=1;
}
char SerialUseDATA() {
	pointerOnCode=0;
}

char SerialGetChar() {
	char c;
	if(pointerOnCode)	putchar(SerialNextChar);
	else				putchar(SerialNextCharDATA);
	c=getchar();      
	switch(c) {
		case '\r': c='\n';
	}
	return c;
}

/***************************************************************

 * We'll send the open file command, the number of characters, * 

 * then the actual characters                                  *

 * returns: 0 if worked, -1 if not

 ***************************************************************/
#ifdef ATMEL         
#if 0
char SerialFOpen(flash char * filename) {  
#else

char SerialFOpen(char * filename) {  
#endif

#else 
char SerialFOpen(char * filename) {  
#endif

	char c,len,i;    
	for(len=0;filename[len]!='\0';len++);//len=strlen(fname);

	putchar(SerialOpenFile);
	putchar(len);     
	for(i=0;i<len;i++) {
		putchar(filename[i]);
	}
	c=getchar();
	if(c==SerialFailureOpeningFile) {    
		sprintf(lcd_buffer, "Error Opening File\n");
    		LCDPrintString(lcd_buffer);   
		while(1);
	}
	return 0;
}

void SerialReopenFile(int num) {
	putchar(SerialResetPointer);
	putchar((num>>8 )&0xff);
	putchar((num    )&0xff);    
}

void SerialReopenFileDATA(int num) {
	putchar(SerialResetPointerDATA); 
	putchar((num>>8 )&0xff);
	putchar((num    )&0xff);	
}

#endif