#include <avr/io.h>
#include "lcd.h"
#include <avr/interrupt.h>



#define F_CPU 1000000UL  // 1 MHz

#include <util/delay.h>
#include <inttypes.h>

uint8_t temp;
int PINS, pw0, pw1, pw2, pw3,  enterPW, pwCounter, entpw0,entpw1,entpw2,entpw3, enabled;
volatile int cardIN;

ISR(INT0_vect)
{
	if(enterPW == 1)
	{
		_delay_ms(50);
		temp = PIND; 
		temp &= 0x33;
		switch(temp)
		{
		case 0x00 :
			PINS = 0;
			disp_writeCh('*');
		break;

		case 0x01 :
			PINS = 1;
			disp_writeCh('*');
		break;

		case 0x02 :
			PINS = 2;
			disp_writeCh('*');
		break;

		case 0x03 :
			PINS = 3;
			disp_writeCh('*');
		break;

		case 0x10 :
			PINS = 4;
			disp_writeCh('*');
		break;

		case 0x11 :
			PINS = 5;
			disp_writeCh('*');
		break;

		case 0x12 :
			PINS = 6;
			disp_writeCh('*');
		break;

		case 0x13 :
			PINS = 7;
			disp_writeCh('*');
		break;

		case 0x20 :
			PINS = 8;
			disp_writeCh('*');
		break;

		case 0x21 :
			PINS = 9;
			disp_writeCh('*');
		break;

		}
		switch(pwCounter)
		{
		case 0:
			entpw0 = PINS;
		break;

		case 1:
			entpw1 = PINS;
		break;

		case 2:
			entpw2 = PINS;
		break;

		case 3:
			entpw3 = PINS;
		break;
		}
		pwCounter++;
		if(pwCounter == 4)
		{
			int result = pw_match(entpw0,entpw1,entpw2,entpw3);
			if(result == 1)
			{
				disp_Welcome();
				_delay_ms(50000);
				_delay_ms(1000);
				_delay_ms(1000);
			}
			else
			{
				disp_wrongPIN();
				_delay_ms(50000);
				_delay_ms(1000);
				_delay_ms(1000);
			}
			cardIN = 0;
			pwCounter = 0;
			entPW = 0;
		}
	}
	_delay_ms(500);

}

int main()
{
	cli();			//enable interrupt
	DDRC = 0xff;
	DDRB = 0xff;
	DDRA = 0xff;
	DDRD = 0x00;
	MCUCR = 0x03;	
	GICR = 0x40;
	SREG = 0x80;
	temp=0x00;
	PINS = 0x00;
	cardIN = 0;
	enterPW = 0;
	pwCounter = 0;
	pw0 = 0;
	pw1 = 1;
	pw2 = 2;
	pw3 = 3;

	sei();			//disable interrupt
   

	disp_init();	
	disp_home();
	disp_hello();

	while(1)
	{

		disp_home();
		disp_hello();
		while(cardIN != 1)
		{
			checkforCardIN();
			_delay_ms(500);

		}
		disp_writePIN();
		disp_moveBotRow();
		enterPW = 1;
		while(cardIN != 0);
	}
}

void
checkforCardIN()
{
	temp = PIND;
	temp &= 0x80;
	if(temp == 0x00)
	{
		cardIN = 1;
	}
}

int 
pw_match(int p0,int p1,int p2, int p3)
{
	if(p0 == pw0, p1==pw1, p2==pw2, p3==pw3)
	{
		return 1;
	}
	return 0;
}


