/* Example pro http://www.abclinuxu.cz/blog/Vallhala/2007/3/25/174160 */

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

#define SECTION_MAX 24
#define DAY_SECOND 86400
#define TIME_SECOND(h, m, s) (((h) * 3600) + ((m) * 60) + (s))

static int section[SECTION_MAX];

static int who_section(int actual_time)
{
  int i;

  for (i = 0; i < SECTION_MAX; ++i) {
    if (i == SECTION_MAX-1)
      return i;

    if (section[i+1] == -1)
      return i;

    if ((actual_time >= section[i]) && (actual_time < section[i+1]))
      return i;
  }

  return 0;
}

int main(void)
{
  int i;
  int actual_section;
  int actual_time;
  int wait_time;
  time_t the_ticks;
  struct tm *the_time;

  for (i = 0; i < SECTION_MAX; ++i)
    section[i] = -1;

  the_ticks = time(NULL);
  the_time = localtime(&the_ticks);

  for (i = 0; i < 4; ++i)
    section[i] = TIME_SECOND(the_time->tm_hour, the_time->tm_min, the_time->tm_sec + (i * 6));

  //section[0] = TIME_SECOND(9, 0, 0); 
  //section[1] = TIME_SECOND(10, 0, 0); 
  //section[2] = TIME_SECOND(17, 0, 0); 
  //section[3] = TIME_SECOND(18, 0, 0); 

  for (i = 0; i < SECTION_MAX; ++i)
    printf("section[%i] = %i\n", i, section[i]);

  while (1) {
    the_ticks = time(NULL);
    the_time = localtime(&the_ticks);

    actual_time = TIME_SECOND(the_time->tm_hour, the_time->tm_min, the_time->tm_sec);
    actual_section = who_section(actual_time);

    if ((actual_section == SECTION_MAX-1) || (section[actual_section+1] == -1))
      wait_time = DAY_SECOND - actual_time + section[0];
    else
      wait_time = section[actual_section+1] - actual_time;

    printf("\n%02i:%02i:%02i\n", the_time->tm_hour, the_time->tm_min, the_time->tm_sec);
    printf("actual_time = %i\n", actual_time);
    printf("section[%i] = %i\n", actual_section, section[actual_section]);
    printf("wait_time = %i\n", wait_time);

    switch (actual_section) {
      case 0:
        printf("A\n");
        break;

      case 1:
        printf("B\n");
        break;

      case 2:
        printf("C\n");
        break;

      case 3:
        printf("D\n");
        break;

      /* ... */

      default:
        break;
    }

#ifdef __WIN32__
    sleep(1000 * wait_time);
#else /* Linux */
    sleep(wait_time);
#endif
  }
}