#include "_sh_inc_list"
#include "events_inc"

void main()
{
    //Let's set this area's pseudo OnExit event (as a workaround for players quitting the game)
    SetLocalString(OBJECT_SELF, "OnExit", "pseudo_qonexit");

    //A workaround to enable selecting this area in the OnClientLeave event, since GetArea returns OBJECT_INVALID there
    SetLocalObject(GetEnteringObject(), "StoredArea", OBJECT_SELF);

    //A workaround to prevent the OnEnter event body from firing after loading a saved game
    if (GetLocalInt(GetModule(), "LoadCooldown") == TRUE) return;

    //Get the area we're in from the area variable, get the PC and declare some variables
    string sAreaString = GetLocalString(OBJECT_SELF, "AreaString");
    object oPC = GetEnteringObject();
    int nEncounterType;

    //Sanity check
    if (!GetIsPC(oPC)) return;

    //Add to the counter of PCs in the area
    SetLocalInt(OBJECT_SELF, "Players", GetLocalInt(OBJECT_SELF, "Players")+1);

    //Do nothing if there is already another PC in the area (and the area integer is TRUE)
    if (GetLocalInt(OBJECT_SELF, "IsPopulated") == TRUE) return;

    //Otherwise flag this area as populated, so that no event is generated for next players entering it
    SetLocalInt(OBJECT_SELF, "IsPopulated", TRUE);

    //Now select the leader of the entering party, stored earlied - we will delete this variable in the OnExit
    oPC = GetLocalObject(OBJECT_SELF, "PartyLeader");

    //Delete this area from the list of free areas
    string sRegionString = GetStringLeft(sAreaString, 1);
    string sList = "sList"+sRegionString+"q";
    object oList = GetLocalObject(GetModule(), sList);
    int i;
    for (i = 1; i <= ListGetElementCount(oList); i++)
    {
        if (ListGetString(oList, i) == sAreaString) ListRemoveElement(oList, i);
    }

    //TEST
    for (i = 1; i <= ListGetElementCount(oList); i++)
    {
        WriteTimestampedLogEntry(GetName(oPC)+" "+ListGetString(oList, i));
        WriteTimestampedLogEntry(GetName(oPC)+" "+"entered qarea "+sAreaString);
    }

    //Here the quest NPC(s) spawn
    SpawnQuest(oPC, sAreaString);
}