/*  WAITUNTL.C - A program to cause the computer to wait until a specified */
/*time before terminating.  Useful in .BAT files for bulletin boards and   */
/*similar situations where time may be a factor in when to run programs.   */

#include <stdio.h>
#include <dos.h>
#define		NUL		0x0000

main(argc, argv)

int argc;
char *argv[];

{
	struct time dostime;
	int	   wait_hour, wait_minute, oldsec, target_time, keyscan, new_time;
    char   wait_time[6], temp[3], semi_colon;

	temp[2] = NULL;
    keyscan = 0;

/*	check for right number of arguments	*/
	if (argc == 1)
		{
			printf("\nUsage:  WAITUNTL xx:xx\n");
			exit(1);
		}

/*	get wait_time from command line */
	strcpy( wait_time, argv[1]);

/*	convert wait_hour to int and check  */
	strncpy( temp, wait_time, 2);
	wait_hour = atoi( temp );
    if ( (wait_hour < 0) || (wait_hour > 23) )
		{
			printf("\nBad hour.  Must be between 0 and 23.  Aborting...\n");
			exit(1);
		}

/*	check argv[1][2] for ":"  */
	semi_colon = argv[1][2];
    if ( semi_colon != ':' )
		{
			printf("\nUsage:  WAITUNTL xx:xx\n");
			exit(1);
		}

/*	get & test minute value	 */
	strncpy( temp, &argv[1][3], 3);
	wait_minute = atoi( temp );
    if ( (wait_minute < 0) || (wait_minute > 59) )
		{
			printf("\nBad minute.  Must be between 0 and 59.  Aborting...\n");
			exit(1);
		}

	target_time = wait_hour * 100 + wait_minute; /*	set target time */

	gettime(&dostime);
	oldsec = dostime.ti_sec;

	printf("\n   Waiting until %s:00\n\n", wait_time);
	printf("Starting time is %02d:%02d:%02d\n", dostime.ti_hour,
					dostime.ti_min, dostime.ti_sec);
	printf(" Current time is %02d:%02d:%02d", dostime.ti_hour,
					dostime.ti_min, dostime.ti_sec);

	do
		{
			do
				{ gettime(&dostime);
					if ( kbhit() != 0)
						{
							keyscan = getch();
							if ( keyscan == 03 ) exit(1);
						}
					new_time = (dostime.ti_hour * 100) + dostime.ti_min;
					if (oldsec != dostime.ti_sec)
						{ printf("\b\b\b\b\b\b\b\b%02d:%02d:%02d",
							dostime.ti_hour, dostime.ti_min, dostime.ti_sec);
							oldsec = dostime.ti_sec;
						}
				} while (dostime.ti_sec > 0);
		} while (new_time != target_time);
	printf("\n");
}
