/*  Core Wars.
 *  Copyright (C) 1999  Walter Hofmann
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as 
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

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

#include "options.h"

#define PREFERENCES_HEADER "This is the Corewars preferences file. Please don't edit it.\n"
#define PREFERENCES_VERSION 0
#define PREFERENCES_COUNT 17

int *const pref_ptr[PREFERENCES_COUNT] = { NULL, &LANGUAGE, &SIZE, &MAX_THREADS, &MAX_CYCLES, &MAX_LENGTH,
					   &MIN_DISTANCE, &STOP_EARLY, &ALLOW_SELF_MOVE, &EXECUTE_DELAY, 
					   &EXECUTE_UPDATE, &STATISTIC_DELAY, &SCORE_ALIVE, &SCORE_CELLS, 
					   &SCORE_KILLS, &SCORE_RANK, &SCORE_BEST };
const int pref_min[PREFERENCES_COUNT] = { 0, 1, SIZE_MIN, 1, 1, 1, 0, 0, 0, EXECUTE_DELAY_MIN, 1, 
					  STATISTIC_DELAY_MIN, 0, 0, 0, 0, 0 };
const int pref_max[PREFERENCES_COUNT] = { 9, 2, SIZE_MAX, 0, 0, 0, 0, 1, 1, 0, 0, 
					  0, 0, 0, 0, 1, 1 };

void preferences_load ()
{
  char filename[1024];
  FILE *f;
  char s[1024];
  int i, j;
  char *p;

  snprintf (filename, 1024, "%s/.corewars", getenv("HOME"));
  filename[1023] = '\0';
  f = fopen (filename, "r");
  if (f==NULL)
    return;
  if (!fgets (s, 1024, f))
    return;
  if (strcmp (s,PREFERENCES_HEADER)!=0)
    return;
  for (i=0; i<PREFERENCES_COUNT; i++)
    {
      if (!fgets (s, 1024, f))
	return;
      j = strtol (s, &p, 0);
      if (s[0]=='\n' || *p!='\n')
	return;
      if (j<pref_min[i])
	return;
      if (pref_max[i]>0 && j>pref_max[i])
	return;
      if (pref_ptr[i])
	(*pref_ptr[i]) = j;
    }
  fgets (s, 1024, f);
  if (s[0]=='\0')
    return;
  s[strlen (s)-1] = '\0';
  strcpy (EDIT_COMMAND, s);
  fclose (f);
}

void preferences_save ()
{
  char filename[1024];
  FILE *f;
  int i;

  snprintf (filename, 1024, "%s/.corewars", getenv("HOME"));
  filename[1023] = '\0';
  f = fopen (filename, "w");
  if (f==NULL)
    return;
  fprintf (f, "%s", PREFERENCES_HEADER);
  fprintf (f, "%d\n", PREFERENCES_VERSION);
  for (i=1; i<PREFERENCES_COUNT; i++)
    fprintf (f, "%d\n", *pref_ptr[i]);
  fprintf (f, "%s\n", EDIT_COMMAND);
  fclose (f);
}
