/*
Copyright (c) 1998 Michael Haar, Ulrich Haar, Michael Thayer,
  Tobias Mueller, Tobias Lenz
All rights reserved.
Terroid Programming by Michael Haar, Michael Thayer, Ulrich Haar
Terroid Graphics by Ulrich Haar, Michael Haar
Terroid Music by Michael Thayer
Terroid Level design by Michael Haar, Ulrich Haar, Tobias Lenz
Terroid Beta testing by Tobias Mueller, Tobias Lenz

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer in the documentation and/or other materials
   provided with the distribution.
3. Any credits displayed during programme execution must include the
   above or an equivalent credit list.
4. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.
5. The authors Michael Thayer and Michael Haar are to be informed,
   preferable by electronic mail, when this software is distributed
   commercially.  A single notification is required for any given
   distribution, and explicit copies of that distribution (e.g. for all
   resellers of a given Linux distribution).
6. If any modifications are made to the software, then a description of them
   must be included when the software is redistributed, or alternatively,
   the distributed binary or source code must be described as a product
   based on source code by Michael Haar, Michael Thayer and Ulrich Haar.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*********************************/
/* Highscoreroutinen für TERROID */
/* (C) Juli 1996 by Michael Haar */
/*********************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dn.h>
#include "DEFS.H"
#include "VARS.H"
#include "FUNCS.H"

#define HISCORE_ENTRIES 10

/* globale Variablen */
struct
{
	int punkte;
	char name[20];
} highscore_entry[HISCORE_ENTRIES];

static BOOLEAN key_pressed;
GFXBLK leuchtepix[3];

/* Funktionsprototypen */
void load_hiscore();
void hiscore();
void hiscore_eintragen();

/* Funktionen */
long hsc_checksum(BOOLEAN nur_punkte)
{
	int i, t;
	long sum;

	sum = 0;
	for(i = 0; i < HISCORE_ENTRIES; i++)
	{
		sum += highscore_entry[i].punkte;
		if(!nur_punkte)
			for(t = 0; t < strlen(highscore_entry[i].name); t++)
				sum += highscore_entry[i].name[t];
	}

	return(sum);
}

void encode_hiscore()
{
	int i, t;
	char buffer[2];

	for(i = 0; i < HISCORE_ENTRIES; i++)
	{
		// Vertauscher zur Sicherheit
		buffer[0] = highscore_entry[i].name[19];
		buffer[1] = highscore_entry[i].name[0];
		highscore_entry[i].name[0] = (unsigned char)((highscore_entry[i].punkte & 0xFF00) >> 8);
		highscore_entry[i].name[19] = (unsigned char)(highscore_entry[i].punkte & 0xFF);
		highscore_entry[i].punkte &= 0xFFFF0000;
		highscore_entry[i].punkte += ((int)buffer[0] << 8);
		highscore_entry[i].punkte += (int)buffer[1];

		// Alles invertieren
		highscore_entry[i].punkte = ~highscore_entry[i].punkte;
		for(t = 0; t < 20; t++)
			highscore_entry[i].name[t] = ~highscore_entry[i].name[t];
	}
}

void decode_hiscore()
{
	int i, t;
	char buffer[2];

	for(i = 0; i < HISCORE_ENTRIES; i++)
	{
		// Invertieren
		highscore_entry[i].punkte = ~highscore_entry[i].punkte;
		for(t = 0; t < 20; t++)
			highscore_entry[i].name[t] = ~highscore_entry[i].name[t];

		// Vertauscher
		buffer[0] = (char)((highscore_entry[i].punkte & 0xFF00) >> 8);
		buffer[1] = (char)(highscore_entry[i].punkte & 0xFF);
		highscore_entry[i].punkte &= 0xFFFF0000;
		highscore_entry[i].punkte +=
		  (((int) (unsigned char) highscore_entry[i].name[0]) << 8) ;
		highscore_entry[i].punkte +=
		  (int) (unsigned char) highscore_entry[i].name[19];
		highscore_entry[i].name[0] = buffer[1];
		highscore_entry[i].name[19] = buffer[0];		
	}
}

void reset_hiscore()
{
	int i;

	for(i = 0; i < HISCORE_ENTRIES; i++)
	{
		highscore_entry[i].punkte = 100000 - i * 7500;
		if(i == 0)
			strcpy(highscore_entry[i].name, "MICHAEL HAAR");
		else if(i == 1)
			strcpy(highscore_entry[i].name, "ULRICH HAAR");
		else if(i == 2)
			strcpy(highscore_entry[i].name, "MICHAEL THAYER");
		else if(i == 3)
			strcpy(highscore_entry[i].name, "------------------");
		else if(i == 4)
			strcpy(highscore_entry[i].name, "      TERROID     ");
		else if(i == 5)
			strcpy(highscore_entry[i].name, "     THE GAME     ");
		else if(i == 6)
			strcpy(highscore_entry[i].name, "DIGITAL NIGHTMARES");
		else if(i == 7)
			strcpy(highscore_entry[i].name, "     - 1996 -     ");
		else if(i == 8)
			strcpy(highscore_entry[i].name, "------------------");
		else if(i == 9)
			strcpy(highscore_entry[i].name, "!NOT GOOD ENOUGH!");
	}
}

void save_hiscore()
{
	FILE *datei;
	char * storeenv ;
	char txt[1024];
	long chksum;

	storeenv = getenv("HOME") ;
	if (storeenv) /* should work under DOS, Windoze and UN*X */
	  {
	    strcpy(txt, storeenv) ;
	    strcat(txt, "/.terroid") ;
	  }
	else
	  {
	    strcpy(txt, gamepath);
	    strcat(txt, "HISCORE.DAT");
	  }

	datei = fopen(txt, "wb");
	if(datei)
	{
		// Check ohne Kodierung
		chksum = hsc_checksum(FALSE);
		fwrite(&chksum, sizeof(long), 1, datei);
		encode_hiscore();
		fwrite(&chksum, sizeof(long), 1, datei);
		fwrite(&highscore_entry[0], sizeof(highscore_entry[0]), HISCORE_ENTRIES / 2, datei);
		// Check mit Kodierung
		chksum = hsc_checksum(TRUE);
		fwrite(&chksum, sizeof(long), 1, datei);
		fwrite(&highscore_entry[HISCORE_ENTRIES / 2], sizeof(highscore_entry[0]), HISCORE_ENTRIES / 2, datei);
		fwrite(&chksum, sizeof(long), 1, datei);
		fclose(datei);

		decode_hiscore();
	}
}

void load_hiscore()
{
	FILE *datei;
	char * storeenv ;
	char txt[1024];
	long chksum, pruef_chksum;

	storeenv = getenv("HOME") ;
	if (storeenv) /* should work under DOS, Windoze and UN*X */
	  {
	    strcpy(txt, storeenv) ;
	    strcat(txt, "/.terroid") ;
	  }
	else
	  {
	    strcpy(txt, gamepath);
	    strcat(txt, "HISCORE.DAT");
	  }
	datei = fopen(txt, "rb");
	if(datei == NULL)
	{
		reset_hiscore();
		save_hiscore();
	}
	else
	{
		fread(&pruef_chksum, sizeof(long), 1, datei);
		fread(&chksum, sizeof(long), 1, datei);
		fread(&highscore_entry[0], sizeof(highscore_entry[0]), HISCORE_ENTRIES / 2, datei);
		fread(&chksum, sizeof(long), 1, datei);
		fread(&highscore_entry[HISCORE_ENTRIES / 2], sizeof(highscore_entry[0]), HISCORE_ENTRIES / 2, datei);
		fread(&chksum, sizeof(long), 1, datei);
		fclose(datei);

		// Check mit Kodierung
		if(chksum != hsc_checksum(TRUE))
		{
			puts("\7");
			reset_hiscore();
			save_hiscore();
		}
		decode_hiscore();
		// Check ohne Kodierung
		if(pruef_chksum != hsc_checksum(FALSE))
		{
			puts("\7");
			reset_hiscore();
			save_hiscore();
		}
	}
}

void hiscore()
{
//	void *old_screen = screen_addr;
	int i;
	long t;

	if(!no_music)
	{
		stop_sound();
		// Music on
		md_numchn = 4;
		if((mymod = ML_LoadFN("TERROID.XM")))
			md_numchn += mymod->numchn;
		start_mod(TRUE, 0, 5);
	}

	load_hiscore();

	cls(0);
	Copy2Screen();
	ClearPalette(alt_rgb);
	SetPalette(alt_rgb);

	load_pic("BILDSCH2.PIX", screen_addr, alt_rgb);
	get(9, 58, 23, 70, &leuchtepix[1]);
	load_pic("BILDSCHI.PIX", screen_addr, alt_rgb);
	get(0, 0, screen_width, screen_height, & leuchtepix[2]) ;
	put(0, 0, & leuchtepix[2]) ;
	get(9, 58, 23, 70, &leuchtepix[0]);
	Copy2Screen();
	PaletteFadeIn(alt_rgb);

	if(strcmp(cheatmode, "IAMGOD") && strcmp(cheatmode, "HELPME"))
		hiscore_eintragen();

	load_pic("BILDSCHI.PIX", screen_addr, alt_rgb);
	Copy2Screen();

	ticker_text(&gamefont, 40, 40, "THE TOP TEN PLAYERS:", FALSE);
	for(i = 0; i < HISCORE_ENTRIES; i++)
	{
		// Punkte
		sprintf(txt, "%6d", highscore_entry[i].punkte);
		ticker_text(&gamefont, 37, 60 + i * 10, txt, FALSE);
		// Name
		sprintf(txt, "%18s", highscore_entry[i].name);
		ticker_text(&gamefont, 47 + schrift.char_w * 7, 60 + i * 10, txt, FALSE);
	}
	while(keyTest(KEY_ENTER) || keyTest(KEY_SPACE) || keyTest(KEY_ESC) || keyTest(KEY_RCTRL) || keyTest(KEY_LCTRL) || joy1_b1())
		;

//	screen_addr = (void *)0xA0000;
	i = 0;
	t = timer();
	while(!keyTest(KEY_ENTER) && !keyTest(KEY_SPACE) && !keyTest(KEY_ESC) && !keyTest(KEY_RCTRL) && !keyTest(KEY_LCTRL) && (timer() - t < 1000) && !joy1_b1())
	{
		i++;
		wait_retrace();
		put(9, 58, &leuchtepix[(i % 32) / 16]);
		Copy2Screen() ;
	}
	if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
	while(keyTest(KEY_ENTER) || keyTest(KEY_SPACE) || keyTest(KEY_ESC) || keyTest(KEY_RCTRL) || keyTest(KEY_LCTRL) || joy1_b1())
		;

//	screen_addr = old_screen;

	free_blk(& leuchtepix[0]);
	free_blk(& leuchtepix[1]);
	free_blk(& leuchtepix[2]) ;
//	leuchtepix[0].mem = NULL;
//	leuchtepix[1].mem = NULL;

	PaletteFadeOut(alt_rgb);
	cls(0);
	Copy2Screen();
}

void get_string(char * str)
{
	if(keyTest(KEY_A))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "A");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_B))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "B");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_C))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "C");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_D))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "D");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_E))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "E");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_F))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "F");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_G))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "G");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_H))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "H");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_I))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "I");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_J))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "J");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_K))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "K");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_L))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "L");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_M))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "M");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_N))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "N");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_O))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "O");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_P))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "P");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_Q))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "Q");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_R))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "R");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_S))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "S");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_T))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "T");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_U))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "U");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_V))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "V");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_W))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "W");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_X))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "X");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_Y))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "Y");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_Z))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, "Z");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_SPACE))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			strcat(str, " ");
		}
		key_pressed = TRUE;
	}
	else if(keyTest(KEY_BACKSPACE))
	{
		if(!key_pressed)
		{
			if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
			if(strlen(str) > 0)
				str[strlen(str) - 1] = 0;
		}
		key_pressed = TRUE;
	}
	else
		key_pressed = FALSE;
}

void hiscore_namenseingabe(char *name)
{
	int i;
	void *bildschirmpix;

	bildschirmpix = malloc(screen_width * screen_height);
	load_pic("BILDSCHI.PIX", bildschirmpix, alt_rgb);

	ticker_text(&gamefont, 40, 40, "CONGRATULATIONS,  YOU", FALSE);
	ticker_text(&gamefont, 40, 50, "REACHED THE TOP RANKS", FALSE);
	ticker_text(&gamefont, 40, 70, "ENTER YOUR NAME:", FALSE);

	key_pressed = FALSE;
	strcpy(name, "");
	i = 0;
	while(!keyTest(KEY_ENTER) && !keyTest(KEY_ESC))
	{
		putvollbild(bildschirmpix);
		put_text(&gamefont, 40, 40, "CONGRATULATIONS,  YOU");
		put_text(&gamefont, 40, 50, "REACHED THE TOP RANKS");
		put_text(&gamefont, 40, 70, "ENTER YOUR NAME:");
		key_pressed = FALSE ;
		get_string(name);
		put_text(&gamefont, 40, 80, name);
		i++;
		put(9, 58, &leuchtepix[(i % 32) / 16]);
		wait_retrace();
		Copy2Screen();
	}
	if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
	while(keyTest(KEY_ENTER) || keyTest(KEY_ESC))
		;

	free(bildschirmpix);
}

void hiscore_eintragen()
{
	int i;
	int pos;

	for(i = 0; i < HISCORE_ENTRIES; i++)
		if(highscore_entry[i].punkte < spieler.punkte)
			break;

	if(i < HISCORE_ENTRIES)
	{
		pos = i;
		// verschieben
		for(i = HISCORE_ENTRIES - 1; i > pos; i--)
			highscore_entry[i] = highscore_entry[i - 1];

		highscore_entry[pos].punkte = spieler.punkte;
		hiscore_namenseingabe(highscore_entry[pos].name);

		save_hiscore();
	}
}
