#include <stdio.h>		/*  printf			*/
#include <stdlib.h>		/*  exit,atoi		*/
#include <time.h>		/*  clock,CLK_TCK	*/
#include <conio.h>		/*  kbhit			*/
#include <dos.h>		/*  bdos			*/

int wait1sec( int cnt )
{
	clock_t st=clock(), elaps, sec, oldsec=-1 ;
	int		ret=0 ;

	printf( "\x1b[33mあと      秒" ) ;
	printf( "\x1b[m   ( キー入力( ESC:RET=1, その他:RET=0 )で, 終了します. )" ) ;
	printf( "\x1b[33m" ) ;
	do {
		if ( kbhit() ) {
			if ( getch() == 0x1B ) ret = 1 ;
			bdos( 0x0C,0,0 ) ;
			break ;
		}
		elaps = clock() - st ;
		if ( elaps < 0 ) elaps *= (clock_t)-1 ;
		elaps /= CLK_TCK ;
		sec = cnt - elaps ;
		if ( oldsec != sec ) {
			printf( "\rあと %4d 秒 ",sec ) ;
			oldsec = sec ;
		}
	} while ( elaps < cnt ) ;
	return ret ;
}

void usage( void )
{
	printf( "Usage: timewait 待ち時間[秒単位]\n" ) ;
	printf( "                0 〜 3600\n" ) ;
	exit( -1 ) ;
}

int main( int ac,char *av[] )
{
	int		waitcnt, ret ;

	printf( "時間待ちプログラム (C) パオパオ 1994.\n" ) ;
	if ( ac != 2 ) usage() ;
	waitcnt = atoi( av[1] ) ;
	if ( waitcnt < 0 || waitcnt > 3600 ) usage() ;
	if ( !( ret = wait1sec( waitcnt ) ) ) {
		printf( "\x1b[m\rプログラムを終了します." ) ;
	} else {
		printf( "\x1b[m\rプログラムを中断します." ) ;
	}
	printf( "                                               \n" ) ;
	return ret ;
}

