/* timestamp-incrementor.c
 *
 * Yoann Aubineau -- yoann.aubineau at free.fr
 * 2004-11-02
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int timestamp_inc( char date[15] )
{
	int i, c = 1;
	char min[7] = {  0,  0,  1,  1,  0,  0,  0 };
	char max[7] = { 99, 99, 12, 31, 23, 59, 59 };

	for( i = 0; i < 14; i += 2 )
		date[i] = ( date[i] & 0x0F ) * 10 + ( date[i+1] & 0x0F );	/* ASCII to decimal */

	if( date[4] == 2 ) {				max[3] = 28;		/* February */
		if( !( date[2] & 0x03 ) &&   date[2] ||
		    !( date[0] & 0x03 ) && ! date[2] )	max[3] = 29;		/* leap year */
	} else if( date[4] == 4 || date[4] ==  6 || 
	           date[4] == 9 || date[4] == 11 ) 	max[3] = 30;		/* 30-day months */

	for( i = 12; i >= 0; i -= 2 ) {
		if( c && ++date[i] > max[i>>1] )  date[i] = min[i>>1];		/* increment */
		else 				  c = 0;			/* carry */
		date[i+1] = ( date[i] % 10 ) | 0x30;
		date[i]   = ( date[i] / 10 ) | 0x30;				/* decimal to ASCII */
	}

	return ( c )? -1 : 0;
}

int main( int argc, char* argv[] )
{
	char* date = NULL;

	if (argc > 1) 	date = argv[1];
	else		date = strdup("19991231235959");

	do {
		printf( "%s\n", date );
		if( timestamp_inc( date ) < 0 )	break;
		else				printf( "%s\n", date );
	} while( 0 );

	return EXIT_SUCCESS;
}
