#include <sys/bios.h>

void renda( void );

int key;
int ikey;
int sw1 = 0;
int sw2 = 0;
unsigned int ch1 = '0';
unsigned int ch2 = '0';
unsigned int ch3 = '0';
unsigned int ch4 = '0';
unsigned int tim1;
unsigned int tim2;
unsigned int ch;

/*メインループ*/
void main(void){

	text_screen_init();
	key_set_repeat( 4, 0);

	text_put_string( 0, 0, "＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊");
	text_put_string( 0, 1, "＊");
	text_put_string( 27, 1, "＊");
	text_put_string( 0, 2, "＊");
	text_put_string( 27, 2, "＊");
	text_put_string( 0, 3, "＊");
	text_put_string( 27, 3, "＊");
	text_put_string( 0, 4, "＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊");
	text_put_string( 10, 2, "連打マシーン");
	text_put_string( 10, 8, "のこり10秒");
	text_put_string( 11, 10, "0000打！");
	text_put_string( 8, 15, "Ａ，Ｘ，Ｙ・・・連打！");
	text_put_string( 10, 16, "Ｂ　　・・・クリア");
	text_put_string( 8, 17, "ＳＴＡＲＴ・・・終了");

	for (;;){
		key_wait();
		key = key_press_check();
		if(key == KEY_START) break;
		if(key == KEY_B){
			text_put_string( 13, 8, "10");
			text_put_string( 11, 10, "0000");
			ch1 = '0';
			ch2 = '0';
			ch3 = '0';
			ch4 = '0';
			ch = '9';
			sw1 = 0;
			sw2 = 0;
		}
		if(key != 0 && key != 1 && key != KEY_B){
			if(sw1 == 1){
				sw1 = sw1;
			}
			if(sw1 == 0){
				renda();
			}
		}
	}
}

/*連打とカウントダウン*/
void renda( void ){

	tim2 = rtc_get_second();
	sw1 = 1;

	while(ch != '0'){
		ikey = key_hit_check();
		if(ikey == 0 || ikey == KEY_START || ikey == KEY_B){
			if(sw2 == 0){
				tim1 = rtc_get_second();
					if(tim1 != tim2){
						ch = '9';
						text_put_string( 13, 8, "0");
						text_put_char( 14, 8, ch);
						tim2 = tim1;
						sw2 = 1;
					}
			}
			if(sw2 == 1){
				tim1 = rtc_get_second();
				if(tim1 != tim2){
					ch = ch -1;
					text_put_char( 14, 8, ch);
					tim2 = tim1;			
				}
			}
		}
		if(ikey != 0 && ikey != KEY_START && ikey != KEY_B){
			if(sw2 == 0){
				tim1 = rtc_get_second();
				if(tim1 != tim2){
					ch = '9';
					text_put_string( 13, 8, "0");
					text_put_char( 14, 8, ch);
					tim2 = tim1;
					sw2 = 1;
				}
			}
			if(sw2 == 1){
				if(ch1 == '9'){
					if(ch2 == '9'){
						if(ch3 == '9'){
							ch4 = ch4 +1;
							text_put_char( 11, 10, ch4);
							ch3 = '0';
							text_put_char( 12, 10, ch3);
						}
						else{
						ch3 = ch3 +1;
						text_put_char( 12, 10, ch3);
						ch2 = '0';
						text_put_char( 13, 10, ch2);
						}
					}
					else{
						ch2 = ch2 +1;
						text_put_char( 13, 10, ch2);
						ch1 = '0';
						text_put_char( 14, 10, ch1);
					}
				}
				else{
            	   	ch1 = ch1 +1;
					text_put_char( 14, 10, ch1);
				}
				tim1 = rtc_get_second();
				if(tim1 != tim2){
					ch = ch -1;
					text_put_char( 14, 8, ch);
					tim2 = tim1;
				}
			}
		}
	}
}
