/*
 * Rubik's clock.
 *
 * This file is public domain, I just hate copy[left/right]s.
 *-------------
 * the main file
 */

/* I always do my includes like this :
 * 1 - the include of the corresponding .h file (in this one, there is no main.h)
 * 2 - the standard includes (stdio, Xlib, ...)
 * 3 - my own .h
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

#include "clock.h"
#include "screen.h"
#include "event.h"
#include "save.h"

/* the main function.
 * The one you code first.
 * As short as possible, you'll do everything somewhere else.
 * Don't forget to be as generic as possible, only high-level stuff here, only function calls.
 * No variables, or just globals that you put here because globals are bad practice, believe
 * me, very hard to maintain a code full of globals. Your brain gets lost very quickly and you make lotsa bugs.
 */
int main(void)
{
  struct timeval tv;
  CLOCK clock;
  SCREEN screen;
  EVENT event;

  /* init the randomizer (yes, this function should not be here, but well, you know... */
  gettimeofday(&tv, 0);
  srand(tv.tv_sec+tv.tv_usec);

  /* init_screen must come before init_clock, as we use &screen in init_clock */
  if (init_screen(&screen)==-1) {
    fprintf(stderr, "Error while initing the screen, sorry\n");
    return 1;
  }
  init_clock(&clock, &screen);
  if (load("saved.rcd", &clock)==-1)
    randomize_clock(&clock);
  draw_all(&clock, &screen);

  event.timer=0;
  while (clock.mode!=END) {
    wait_next_event(&event, &screen);
    handle_event(&event, &clock, &screen);
  }

  save("saved.rcd", &clock);

  close_screen(&screen);

  return 0;
}
