// Copyright 1994 Brad Pitzel
//
// Feel free to use/distribute/modify as long as credit/copyrights for myself 
// are included.

#include "HiScore.h"
#include <fstream.h>

// create hi score list, read in from save file if it exists
// Note: no error checking on format of save file!
HiScore::HiScore( const char *file )
	{
	Vfile = SCOREDIR;
	Vfile += file;

	// init list
	int i;
	for (i=0; i<HiScoreListSize; i++)
		{
		Vscore[i] = 0;
		Vname[i] = "";
		}
	
	// if file exists, load high scores/names into memory
	ifstream ifstr(Vfile);
	
	if (ifstr.is_open())
		{
		i=0;
		
		while( (i<HiScoreListSize) && (!ifstr.eof()) )
			{
			ifstr >> Vname[i] >> Vscore[i];
			i++;
			}
			
		ifstr.close();
		}
	}


// save hi score list on destruction
HiScore::~HiScore()
	{
	save();
	}
	

// return pos 0..(ListSize-1) if score is good enough, -1 otherwise
char HiScore::isHigh( Score s ) const
	{
	char result=-1;
	int i=0;
	
	while( (i<HiScoreListSize) && (result==-1) )
		{
		if (Vscore[i]<s) result=i;
		else i++;
		}
		
	return result;
	}

char HiScore::add( const char *name, Score s )
	{
	char result = 0;
	char pos = isHigh( s );
	int  i;
	
	if (pos >= 0 )
		{
		// move everyone below down 1 position in list
		for(i=(HiScoreListSize-1); i>pos; i--)
			{
			Vscore[i] = Vscore[i-1];
			Vname[i]  = Vname[i-1];
			}
		
		Vscore[pos] = s;
		Vname[pos] = name;
		result = 1;
		}
	return result;
	}


// save high score list to file
char HiScore::save() const
	{
	char result = 0;

	ofstream ofstr(Vfile);
	
	if (ofstr.is_open())
		{
		int i=0;
		
		while( (i<HiScoreListSize) && (Vname[i].Length()>0) )
			{
			ofstr << Vname[i] << " " << Vscore[i] << " ";
			i++;
			}

		ofstr.close();
		}
	else
		{
		cerr << "HiScore: cannot open score file for writing" << endl;
		}

	return result;
	}
