#include "startCube.h"

static const int CHARS_PER_LINE = 512;

void startCube (void )
{

  FILE * input_stream;
  char * line = calloc(CHARS_PER_LINE + 1, sizeof(char));
  char * width = calloc(16, sizeof(char)); // "8" is arbitrary, just don't choose something less than 5
  char * height = calloc(16, sizeof(char));
  
  if ((input_stream = fopen("autoexec.cfg", "r")) == NULL)
  {
    fprintf(stderr, "Unable to open autoexec.cfg file\n");
    free(line);
    return ;
  }

  while (readLine(line, input_stream) == 1)
  {
    if (strncmp(line, "screen_width ", 13) == 0)
    {
      strcpy(width, line + (sizeof(char) * 13));
    }
    else if (strncmp(line, "screen_height ", 14) == 0)
    {
      strcpy(height, line + (sizeof(char) * 14));
    }
    free(line);
    line = calloc(CHARS_PER_LINE + 1, sizeof(char));
  }
  
  free(line);
  
  /* in case it was never defined in the config file... */
  if (* width == '\0') {
    fprintf(stderr, "Screen width not defined in configuration file\n");
    strcpy(width, "1024");
  }
  if (* height == '\0') {
    fprintf(stderr, "Screen height not defined in configuration file\n");
    strcpy(height, "768");
  }
  
  /* much as I hate error checking, these strings are going to be used in a system command.
     They must be checked that each character is a number and not something hateful */
  char * width_check = width;
  while (* width_check != '\0')
  {
    if ((* width > '9') || (* width < '0'))
    {
      fprintf(stderr, "Invalid width: %s\nUsing default screen resolution 1024x768\n", width);
      strcpy(width, "1024");
      strcpy(height, "768");
    }
    width_check++;
  }
  char * height_check = height;
  while (* height_check != '\0')
  {
    if ((* height > '9') || (* height < '0'))
    {
      fprintf(stderr, "Invalid height: %s\nUsing default screen resolution 1024x768\n", height);
      strcpy(width, "1024");
      strcpy(height, "768");
    }
    height_check++;
  }
  
  // the decision to use CHARS_PER_LINE here is arbitrary
  char * system_command = calloc(CHARS_PER_LINE + 1, sizeof(char));
  /* here's the crucial line where you set your main cube executable location */
  sprintf(system_command, "./linux_client -w%s -h%s", width, height);

  free(height);
  free(width);
  #ifdef DEBUG
  printf("Sending the following command to the operating system: %s\n", system_command);
  #endif
  #ifndef DEBUG
  system(system_command);
  #endif
  free(system_command);
  return ;
}
