#include "misc.h"
#include "defs.h"
#include "savefile.h"
#include <string.h>
#include "world.h"
#include "rules.h"
#include "player.h"
#include "display.h"
#include "trans.h"
#include "city.h"
#include "debug.h"

static FILE *f;

void CreateSaveFile()
{
  char name[128];
  strcpy(name, "save_");
  strcat(name, myName);
  f = fopen(name, "w");

  WriteUShort(playerId);
  WriteUShort(currTurn);
  WriteUShort(cityNames-initCityNames);
  trans->Save();
  world->Save();
  // each player writes his units and cities
  WriteUShort(numPlayers);
  for (int i = 0; i < numPlayers; ++i) {
    WriteString(players[i]->name);
    players[i]->Save();
  }
  fclose(f);
}

// called by CivInit()
void ReadSaveFile()
{
  char name[128];
  strcpy(name, "save_");
  strcat(name, myName);
  f = fopen(name, "r");

  InitializeRules();

  playerId = ReadUShort();
  currTurn = ReadUShort();
  cityNames = initCityNames+ReadUShort();
  trans = new TransTable;
  Debug('s', "Restoring world\n");
  world = new World; // default constructor tells to read from save file
  display = new WDisplay(world);
  world->AllocColors();
  display->AllocColors();
  AllocCityColors();
  numPlayers = ReadUShort();
  players = new PlayerP[numPlayers];
  for (int i = 0; i < numPlayers; ++i) {
    char *name = ReadString();
    Debug('s', "Restoring player %s\n", name);
    players[i] = new Player(name, i);
    players[i]->Restore();
  }
  fclose(f);
}

void WriteUChar(uchar ch)
{
  putc(ch, f);
}

void WriteUShort(ushort i)
{
  fwrite(&i, sizeof(ushort), 1, f);
}

void WriteULong(ulong l)
{
  fwrite(&l, sizeof(ulong), 1, f);
}

void WriteString(char *str)
{
  WriteUShort(strlen(str));
  fputs(str, f);
}

void WriteBytes(char *ptr, int n)
{
  fwrite(ptr, n, 1, f);
}

uchar ReadUChar()
{
  return getc(f);
}

ushort ReadUShort()
{
  ushort i;
  fread(&i, sizeof(ushort), 1, f);
  return i;
}

ulong ReadULong()
{
  ulong l;
  fread(&l, sizeof(ulong), 1, f);
  return l;
}

char *ReadString()
{
  ushort n = ReadUShort();
  char *str = new char[n+1];
  fread(str, n, 1, f);
  str[n] = 0;
  return str;
}

void ReadBytes(char *ptr, int n)
{
  fread(ptr, n, 1, f);
}
