/* Bugger the Democracy... this is Toast's Map Dictatorship. Randomly chooses a map 
   from your mapcycle.txt and sets it running. The last 20 maps are stored in a file
   preventing them from being chosen again.
 
   Inspired by Platinum's Random Map Voting Script.
 
   KNOWN ISSUES: You must have at least 20 maps in your mapcycle or it will freak!
                 This is my first attempt at a plugin... so no warranty's are provided!
 
   toast@downie.org
 */
 
 
#include <core>
#include <console>
#include <string>
#include <admin>
#include <adminlib>
 
public StartMapVote() {
 
	new LoadFile[MAX_NAME_LENGTH];
	new MapFileSize;
	new MapLine;
	new TheMap[MAX_NAME_LENGTH];
	new TheCurrentMap[MAX_NAME_LENGTH];
	new Recent=0;
	new RecentMaps[20][MAX_NAME_LENGTH];
	new RecentMapsFile[MAX_NAME_LENGTH];
 
	getstrvar("maps_file", LoadFile, MAX_NAME_LENGTH);
	if ((strlen(LoadFile)==0) || (streq(LoadFile, "0")==1)) {
		strcpy(LoadFile, "mapcycle.txt", 13);
	}
 
	MapFileSize = filesize(LoadFile,lines);
 
 
	strcpy(RecentMapsFile, "recent.txt", 11);
	for (new i = 0; i < 20 ; ++i) {
		readfile(RecentMapsFile, RecentMaps[i], i+1, MAX_TEXT_LENGTH);
	}
 
	for (new i = 0;i<19;i++) {
		RecentMaps[i]=RecentMaps[i+1];
		writefile(RecentMapsFile,RecentMaps[i],i+1);
	}
	currentmap(TheCurrentMap, MAX_TEXT_LENGTH);
	RecentMaps[19] = TheCurrentMap;
	writefile(RecentMapsFile,RecentMaps[19],20);
 
	while(Recent==0) {
		Recent=1;
		MapLine = random(MapFileSize);
		readfile(LoadFile, TheMap, MapLine, MAX_TEXT_LENGTH);
 
		for (new i = 0; i < 20; ++i) {
			if (streq(RecentMaps[i],TheMap)==1) {
				Recent=0;
				say(TheMap);
			}
		}
	} 
 
	say("    [Toast's Random Map Script v1.1]");
	changelevel(TheMap);
 
	return PLUGIN_HANDLED;
}
 
 
public CheckTime() {
	new Text[MAX_NAME_LENGTH];
	new intTime = timeleft(0);
	numtostr(intTime-30,Text);
	if(intTime<61){
		if(intTime<30){
			centersay("END OF ROUND:^nChoosing Random Map^n^n[Toast's Random Map Script v1.1]",18,249,244,0);
			if(intTime<29){
				StartMapVote();
			}
		}
		else {
			strcat(Text, " seconds left",MAX_NAME_LENGTH);
			centersay(Text,1,249,244,0);
		}
	}
	return PLUGIN_CONTINUE;
}
 
 
public plugin_init() {
	plugin_registerinfo("Toast's Random Map Plugin","Changes to a random map at the end of the round","1");
	plugin_registercmd("admin_randommap","StartMapVote",ACCESS_VOTE_MAP,"What!? are you mental?");
	new intTime = timeleft(0);
	if(intTime<0){
		StartMapVote();	
	}
	set_timer("CheckTime",1, 99999, ""); 
 
	return PLUGIN_CONTINUE;
}