#include "globals.h"
#include "score.h"
#include "menu.h"
#include "object.h"
#include "ship.h"


HighScore HighScores[NUM_HIGHSCORES];
char HighScoreName[MAX_PLAYERNAME_LENGTH];
int Score;
char ScoreFileName[MAX_FILENAME_SIZE];


void InitHighScores();
int CheckForHighScore();
void AddHighScore(char *name);
void ReadHighScores();
void SaveHighScores();


void ClearHighScores()
{
  InitHighScores();
  SaveHighScores();
  ScoreMenu();
}


void InitHighScores()
{
  int i;

  for (i=0; i<NUM_HIGHSCORES; i++) {
    HighScores[i].Score=0;
    HighScores[i].Name[0]=0;
  }
}


int CheckForHighScore()
{
  int i;

  for (i=0; i<NUM_HIGHSCORES; i++) {
    if (Ships[myShip]->Score > HighScores[i].Score) {
      return(1);
    }
  }
  return(0);
}


void AddHighScore(char *name)
{
  int i, j;

  for (i=0; i<NUM_HIGHSCORES; i++) {
    if (Ships[myShip]->Score > HighScores[i].Score) {
      for (j=NUM_HIGHSCORES-1; j>i; j--) {
        HighScores[j].Score=HighScores[j-1].Score;
        strcpy(HighScores[j].Name, HighScores[j-1].Name);
      }
      HighScores[i].Score=Ships[myShip]->Score;
      strcpy(HighScores[i].Name, name);
      break;
    }
  }
  SaveHighScores();
}


void ReadHighScores()
{
  int i;
  char score[10];
  char name[MAX_PLAYERNAME_LENGTH];
  char *c;
  FILE *HighScoreFile;

  if (!(HighScoreFile=fopen(ScoreFileName, "r"))) {
    return;
  }

  for (i=0; i<NUM_HIGHSCORES; i++) {
    c=score;
    while((*c=fgetc(HighScoreFile))!=' ') {
      if (*c==EOF) {
	fclose(HighScoreFile);
	return;
      }
      c++;
    }
    *c=0;

    c=name;
    while((*c=fgetc(HighScoreFile))!='\n') {
      if (*c==EOF) {
	fclose(HighScoreFile);
	return;
      }
      c++;
    }
    *c=0;
    HighScores[i].Score=atoi(score);
    strcpy(HighScores[i].Name, name);
  }
  fclose(HighScoreFile);
}


void SaveHighScores()
{
  int i;
  FILE *HighScoreFile;

  HighScoreFile=fopen(ScoreFileName, "w");

  for (i=0; i<NUM_HIGHSCORES; i++) {
    fprintf(HighScoreFile, "%d %s\n", HighScores[i].Score, HighScores[i].Name);
  }
  fclose(HighScoreFile);
}
