// vim: ts=2 sw=2 et
#include <stdio.h>

// returns
// ' ' when game is in progress
// 'X' when X wins
// 'O' when O wins
// '?' when game is finished but no one wins
char get_winner(char board[9]) {
  for (int i = 0; i < 3; i++) {
    // Line
    if (board[3 * i] != ' ' && board[3 * i] == board[3 * i + 1] &&
        board[3 * i] == board[3 * i + 2]) {
      return board[3 * i];
    }
    // Column
    if (board[i] != ' ' && board[i] == board[i + 3] &&
        board[i] == board[i + 6]) {
      return board[i];
    }
  }
  // Diag 1
  if (board[0] != ' ' && board[0] == board[4] && board[0] == board[8]) {
    return board[0];
  }
  // Diag 2
  if (board[2] != ' ' && board[2] == board[4] && board[2] == board[6]) {
    return board[2];
  }
  for (int i = 0; i < 9; i++) {
    if (board[i] == ' ') {
      return ' ';
    }
  }
  return '?';
}

void print_board(int file_descriptor, char board[9]) {
  dprintf(file_descriptor,
          "\n"
          " %c | %c | %c \n"
          "---+---+---\n"
          " %c | %c | %c \n"
          "---+---+---\n"
          " %c | %c | %c \n"
          "\n",
          board[6], board[7], board[8], board[3], board[4], board[5], board[0],
          board[1], board[2]);
}