#include "highscores.h"
#include "arch.h"

#include <fstream>
#include <iostream>
using namespace std;

static vector<highscoreentry> scores;
static bool loaded;

void load_highscores()
{
  char output[50];
  hiscoresfile(output);
  ifstream fin(output);
  bool isgood = fin.good();
  highscoreentry tempentry;
  while(isgood)
    {
      fin >> tempentry.name;
      fin >> tempentry.level;
      isgood = fin.good();
      fin >> tempentry.score;
      if (isgood)
	scores.push_back(tempentry);
      isgood = fin.good();
    }
  loaded = 1;
  fin.close();
}

void save_highscores()
{
  char output[50];
  hiscoresfile(output);
  ofstream fout(output);
  vector<highscoreentry>::iterator i;
  for (i = scores.begin(); i < scores.end(); i++)
    {
      fout << i->name << '\t' << i->level << '\t' << i->score << '\n';
    }
  fout.close();
}

void add_highscore(highscoreentry toadd)
{
  if (loaded == 0)
    load_highscores();
  vector<highscoreentry>::iterator i;
  for (i = scores.begin(); i < scores.end(); i++)
    {
      if (i->score < toadd.score)
	break;
    }
  scores.insert(i, toadd);
  if (scores.size() > 10)
    scores.pop_back();
  save_highscores();
}
vector<highscoreentry> gethighscores()
{
  if (loaded == 0)
    load_highscores();
  return scores;
}

highscoreentry gethighscore()
{
  if (loaded == 0)
    load_highscores();
  if (scores.size() > 0)
    return scores[0];
  highscoreentry output;
  output.name = "no name";
  output.level = 0;
  output.score = 0;
  return output;
}
