#define TIMECTRL_NONE 0
#define TIMECTRL_TIMEPERPLAYER 1
#define TIMECTRL_TIMEPERMOVE 2

void save_move_start_time(void)
{
  game_status->move_start_time = time(0);
  if(setup.timecontrol == TIMECTRL_TIMEPERMOVE)
  {
    if(game_status->turn)
      game_status->black_time = setup.timelimit;
    else
      game_status->white_time = setup.timelimit;
  }
}

signed long get_move_time(void)
{
  return time(0) - game_status->move_start_time;
}

signed long get_move_time_rt(unsigned char player)
{
  signed long t = player ? game_status->black_time : game_status->white_time;

  if(player == game_status->turn && game_status->move_start_time)
  {
    if(setup.timecontrol == TIMECTRL_NONE)
      return t + get_move_time();
    else
      return t - get_move_time();
  }
  else
    return t;
}

int playeroutoftime(void)
{
  unsigned long *t;

  if(setup.timecontrol == TIMECTRL_NONE)
    return 0;

  if(get_move_time_rt(game_status->turn) <= 0)
    return 1;
  return 0;
}


void set_player_time(void)
{
  unsigned long *time;
  if(game_status->turn)
    time = &game_status->black_time;
  else
    time = &game_status->white_time;

  if(setup.timecontrol == TIMECTRL_NONE)
    *time += get_move_time();
  else
  {
    *time -= get_move_time();
    if((signed long)*time <= 0) *time = 0;
  }

  game_status->move_start_time = 0;
}

void draw_timectrl(void)
{
  draw_rectangle(220, 36, 80, 10, 0x00);
  draw_rectangle(220, 76, 80, 10, 0x00);
}

char *secondstotimestr(signed long s)
{
  unsigned hour;
  unsigned char min;
  unsigned char sec;
  static char ret[16];

  if(s < 0) s = 0;

  hour = s / 3600;
  min = s % 3600 / 60;
  sec = s % 3600 % 60;

  sprintf(ret, "%u:%.2u:%.2u", hour, min, sec);

  return ret;
}

char *get_timestr(unsigned char player)
{
  return secondstotimestr(get_move_time_rt(player));
}

void print_timectrl(unsigned char update)
{
  draw_timectrl();
  print_text(230, 37, 0xAA, get_timestr(1));
  print_text(230, 77, 0xAA, get_timestr(0));
  if(update)
    update_screen();
}
