#ifndef _XTAL_FREQ
 #define _XTAL_FREQ 8000000
#endif
#include	<htc.h>
#include	"lcd.h"
#define	LCD_RS 		RA3
#define LCD_EN 		RC5
#define LCD_DATA	PORTB

void LCD_STROBE (void);

void zak100(void)
{
	__delay_us(100);
}

void
lcd_write(unsigned char c)
{
	__delay_us(70);
	LCD_DATA = ( ( c >> 4 ) & 0x0F );
	LCD_STROBE();
	LCD_DATA = ( c & 0x0F );
	LCD_STROBE();
}

/*
 * 	Clear and home the LCD
 */

void
lcd_clear(void)
{
	LCD_RS = 0;
	lcd_write(0x1);
	__delay_us(10);
}

/* write a string of chars to the LCD */

void
lcd_puts(const char * s)
{
	LCD_RS = 1;	// write characters
	while(*s)
		lcd_write(*s++);
}

/* write one character to the LCD */

void
lcd_putch(char c)
{
	LCD_RS = 1;	// write characters
	lcd_write( c );
}


/*
 * Go to the specified position
 */

void
lcd_goto(unsigned char pos)
{
	LCD_RS = 0;
	lcd_write(0x80+pos);
}
	
/* initialise the LCD - put into 4 bit mode */

void lcd_init()
{
	char init_value;

	init_value = 0x3;


	TRISB=0;
	TRISA=0;
	TRISC=0;

	LCD_RS = 0;
	LCD_EN = 0;
	
	__delay_ms(150); // Zabavqne sled puskane na zahranvane
	LCD_DATA	 = 0x3;
	LCD_STROBE();
	__delay_ms(5);

	LCD_DATA	 = 0x3;
	LCD_STROBE();
	zak100();
	
	LCD_DATA	 = 0x3;
	LCD_STROBE();
	zak100();

	LCD_DATA	 = 0x2;
	LCD_STROBE();
	zak100();
	
	LCD_DATA	 = 0x2;
	LCD_STROBE();
	LCD_DATA	 = 0x8;
	LCD_STROBE();
	zak100();

	LCD_DATA	 = 0x0;
	LCD_STROBE();
	LCD_DATA	 = 0x8;
	LCD_STROBE();
	zak100();

	LCD_DATA	 = 0x0;
	LCD_STROBE();
	LCD_DATA	 = 0x1;
	LCD_STROBE();
	__delay_ms(5);

	LCD_DATA	 = 0x0;
	LCD_STROBE();
	LCD_DATA	 = 0x6;
	LCD_STROBE();
	zak100();

	LCD_DATA	 = 0x0;
	LCD_STROBE();
	LCD_DATA	 = 0xC;
	LCD_STROBE();
	zak100();



	
LCD_RS = 1;
}


void LCD_STROBE(void)
{
	LCD_EN = 1;
	__delay_us(10);
	LCD_EN= 0;
}

void long_to_string (unsigned int input, char *str, char numdigits)
{
	char digit;
	int blank = 1;

	long_to_string_lz(input, str, numdigits);

	for (digit=0; digit < numdigits-1; digit++) 
	{
    	if (str[digit] == '0')
		{
			if (blank == 1) 
				str[digit] = ' ';
    	}
 	   else 
		{
			blank = 0;
    	}
	}
}


void long_to_string_lz (unsigned int input, char *str, char numdigits)
{
	char digit;
	for (digit=numdigits; digit > 0; digit--) 
	{
    	str[digit-1] = (input % 10) + '0';
    	input = input / 10;
  	}
  	str[numdigits] = 0;    // null-terminate the string
}