#include <pic.h>
#include	"delay.h"
#include "lcd.h"

__CONFIG(XT & WDTDIS & PWRTEN & BOREN & LVPDIS);

static unsigned char	xmsec;
static unsigned char	seconds;
static unsigned char	key;

void setup_port() {

	ADCON0	= 0b00000000;
	ADCON1	= 0b00000111;
	OPTION	= 0b10000111;
	TRISA	= 0b00100000;
	TRISB	= 0b00000000;
	TRISC	= 0b10111111;
	PORTA	= 0b00000000;
	PORTB	= 0b00000000;
	PORTC	= 0b00000000;

	TMR0	= -PRELOAD;		// preload timer
	T0IE	= 1;
	GIE	= 1;			//interrupt enable

}

unsigned char switch_read() {

	return(~PORTC&0x3F);
}

unsigned char switch_test() {

	unsigned char sw_data;

test_switch_on:
				//SWが押されるまで待つ
	while(!switch_read());
	sw_data = switch_read();
	DelayMs(30);
	if (sw_data != switch_read()) goto test_switch_on;

test_switch_off:
				//SWが離されるのを待つ
	while(switch_read());
	DelayMs(30);
	if (switch_read()) goto test_switch_off;

	return(sw_data);
}

static void interrupt intx(void) 
{
	if(T0IF == 1){
	  xmsec++;
	  TMR0 += -PRELOAD;	// re-load timer
	}
	T0IF = 0;	
}

main() {

	unsigned char key0,key1,count,countx,mark,mark0;
	unsigned char bpos,tdata,ttt,tcurs,first;

	setup_port();

	lcd_init();
	lcd_clear();
	lcd_prints(0,	"*JJY clock      ");
	lcd_prints(0x40,	"   040505 by K.I");

	blink_led(1);
	lcd_curs(0);

	countx = 0;
	count = 0;
	first = 0;
	mark = ' ';
	tcurs = 0x40;

	while(1) {
	  if (!xmsec) {		//50ms毎にチェック
	    xmsec += -5;

// key check
	    key1 = switch_read();
	    if (key0 == key1) key = key0;
	    key0 = key1;
	    if (first) {
	      lcd_curs(0x4E);
	      lcd_puthex2(key);
	    }

// seconds display
	    lcd_curs(11);
	    lcd_puthex2(seconds);
	    lcd_write(' ');
	    lcd_write(mark);
	    lcd_curs(tcurs);

	    switch(countx) {
	      case 2:
	      case 3:
		mark = 'M';
		break;
	      case 5:
	      case 6:
		mark = '1';
		break;
	      case 8:
	      case 9:
		mark = '0';
		break;
	      default:
		mark = '?';
	    }

// JJY to LED display
	    if (RA5) {
	      LED = 0;
	      if (count) {
	        countx = count;
	        count = 0;
	      }
	    }
	    else {
	      if (!LED) {
	        seconds++;
	        if (mark != 'M' &&((tcurs < 0x48 && bpos != 4) ||
			tcurs==0x48 || (tcurs == 0x4A && bpos < 7)))
		 tdata = tdata << 1;
	        switch (mark) {
	          case 'M':
		   if (mark0 == 'M') {
	              seconds = 1;
		     bpos = 1;
		     tcurs = 0x40;
		   }
	            else {
	              seconds = (seconds&0xF0)+0x10;
	              if (seconds == 0x60) seconds = 0;
		     bpos = 0;
		     ttt = tdata;
	    	     lcd_curs(tcurs);
		     lcd_puthex2(ttt);
		     if (tcurs<0x4A) tcurs += 2;
	            }
		   if (!first) {
		     lcd_prints(0x40,"                ");
		     tcurs = 0x40;
		     first = 1;
		   }
		   break;
		 case '0':
		   bpos++;
		   break;
		 case '1':
		   tdata |= 1;
		   bpos++;
		   break;
	        }
	        mark0 = mark;
	      }
	      LED = 1;
	      count++;
	    }
	  }
	}

}