function eqbuffhelper_applyorstrip()
{
    $id = get_module_pref("weaponid", "mysticalshop");
    if ($id) {
        if ($id == 80) {
            apply_buff('ccfail', array("roundmsg" => "`\$Your Chainsaw-Chuks have a depressingly predictable effect - complete unpredictability.", "name" => "`\$Chainsaw-Chuk Fail", "rounds" => -1, "minioncount" => 6, "maxgoodguydamage" => 20, "mingoodguydamage" => 0, "effectmsg" => "`\$One of your chainsaws bungees back at you and rips into you for `^{damage} `\$damage!", "schema" => "module-eqbuffhelper"));
        }
        if ($id == 86 || $id == 87) {
            apply_buff('sklfail', array("roundmsg" => "`\$Your SpiderKitty Launcher recoils like a box of a dozen shotguns, spraying wriggling SpiderKitties in every direction.  Including straight back.", "name" => "`\$SpiderKitty Launcher Fail", "rounds" => -1, "minioncount" => 10, "maxgoodguydamage" => 20, "mingoodguydamage" => 0, "effectmsg" => "`\$One of your SpiderKitties attaches itself to your face and scratches you for `^{damage} `\$damage!", "effectfailmsg" => "`\$One of your SpiderKitties attaches itself to your face and scratches you for `^{damage} `\$damage!", "schema" => "module-eqbuffhelper"));
        }
    }
    if ($id != 80 && $id != 86 && $id != 87 || !$id) {
        strip_buff("sklfail");
        strip_buff("ccfail");
    }
    return $args;
}
function apply_clan_buff_for_one()
{
    global $session;
    strip_buff("clanbuff");
    strip_buff("clanbuff2");
    strip_buff("clanbuff3");
    if (get_module_setting("allowatk") && get_module_objpref("clans", $session['user']['clanid'], "atkactive")) {
        $atkmod = 1 + get_module_setting("eatkbase") + get_module_objpref("clans", $session['user']['clanid'], "atklevel") * get_module_setting("eatkinc");
    } else {
        $atkmod = 1;
    }
    if (get_module_setting("allowdef") && get_module_objpref("clans", $session['user']['clanid'], "defactive")) {
        $defmod = 1 + get_module_setting("edefbase") + get_module_objpref("clans", $session['user']['clanid'], "deflevel") * get_module_setting("edefinc");
    } else {
        $defmod = 1;
    }
    if (get_module_setting("allowdrain") && get_module_objpref("clans", $session['user']['clanid'], "drainactive")) {
        $lifetap = get_module_setting("edrainbase") + get_module_objpref("clans", $session['user']['clanid'], "drainlevel") * get_module_setting("edraininc");
    } else {
        $lifetap = 0;
    }
    $allowinpvp = get_module_setting("allowinpvp");
    $allowintrain = get_module_setting("allowintrain");
    if (get_module_setting("allowult") && get_module_objpref("clans", $session['user']['clanid'], "ultactive")) {
        $rounds = -1;
    } else {
        $rounds = get_module_setting("eroundbase") + get_module_objpref("clans", $session['user']['clanid'], "roundlevel") * get_module_setting("eroundinc");
    }
    if (get_module_setting("allowthorn") && get_module_objpref("clans", $session['user']['clanid'], "thornactive")) {
        $damageshield = get_module_setting("ethornbase") + get_module_objpref("clans", $session['user']['clanid'], "thornlevel") * get_module_setting("ethorninc");
    } else {
        $damageshield = 0;
    }
    if (get_module_setting("allowregen") && get_module_objpref("clans", $session['user']['clanid'], "regenactive")) {
        $regen = get_module_setting("eregenbase") + get_module_objpref("clans", $session['user']['clanid'], "regenlevel") * get_module_setting("eregeninc");
    } else {
        $regen = 0;
    }
    apply_buff("clanbuff", array("name" => "`^Clan Aura`0", "atkmod" => $atkmod, "defmod" => $defmod, "lifetap" => $lifetap, "effectmsg" => sprintf_translate("`6Your Clan Aura allows you to absorb `^{damage}`6 of the damage you dealt to {badguy}!"), "allowinpvp" => $allowinpvp, "allowintrain" => $allowintrain, "rounds" => $rounds, "roundmsg" => "Your Clan's Aura strengthens you!", "schema" => "module-clanbuffs"));
    apply_buff("clanbuff2", array("damageshield" => $damageshield, "effectmsg" => sprintf_translate("`6Your Clan Aura allows you to reflect `^{damage}`6 of the damage you received {badguy}!"), "allowinpvp" => $allowinpvp, "allowintrain" => $allowintrain, "rounds" => $rounds, "schema" => "module-clanbuffs"));
    apply_buff("clanbuff3", array("regen" => $regen . "*<level>", "effectmsg" => sprintf_translate("`6Your Clan Aura allows you to regenerate `^{damage}`6 damage!"), "allowinpvp" => $allowinpvp, "allowintrain" => $allowintrain, "rounds" => $rounds, "schema" => "module-clanbuffs"));
}
function implantservoarms_dohook($hookname, $args)
{
    global $session, $resline;
    $spec = "SR";
    $name = "Servo Arms";
    $ccode = "`&";
    switch ($hookname) {
        case "dragonkill":
            set_module_pref("battery", 0);
            set_module_pref("status", 0);
            break;
        case "choose-specialty":
            if ($session['user']['dragonkills'] < 2) {
                break;
            }
            if ($session['user']['specialty'] == "" || $session['user']['specialty'] == '0') {
                addnav("{$ccode}{$name}`0", "newday.php?setspecialty={$spec}{$resline}");
                output("`5\"The `&Servo Arms`5 implant doesn't go in your brain, but in your spinal column instead.  As you can see, you get two lovely shiny metal arms, to supplement your existing ones.  You can set them to offensive or defensive stances, and can change their settings even in the middle of a fight if you like.  They're battery powered, so they have a finite life, but your master at the Dojo will give you a new battery in exchange for defeating him.\"`n`n");
            }
            set_module_pref("battery", 100);
            set_module_pref("status", 0);
            break;
        case "set-specialty":
            if ($session['user']['specialty'] == $spec) {
                page_header($name);
                output("`&Wow, you've really done it this time.  Other contestants opted for the tiny little chips in their brains but not you, oh no.  You had to go for the enormous servo arms jutting out of your back, didn't you?  Well, don't blame me when you get propositioned by people with rather curious fetishes.`n`nYou can activate or deactivate your Servo Arms, or change their stance, at any time.  But remember, your battery has to last you for a whole level, so don't overdo it.");
            }
            break;
        case "specialtycolor":
            $args[$spec] = $ccode;
            break;
        case "specialtynames":
            $args[$spec] = translate_inline($name);
            break;
        case "specialtymodules":
            $args[$spec] = "implantservoarms";
            break;
        case "incrementspecialty":
            if ($session['user']['specialty'] == $spec) {
                set_module_pref("battery", 100 + $session['user']['level'] * 5);
                output("`&`nYour defeated master hands you a new battery for your Servo Arms!`n");
            }
            break;
        case "fightnav-specialties":
            if ($session['user']['specialty'] == $spec) {
                // Evaluate the number of rounds that the battle has lasted thus far.  Because this is only called once per click, and the user can choose to play five rounds, ten rounds or to the end of the fight, we've got to get the number of rounds by looking at the remaining rounds left in the buff we set up the last time the user clicked to fight.
                if (has_buff("servoarms")) {
                    $roundsplayed = 1000 - $session['bufflist']['battery']['rounds'];
                    set_module_pref("battery", get_module_pref("battery") - $roundsplayed);
                    if (get_module_pref("battery") < 0) {
                        set_module_pref("battery", 0);
                        set_module_pref("status", 0);
                        strip_buff('servoarms');
                    }
                } else {
                    $roundsplayed = 0;
                }
                apply_buff('battery', array("rounds" => 1000, "dmgmod" => 1));
                $script = $args['script'];
                $battery = get_module_pref("battery");
                $status = get_module_pref("status");
                addnav(array("{$ccode} `bServo Arms`b", ""));
                addnav(array("{$ccode} Battery: %s", $battery), "");
                if ($status == 0 && $battery > 0) {
                    addnav("{$ccode} Stance: Off", "");
                    addnav(array("{$ccode} Set to Offensive stance`0"), $script . "op=fight&skill={$spec}&l=1", true);
                    addnav(array("{$ccode} Set to Defensive stance`0"), $script . "op=fight&skill={$spec}&l=2", true);
                }
                if ($status == 1 && $battery > 0) {
                    addnav("{$ccode} Stance: Offensive", "");
                    addnav(array("{$ccode} Set to Defensive stance`0"), $script . "op=fight&skill={$spec}&l=2", true);
                    addnav(array("{$ccode} Turn Servos Off`0"), $script . "op=fight&skill={$spec}&l=0", true);
                }
                if ($status == 2 && $battery > 0) {
                    addnav("{$ccode} Stance: Defensive", "");
                    addnav(array("{$ccode} Set to Offensive stance`0"), $script . "op=fight&skill={$spec}&l=1", true);
                    addnav(array("{$ccode} Turn Servos Off`0"), $script . "op=fight&skill={$spec}&l=0", true);
                }
            }
            break;
        case "apply-specialties":
            if ($session['user']['specialty'] == $spec) {
                $skill = httpget('skill');
                $l = httpget('l');
                if ($skill == $spec) {
                    switch ($l) {
                        case "1":
                            if (get_module_pref("battery") > 0) {
                                apply_buff('servoarms', array("startmsg" => "`&Your Servo Arms swing around in front of you, ready to attack {badguy}!", "name" => "`&Servo Arms", "atkmod" => "1.25", "rounds" => -1, "schema" => "module-implantlaser"));
                                set_module_pref("status", 1);
                            } else {
                                output("`&Your Servo Arms batteries are DEAD!");
                            }
                            break;
                        case "2":
                            if (get_module_pref("battery") > 0) {
                                apply_buff('servoarms', array("startmsg" => "`&Your Servo Arms swing around in front of you, ready to defend against {badguy}!", "name" => "`&Servo Arms", "defmod" => "1.25", "rounds" => -1, "schema" => "module-implantlaser"));
                                set_module_pref("status", 2);
                            } else {
                                output("`&Your Servo Arms batteries are DEAD!");
                            }
                            break;
                        case "0":
                            set_module_pref("status", 0);
                            strip_buff('servoarms');
                            break;
                    }
                }
            }
            break;
        case "battle-defeat":
        case "battle-victory":
            if ($session['user']['specialty'] == $spec) {
                if (has_buff("servoarms")) {
                    $roundsplayed = 1000 - $session['bufflist']['battery']['rounds'];
                    set_module_pref("battery", get_module_pref("battery") - $roundsplayed);
                    if (get_module_pref("battery") < 0) {
                        set_module_pref("battery", 0);
                    }
                    set_module_pref("status", 0);
                    strip_buff('servoarms');
                    output("`&Your Servo Arms neatly turn themselves back behind your back, to save on battery power.`n");
                }
            }
            break;
        case "newday":
        case "village":
            set_module_pref("status", 0);
            strip_buff('servoarms');
            break;
    }
    return $args;
}
function strip_all_buffs()
{
    global $session;
    $thebuffs = $session['bufflist'];
    reset($thebuffs);
    while (list($buffname, $buff) = each($thebuffs)) {
        strip_buff($buffname);
    }
}
function improbablestuff_dohook($hookname, $args)
{
    global $session;
    $smallmedkit = get_module_pref("item1number");
    $largemedkit = get_module_pref("item2number");
    $energydrink = get_module_pref("item3number");
    $nicotinegum = get_module_pref("item4number");
    $potentpill = get_module_pref("item5number");
    $teleporter = get_module_pref("item6number");
    $banggrenade = get_module_pref("item7number");
    $whoomphgrenade = get_module_pref("item8number");
    $zapgrenade = get_module_pref("item9number");
    $repellantspray = get_module_pref("item10number");
    $rationpack = get_module_pref("item11number");
    $improbabilitybomb = get_module_pref("item12number");
    $kittencard = get_module_pref("item13number");
    $traveladd = get_module_pref("traveladd");
    $spec = "improbablestuff";
    switch ($hookname) {
        case "forest":
            if ($smallmedkit >= 1 || $largemedkit >= 1 || $energydrink >= 1 || $nicotinegum >= 1 || $potentpill >= 1 || $repellantspray >= 1 || $rationpack >= 1) {
                addnav("`0`bUse Equipment`b`0");
            }
            if ($smallmedkit > 0) {
                addnav(array("Use Small Medkit (%s remaining)", $smallmedkit), "runmodule.php?module=improbablestuff&use=smallmedkit&from=forest");
            }
            if ($largemedkit > 0) {
                addnav(array("Use Large Medkit (%s remaining)", $largemedkit), "runmodule.php?module=improbablestuff&use=largemedkit&from=forest");
            }
            if ($energydrink > 0) {
                addnav(array("Use Energy Drink (%s remaining)", $energydrink), "runmodule.php?module=improbablestuff&use=energydrink&from=forest");
            }
            if ($nicotinegum > 0) {
                addnav(array("Use Nicotine Gum (%s remaining)", $nicotinegum), "runmodule.php?module=improbablestuff&use=nicotinegum&from=forest");
            }
            if ($potentpill > 0) {
                addnav(array("Use Power Pill (%s remaining)", $potentpill), "runmodule.php?module=improbablestuff&use=potentpill&from=forest");
            }
            if ($teleporter > 0) {
                addnav(array("Use One-Shot Teleporter (%s remaining)", $teleporter), "runmodule.php?module=improbablestuff&use=teleporter", true);
            }
            if ($session['user']['race'] != "Robot" && $session['user']['race'] != "Gobot" && $session['user']['race'] != "Foebot" && $session['user']['race'] != "Joker" && $session['user']['race'] != "Stranger" && $rationpack > 0 && get_module_pref("fullness", "staminafood") < 100) {
                addnav(array("Use Ration Pack (%s remaining)", $rationpack), "runmodule.php?module=improbablestuff&use=rationpack&from=forest", true);
            }
            if ($repellantspray > 0) {
                addnav(array("Use Monster Repellant Spray (%s remaining)", $repellantspray), "runmodule.php?module=improbablestuff&use=repellantspray&from=forest");
            }
            break;
        case "village":
            if ($smallmedkit >= 1 || $largemedkit >= 1 || $energydrink >= 1 || $nicotinegum >= 1 || $potentpill >= 1 || $repellantspray >= 1 || $rationpack >= 1) {
                addnav("`0`bUse Equipment`b`0");
            }
            if ($smallmedkit > 0) {
                addnav(array("Use Small Medkit (%s remaining)", $smallmedkit), "runmodule.php?module=improbablestuff&use=smallmedkit&from=village");
            }
            if ($largemedkit > 0) {
                addnav(array("Use Large Medkit (%s remaining)", $largemedkit), "runmodule.php?module=improbablestuff&use=largemedkit&from=village");
            }
            if ($energydrink > 0) {
                addnav(array("Use Energy Drink (%s remaining)", $energydrink), "runmodule.php?module=improbablestuff&use=energydrink&from=village");
            }
            if ($nicotinegum > 0) {
                addnav(array("Use Nicotine Gum (%s remaining)", $nicotinegum), "runmodule.php?module=improbablestuff&use=nicotinegum&from=village");
            }
            if ($potentpill > 0) {
                addnav(array("Use Power Pill (%s remaining)", $potentpill), "runmodule.php?module=improbablestuff&use=potentpill&from=village");
            }
            if ($teleporter > 0) {
                addnav(array("Use One-Shot Teleporter (%s remaining)", $teleporter), "runmodule.php?module=improbablestuff&use=teleporter", true);
            }
            if ($session['user']['race'] != "Robot" && $session['user']['race'] != "Gobot" && $session['user']['race'] != "Foebot" && $session['user']['race'] != "Joker" && $session['user']['race'] != "Stranger" && $rationpack > 0 && get_module_pref("fullness", "staminafood") < 100) {
                addnav(array("Use Ration Pack (%s remaining)", $rationpack), "runmodule.php?module=improbablestuff&use=rationpack&from=village", true);
            }
            if ($repellantspray > 0) {
                addnav(array("Use Monster Repellant Spray (%s remaining)", $repellantspray), "runmodule.php?module=improbablestuff&use=repellantspray&from=village");
            }
            strip_buff('ibomb7a');
            strip_buff('ibomb7b');
            strip_buff('ibomb8');
            break;
        case "worldnav":
            if ($smallmedkit >= 1 || $largemedkit >= 1 || $energydrink >= 1 || $nicotinegum >= 1 || $potentpill >= 1 || $repellantspray >= 1 || $rationpack >= 1) {
                addnav("`0`bUse Equipment`b`0");
            }
            if ($smallmedkit > 0) {
                addnav(array("Use Small Medkit (%s remaining)", $smallmedkit), "runmodule.php?module=improbablestuff&use=smallmedkit&from=worldnav");
            }
            if ($largemedkit > 0) {
                addnav(array("Use Large Medkit (%s remaining)", $largemedkit), "runmodule.php?module=improbablestuff&use=largemedkit&from=worldnav");
            }
            if ($energydrink > 0) {
                addnav(array("Use Energy Drink (%s remaining)", $energydrink), "runmodule.php?module=improbablestuff&use=energydrink&from=worldnav");
            }
            if ($nicotinegum > 0) {
                addnav(array("Use Nicotine Gum (%s remaining)", $nicotinegum), "runmodule.php?module=improbablestuff&use=nicotinegum&from=worldnav");
            }
            if ($potentpill > 0) {
                addnav(array("Use Power Pill (%s remaining)", $potentpill), "runmodule.php?module=improbablestuff&use=potentpill&from=worldnav");
            }
            if ($teleporter > 0) {
                addnav(array("Use One-Shot Teleporter (%s remaining)", $teleporter), "runmodule.php?module=improbablestuff&use=teleporter", true);
            }
            if ($session['user']['race'] != "Robot" && $session['user']['race'] != "Gobot" && $session['user']['race'] != "Foebot" && $session['user']['race'] != "Joker" && $session['user']['race'] != "Stranger" && $rationpack > 0 && get_module_pref("fullness", "staminafood") < 100) {
                addnav(array("Use Ration Pack (%s remaining)", $rationpack), "runmodule.php?module=improbablestuff&use=rationpack&from=worldnav", true);
            }
            if ($repellantspray > 0) {
                addnav(array("Use Monster Repellant Spray (%s remaining)", $repellantspray), "runmodule.php?module=improbablestuff&use=repellantspray&from=worldnav");
            }
            break;
        case "fightnav-specialties":
            $script = $args['script'];
            if ($banggrenade >= 1 || $whoomphgrenade >= 1 || $zapgrenade >= 1 || $teleporter >= 1 || $potentpill >= 1 || $repellantspray >= 1) {
                addnav("`0`bUse Equipment`b`0");
            }
            if ($banggrenade >= 1) {
                addnav(array("`4BANG Grenade`7 (%s left)`0", $banggrenade), $script . "op=fight&skill={$spec}&l=1", true);
            }
            if ($whoomphgrenade >= 1) {
                addnav(array("`^WHOOMPH Grenade`7 (%s left)`0", $whoomphgrenade), $script . "op=fight&skill={$spec}&l=2", true);
            }
            if ($zapgrenade >= 1) {
                addnav(array("`#ZAP Grenade`7 (%s left)`0", $zapgrenade), $script . "op=fight&skill={$spec}&l=3", true);
            }
            if ($potentpill >= 1) {
                addnav(array("Use Power Pill (%s remaining)", $potentpill), $script . "op=fight&skill={$spec}&l=4", true);
            }
            if ($teleporter >= 1) {
                addnav(array("`7One-Shot Teleporter`7 (%s left)`0", $teleporter), "runmodule.php?module=improbablestuff&use=teleporter", true);
            }
            if ($repellantspray >= 1) {
                addnav(array("Use Monster Repellant Spray (%s remaining)", $repellantspray), $script . "op=fight&skill={$spec}&l=5", true);
            }
            if ($improbabilitybomb >= 1) {
                addnav(array("Use Improbability Bomb (%s remaining)", $improbabilitybomb), $script . "op=fight&skill={$spec}&l=6", true);
            }
            break;
        case "ramiusfavors":
            if ($kittencard >= 1) {
                addnav("Other");
                addnav(array("K?`0Give `\$The Watcher`0 a Kitten Card (%s left)`0", $kittencard), "runmodule.php?module=improbablestuff&use=kittencard", true);
            }
            break;
        case "newday":
            set_module_pref("traveladd", 0);
            set_module_pref("encounterchance", 100, "worldmapen");
            set_module_pref("repellantbuff", 100);
            break;
        case "dragonkill":
            set_module_pref("item1number", 0);
            set_module_pref("item2number", 0);
            set_module_pref("item3number", 0);
            set_module_pref("item4number", 0);
            set_module_pref("item5number", 0);
            set_module_pref("item6number", 0);
            set_module_pref("item7number", 0);
            set_module_pref("item8number", 0);
            set_module_pref("item9number", 0);
            set_module_pref("item10number", 0);
            set_module_pref("item11number", 0);
            set_module_pref("item12number", 0);
            set_module_pref("item13number", 0);
            set_module_pref("traveladd", 0);
            set_module_pref("encounterchance", 100, "worldmapen");
            set_module_pref("repellantbuff", 100);
            break;
        case "apply-specialties":
            $skill = httpget('skill');
            $l = httpget('l');
            if ($skill == $spec) {
                if ($banggrenade >= 1) {
                    switch ($l) {
                        case 1:
                            apply_buff('is1', array("startmsg" => "`4You pull the pin on your grenade and toss it at {badguy}!", "rounds" => 1, "minioncount" => 1, "minbadguydamage" => "5+round(<attack>*1.0,0);", "maxbadguydamage" => "10+round(<attack>*2.0,0);", "effectmsg" => "`4The grenade explodes close enough to {badguy}`4 to do `^{damage}`4 damage!", "schema" => "module-improbablestuff"));
                            set_module_pref("item7number", get_module_pref("item7number") - 1);
                            break;
                    }
                }
                if ($whoomphgrenade >= 1) {
                    switch ($l) {
                        case 2:
                            apply_buff('is2', array("startmsg" => "`^You pull the pin on your grenade and toss it at {badguy}.  The grenade explodes with a satisfying WHOOMPH, close enough to set your foe aflame!", "name" => "`^WHOOMPH Grenade", "rounds" => -1, "minioncount" => 1, "minbadguydamage" => "1+round(<attack>*0.1,0);", "maxbadguydamage" => "2+round(<attack>*0.4,0);", "effectmsg" => "`^Your enemy beats at the flames, but it's still on fire!  `^{damage}`^ damage has been done in this round!", "expireafterfight" => 1, "schema" => "module-improbablestuff"));
                            set_module_pref("item8number", get_module_pref("item8number") - 1);
                            break;
                    }
                }
                if ($zapgrenade >= 1) {
                    switch ($l) {
                        case 3:
                            apply_buff('is3', array("startmsg" => "`#You pull the pin on your grenade and toss it at {badguy}`#, shielding your eyes.  After a blinding flash, your foe is left dazed and confused!", "name" => "`^ZAP Grenade", "rounds" => e_rand(2, 7), "badguyatkmod" => 0, "badguydefmod" => 0, "roundmsg" => "{badguy} is blinded, deafened and thoroughly confused, and flails wildly while you pummel it!`n", "wearoff" => "{badguy}`# feels some coherence return, and lunges at you!`n", "expireafterfight" => 1, "schema" => "module-improbablestuff"));
                            set_module_pref("item9number", get_module_pref("item9number") - 1);
                            break;
                    }
                }
                if ($potentpill >= 1) {
                    switch ($l) {
                        case 4:
                            apply_buff('is4', array("startmsg" => "`#You hastily swallow a Power Pill.  You feel immediately revitalised!  You regain some Stamina, and you are now regenerating some hitpoints!`n", "name" => "`^Power Pill", "rounds" => 10, "regen" => "ceil(<maxhitpoints>/10)+1;", "effectmsg" => "The effects of the Power Pill heal you for {damage} points.", "wearoff" => "The Power Pill effects have worn off.`n", "schema" => "module-improbablestuff"));
                            set_module_pref("item5number", get_module_pref("item5number") - 1);
                            require_once "modules/staminasystem/lib/lib.php";
                            addstamina(250000);
                            break;
                    }
                }
                if ($repellantspray >= 1) {
                    switch ($l) {
                        case 5:
                            apply_buff('is5', array("startmsg" => "`#You pull out a can of Monster Repellant Spray, and spray it liberally on the enemy!`n", "name" => "`^Repellant Spray", "rounds" => 10, "badguyatkmod" => 0.5, "badguydefmod" => 0.5, "roundmsg" => "{badguy} is coughing, choking and all runny-nosed, and cannot attack or defend as effectively!", "wearoff" => "The effects of your Monster Repellant Spray seem to have worn off...`n", "expireafterfight" => 1, "schema" => "module-improbablestuff"));
                            set_module_pref("item10number", get_module_pref("item10number") - 1);
                            break;
                    }
                }
                if ($improbabilitybomb >= 1) {
                    switch ($l) {
                        case 6:
                            $effect = e_rand(1, 9);
                            if (has_buff("ibomb7a") && $effect == 7) {
                                $effect = 3;
                            }
                            if (has_buff("ibomb8") && $effect == 8) {
                                $effect = 3;
                            }
                            apply_buff('startmsg', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0You light the fuse on the Improbability Bomb and toss it towards your opponent.", "schema" => "module-improbablestuff"));
                            increment_module_pref("item12number", -1);
                            switch ($effect) {
                                case 1:
                                    apply_buff('ibomb1', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The bomb bursts into a shower of Requisition tokens!  Blimey, there must be about a thousand of them!  What's more, all these tokens are swirling into the air and nose-diving straight into your pocket.  Result!", "schema" => "module-improbablestuff"));
                                    $gold = e_rand(900, 1100);
                                    $session['user']['gold'] += $gold;
                                    break;
                                case 2:
                                    apply_buff('ibomb2', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The fuse fizzes and sparks, until eventually... it goes out.  The bomb is gone.  However, there's a tasty, tasty cigarette in its place!  You grab it before your enemy gets the chance.", "schema" => "module-improbablestuff"));
                                    $session['user']['gems']++;
                                    break;
                                case 3:
                                    apply_buff('ibomb3', array("rounds" => 1, "minioncount" => 1, "minbadguydamage" => "5+round(<attack>*1.0,0);", "maxbadguydamage" => "5+round(<attack>*3.0,0);", "effectmsg" => "`4The bomb explodes close enough to {badguy}`4 to do `^{damage}`4 damage!", "schema" => "module-improbablestuff"));
                                    break;
                                case 4:
                                    apply_buff('ibomb4', array("rounds" => 1, "minioncount" => 1, "minbadguydamage" => 1000000, "maxbadguydamage" => 1000000000, "effectmsg" => "`4The fuse fizzles down until the bomb ignites with an tiny, dense explosion.  The gravity well draws {badguy}`4 in!  Within moments, {badguy} fuses with the matter that made up the original bomb in an ultra-dense, ultra-high gravity ball of dark matter, which then pops with a faint \"crack,\" leaving behind only a smoking area of burned ground about the size of a penny.  The damage done to the enemy, as if it matters at this stage, was `^{damage}`4 points!", "schema" => "module-improbablestuff"));
                                    break;
                                case 5:
                                    redirect("runmodule.php?module=improbablestuff&use=teleporter&bomb=1");
                                    break;
                                case 6:
                                    apply_buff('ibomb6', array("rounds" => 1, "atkmod" => 1, "startmsg" => "`0The Improbability Bomb breaks open, bathing you in a cool white light.  When it fades, you feel calm, self-confident and somehow more attractive.  Pretty useless in a combat situation, but hey, it's nice to be feel good about yourself.  You gain some Charm.", "schema" => "module-improbablestuff"));
                                    $session['user']['charm'] += 2;
                                    break;
                                case 7:
                                    apply_buff('ibomb7a', array("rounds" => 4, "minioncount" => 8, "minbadguydamage" => 0, "maxbadguydamage" => 5, "startmsg" => "The bomb begins to roll around the theater of combat, bouncing off rocks like a pinball - and firing out showers of white-hot sparks!", "effectmsg" => "`2A glowing spark leaps onto {badguy}, burning it for {damage} points!", "schema" => "module-improbablestuff", "expireafterfight" => 1));
                                    apply_buff('ibomb7b', array("rounds" => 4, "minioncount" => 8, "mingoodguydamage" => 0, "maxgoodguydamage" => 5, "effectmsg" => "`4A white-hot spark attaches to you, burning you for {damage} points!", "schema" => "module-improbablestuff", "wearoff" => "The bomb fizzles out and sends out one last dying volley of sparks.", "expireafterfight" => 1));
                                    break;
                                case 8:
                                    apply_buff('ibomb8', array("startmsg" => "`0The bomb uncurls, revealing a little `5Purple Monster!`0", "rounds" => -1, "name" => "`5Purple Monster`0", "minioncount" => 1, "minbadguydamage" => 5, "maxbadguydamage" => 50, "effectmsg" => "`5The Purple Monster leaps towards {badguy} and bites down hard for {damage} damage!`0", "schema" => "module-improbablestuff", "wearoff" => "`5The Purple Monster, seeing its business here concluded, disappears with a faint 'pop.'", "expireafterfight" => 1));
                                    break;
                                case 9:
                                    apply_buff('ibomb9', array("rounds" => 1, "minioncount" => 1, "mingoodguydamage" => 100, "maxgoodguydamage" => 500, "effectmsg" => "`4Before the bomb even leaves your hand, it blows up in your face!  The explosion causes {damage} points!", "schema" => "module-improbablestuff", "expireafterfight" => 1));
                                    break;
                            }
                            break;
                    }
                }
            }
            break;
    }
    return $args;
}
function expire_buffs()
{
    global $session, $badguy;
    tlschema("buffs");
    foreach ($session['bufflist'] as $key => $buff) {
        if (array_key_exists('suspended', $buff) && $buff['suspended']) {
            continue;
        }
        if ($buff['schema']) {
            tlschema($buff['schema']);
        }
        if (array_key_exists('used', $buff) && $buff['used']) {
            $session['bufflist'][$key]['used'] = 0;
            if ($session['bufflist'][$key]['rounds'] > 0) {
                $session['bufflist'][$key]['rounds']--;
            }
            if ((int) $session['bufflist'][$key]['rounds'] == 0) {
                if (isset($buff['wearoff']) && $buff['wearoff']) {
                    if (is_array($buff['wearoff'])) {
                        $buff['wearoff'] = str_replace("`%", "`%%", $buff['wearoff']);
                        $msg = sprintf_translate($buff['wearoff']);
                        $msg = substitute("`5" . $msg . "`0`n");
                        output_notl($msg);
                        //Here it's already translated
                    } else {
                        $msg = substitute("`5" . $buff['wearoff'] . "`0`n");
                        output_notl($msg);
                    }
                }
                //unset($session['bufflist'][$key]);
                strip_buff($key);
            }
        }
        if ($buff['schema']) {
            tlschema();
        }
    }
    tlschema();
}
function mountupgrade_dohook($hookname, $args)
{
    global $session;
    if (is_module_active("prizemount")) {
        $prizemount = get_module_setting("mountid", "prizemount");
        if ($prizemount) {
            $prizemounts = array($prizemount => 1);
            while ($prizemount) {
                $prizemount = get_module_objpref("mounts", $prizemount, "upgradeto", "mountupgrade");
                if ($prizemount) {
                    $prizemounts[$prizemount] = 1;
                }
            }
        }
    }
    $upgradeto = get_module_objpref("mounts", $session['user']['hashorse'], "upgradeto");
    if (get_module_objpref("mounts", $session['user']['hashorse'], "lose")) {
        $upgradeto = -1;
    }
    $upgradetext = get_module_objpref("mounts", $session['user']['hashorse'], "upgradetext");
    $reqdks = get_module_objpref("mounts", $session['user']['hashorse'], "reqdks");
    $reqlevels = get_module_objpref("mounts", $session['user']['hashorse'], "reqlevels");
    $reqdays = get_module_objpref("mounts", $session['user']['hashorse'], "reqdays");
    $reqffs = get_module_objpref("mounts", $session['user']['hashorse'], "reqffs");
    $upgrade = get_module_pref("upgrade");
    $metdks = get_module_pref("metdks");
    $metlevels = get_module_pref("metlevels");
    $metdays = get_module_pref("metdays");
    $metffs = get_module_pref("metffs");
    switch ($hookname) {
        case "pre-newday":
            if ($upgradeto && $metdks >= $reqdks && $metlevels >= $reqlevels && $metdays >= $reqdays && $metffs >= $reqdks) {
                set_module_pref("upgrade", 1);
                set_module_pref("upgradetext", $upgradetext);
                set_module_pref("metdks", 0);
                set_module_pref("metlevels", 0);
                set_module_pref("metdays", 0);
                set_module_pref("metffs", 0);
                global $playermount;
                $debugmount1 = $playermount['mountname'];
                if ($upgradeto == -1) {
                    strip_buff("mount");
                    $session['user']['hashorse'] = 0;
                    debuglog("upgraded their {$debugmount1} to nothing.");
                } else {
                    $session['user']['hashorse'] = $upgradeto;
                    $playermount = getmount($session['user']['hashorse']);
                    $debugmount2 = $playermount['mountname'];
                    debuglog("upgraded their {$debugmount1} to {$debugmount2}.");
                }
            }
            break;
        case "newday":
            if ($upgrade) {
                output("`n`^%s`0`n", stripslashes(translate_inline(get_module_pref("upgradetext"))));
                $mount = getmount($session['user']['hashorse']);
                apply_buff("mount", unserialize($mount['mountbuff']));
                set_module_pref("upgrade", 0);
            }
            if ($upgradeto && $reqdays) {
                set_module_pref("metdays", $metdays + 1);
            }
            break;
        case "dragonkill":
            if ($upgradeto) {
                if ($reqdks) {
                    set_module_pref("metdks", $metdks + 1);
                }
                if ($reqlevels) {
                    set_module_pref("metlevels", $metlevels + 1);
                }
            }
            break;
        case "battle-victory":
            static $runonce = false;
            if ($runonce !== false) {
                break;
            }
            $runonce = true;
            if ($upgradeto) {
                global $options;
                if ($reqffs && ($options['type'] == "forest" || $options['type'] == "travel")) {
                    set_module_pref("metffs", $metffs + 1);
                }
                if ($reqlevels && $options['type'] == "train") {
                    set_module_pref("metlevels", $metlevels + 1);
                }
            }
            break;
        case "battle-defeat":
            static $runonce = false;
            if ($runonce !== false) {
                break;
            }
            $runonce = true;
            global $options;
            if ($upgradeto && $reqffs && ($options['type'] == "forest" || $options['type'] == "travel")) {
                set_module_pref("metffs", $metffs + 1);
            }
            break;
        case "showformextensions":
            $args['mount'] = "mountupgrade_showform";
            break;
        case "boughtmount":
        case "soldmount":
            set_module_pref("upgrade", 0);
            set_module_pref("upgradetext", "");
            set_module_pref("metdks", 0);
            set_module_pref("metlevels", 0);
            set_module_pref("metdays", 0);
            set_module_pref("metffs", 0);
            break;
        case "gainprizemount":
            $oldmount = get_module_pref("prizemount");
            $prizemount = get_module_pref("mountid", "prizemount");
            if ($prizemount != $oldmount) {
                while ($prizemount) {
                    $prizemount = get_module_objpref("mounts", $prizemount, "upgradeto", "mountupgrade");
                    if ($prizemount == $oldmount) {
                        $args['prizemount'] = $prizemount;
                        break;
                    }
                }
            }
            if ($upgradeto) {
                set_module_pref("savedks", $metdks);
                set_module_pref("savelevels", $metlevels);
                set_module_pref("savedays", $metdays);
                set_module_pref("saveffs", $metffs);
            }
            break;
        case "loseprizemount":
            set_module_pref("metdks", get_module_pref("savedks"));
            set_module_pref("metlevels", get_module_pref("savelevels"));
            set_module_pref("metdays", get_module_pref("savedays"));
            set_module_pref("metffs", get_module_pref("saveffs"));
            if ($upgradeto) {
                set_module_pref("prizemount", $session['user']['hashorse']);
                set_module_pref("savedks", $metdks);
                set_module_pref("savelevels", $metlevels);
                set_module_pref("savedays", $metdays);
                set_module_pref("saveffs", $metffs);
            }
            break;
    }
    return $args;
}
function dragonbuffercizer_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "buffdragon":
            //Checking for and setting up the dragonfire buff
            $breathfire = get_module_setting("breathfire");
            if ($breathfire && e_rand(1, 100) < get_module_setting("firechance")) {
                $firebase = get_module_setting("firebase");
                $firebydk = get_module_setting("firebydk");
                $firebydkpoints = get_module_setting("firebydkpoints");
                $dkpoints = 0;
                if ($firebydkpoints > 0) {
                    $dkpoints = round(($session['user']['maxhitpoints'] - 150) / 5, 0);
                    //I'm not exactly certain that the following while loop works.
                    while (list($key, $val) = each($session['user']['dragonpoints'])) {
                        if ($val == "at" || $val == "de") {
                            $dkpoints++;
                        }
                    }
                }
                $maxfiredamage = round($firebase + $firebydk * $session['user']['dragonkills'] + $firebydkpoints * $dkpoints, 0);
                apply_buff('improbably_burny_fire', array("startmsg" => "`n`^The Improbability Drive flickers for a moment as it changes reality.  When the Improbability energy has faded, you realise whta the Improbability Drive has changed - you're on fire!`n`n", "name" => "`%Improbably Burny Fire", "rounds" => 30, "wearoff" => "The Improbably Burny Fire appears to be extinguished.  The drive must be getting weak now.", "minioncount" => 1, "mingoodguydamage" => 0, "maxgoodguydamage" => $maxfiredamage, "effectmsg" => "`7You are engulfed in `4Improbably Burny fire`7 and take`4 {damage} `7damage.`0", "effectnodmgmsg" => "`7You are engulfed in `4Improbably Burny fire`7 but take no damage.`0", "effectfailmsg" => "`7Miraculously, the `4Improbably Burny fire`7 misses you.`0", "schema" => "module-dragonbuffercizer"));
                debug("DEBUG: Max {$maxfiredamage} damage of dragonfire.");
            }
            //Compiling the different methods of dragon stat determination
            $standardweight = get_module_setting("standardweight");
            $doppleweight = get_module_setting("doppleweight");
            $dkmodelweight = get_module_setting("dkmodelweight");
            // The scaled doppleganger model
            $attackratio = get_module_setting("attackratio");
            $defenseratio = get_module_setting("defenseratio");
            $hpratio = get_module_setting("hpratio");
            // starting with a dragon that is the same level as the player,
            // with a level 15 weapon and armor
            $dopplegangeratk = $session['user']['attack'] * $attackratio;
            $dopplegangerdef = $session['user']['defense'] * $defenseratio;
            $dopplegangerhealth = $hpratio * $session['user']['maxhitpoints'];
            //dkmodel stats
            $numdks = $session['user']['dragonkills'];
            $dkmodelhealth = get_module_setting("dkbasehp") + $numdks * get_module_setting("dkhprate");
            $dkmodelatk = get_module_setting("dkbaseatk") + $numdks * get_module_setting("dkatkrate");
            $dkmodeldef = get_module_setting("dkbasedef") + $numdks * get_module_setting("dkdefrate");
            //Adding up the differently weighted components
            $statrandom = get_module_pref("statrandom");
            $args['creatureattack'] = round(($args['creatureattack'] * $standardweight + $dopplegangeratk * $doppleweight + $dkmodelatk * $dkmodelweight) / ($standardweight + $doppleweight + $dkmodelweight), 0);
            $args['creaturedefense'] = round(($args['creaturedefense'] * $standardweight + $dopplegangerdef * $doppleweight + $dkmodeldef * $dkmodelweight) / ($standardweight + $doppleweight + $dkmodelweight), 0);
            $args['creaturehealth'] = round(($args['creaturehealth'] * $standardweight + $dopplegangerhealth * $doppleweight + $dkmodelhealth * $dkmodelweight) / ($standardweight + $doppleweight + $dkmodelweight), 0);
            if ($statrandom) {
                $randompercent = get_module_setting("randompercent");
                $args['creatureattack'] = e_rand(round($args['creatureattack'] * (1 - $randompercent / 100), 0), round($args['creatureattack'] * (1 + $randompercent / 100), 0));
                $args['creaturedefense'] = e_rand(round($args['creaturedefense'] * (1 - $randompercent / 100), 0), round($args['creaturedefense'] * (1 + $randompercent / 100), 0));
                $args['creaturehealth'] = e_rand(round($args['creaturehealth'] * (1 - $randompercent / 100), 0), round($args['creaturehealth'] * (1 + $randompercent / 100), 0));
            }
            break;
        case "dragonkilltext":
            strip_buff('dragonfire');
            break;
        case "shades":
            strip_buff('dragonfire');
            break;
    }
    $dragonatk = $args['creatureattack'];
    $dragondef = $args['creaturedefense'];
    debug("DEBUG-dragonbuffercizer: dragon attack set to {$dragonatk}");
    debug("DEBUG-dragonbuffercizer: dragon defense set to {$dragondef}");
    return $args;
}
function strip_accessories()
{
    global $session;
    $accs = get_player_acc_list($userid);
    foreach ($accs as $acc => $details) {
        strip_buff($acc);
        modulehook("mountaccessories_strip_accessories", $acc);
    }
    $blank = array();
    set_module_pref("accessories", serialize($blank), "mountaccessories");
}
        tlschema();
    }
} elseif ($op == 'sellmount') {
    tlschema($schemas['confirmsale']);
    output($texts['confirmsale'], $session['user']['sex'] ? $texts["lass"] : $texts["lad"]);
    tlschema();
    addnav("Confirm sale");
    addnav("Yes", "stables.php?op=confirmsell");
    addnav("No", "stables.php");
    $confirm = 1;
} elseif ($op == 'confirmsell') {
    $session['user']['gold'] += $repaygold;
    $session['user']['gems'] += $repaygems;
    $debugmount = $playermount['mountname'];
    debuglog("gained {$repaygold} gold and {$repaygems} gems selling their mount, a {$debugmount}");
    strip_buff('mount');
    $session['user']['hashorse'] = 0;
    modulehook("soldmount");
    $amtstr = "";
    if ($repaygold > 0) {
        $amtstr .= "%s gold";
    }
    if ($repaygems > 0) {
        if ($repaygold) {
            $amtstr .= " and ";
        }
        $amtstr .= "%s gems";
    }
    if ($repaygold > 0 && $repaygems > 0) {
        $amtstr = sprintf_translate($amtstr, $repaygold, $repaygems);
    } elseif ($repaygold > 0) {
function racerobot_run()
{
    global $session;
    page_header("Overclocking Configuration");
    $from = httpget('from');
    switch (httpget('op')) {
        case "config":
            output("You sit down and open up your chest panel.  Inside is a row of variable resistors which increase power to various subsystems.  You can adjust the resistors to enhance your performance in combat, albeit with some tradeoffs - applying too much voltage will result in catastrophic overheating.`n`nYou mull over your decisions carefully.`n`n");
            break;
        case "atkinc":
            output("You twist the Upper Torso Servo Voltage VR clockwise.  You feel a rush of extra burning energy in your arms.  This should help with your attack power.`n`n");
            increment_module_pref("atk");
            break;
        case "atkdec":
            output("You twist the Upper Torso Servo Voltage VR anti-clockwise.  You feel your attack power drain away a little.`n`n");
            increment_module_pref("atk", -1);
            break;
        case "definc":
            output("You twist the Lower Torso Servo Voltage VR clockwise.  You feel a rush of extra burning energy in your legs, making you lighter on your feet and better able to step out of the way of impending fists and claws.`n`n");
            increment_module_pref("def");
            break;
        case "defdec":
            output("You twist the Lower Torso Servo Voltage VR anti-clockwise.  Your legs feel more sluggish, and you have a feeling you won't be able to dodge blows from enemies as easily.`n`n");
            increment_module_pref("def", -1);
            break;
        case "healinc":
            output("You twist the Damage Repair Subsystem CPU Voltage VR clockwise.  You feel the extra threads rushing through you, ready to heal your glass skin during battle.`n`n");
            increment_module_pref("heal");
            break;
        case "healdec":
            output("You twist the Damage Repair Subsystem CPU Voltage VR anti-clockwise.  The CPU controlling your in-combat self-healing abilities lowers its speed by a few megahertz.  You feel slightly uneasy and vulnerable.`n`n");
            increment_module_pref("heal", -1);
            break;
        case "standby":
            $heat = get_module_pref("heat");
            require_once "modules/staminasystem/lib/lib.php";
            switch (httpget('til')) {
                case "repaired":
                    output("You go into Standby Mode, reducing every system process to the bare minimum required to stay alive, and activate your self-healing routine.  The cracks in your glass skin begin to shorten in jagged little hops.`n`nThe sound of glass mending itself is, oddly enough, rather similar to the sound of glass breaking.`n`nYour subsystems cool down too, with little plinks and pops.`n`n");
                    $hp = $session['user']['maxhitpoints'] - $session['user']['hitpoints'];
                    $s = 0;
                    for ($i = 0; $i < $hp; $i++) {
                        $session['user']['hitpoints']++;
                        $heat -= 10;
                        $s += 400;
                    }
                    removestamina($s);
                    output("When consciousness returns, your Hitpoints have been restored to full and your internal systems have cooled down a little.  You have used `Q%s`0 Stamina points (about `Q%s`0%% of total Stamina).`n`n", number_format($s), $s / 1000000 * 100);
                    break;
                case "cooled":
                    output("You go into Standby Mode, reducing every system process to the bare minimum required to stay alive, and activate your self-healing routine.  The cracks in your glass skin begin to shorten in jagged little hops.`n`nThe sound of glass mending itself is, oddly enough, rather similar to the sound of glass breaking.`n`nYour subsystems cool down too, with little plinks and pops.`n`n");
                    $j = $heat / 10;
                    $s = 0;
                    for ($i = 0; $i < $j; $i++) {
                        $session['user']['hitpoints']++;
                        $heat -= 10;
                        $s += 400;
                    }
                    removestamina($s);
                    output("When consciousness returns, your Hitpoints have increased and your internal systems have cooled down to normal operating temperatures.  You have used `Q%s`0 Stamina points (about `Q%s`0%% of total Stamina).`n`n", number_format($s), $s / 1000000 * 100);
                    break;
            }
            if ($session['user']['hitpoints'] > $session['user']['maxhitpoints']) {
                $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            }
            if ($heat < 0) {
                $heat = 0;
            }
            set_module_pref("heat", $heat);
            strip_buff('robotoverheat');
            break;
    }
    $atk = get_module_pref("atk");
    $def = get_module_pref("def");
    $heal = get_module_pref("heal");
    $buff = get_module_pref("buff");
    $heat = get_module_pref("heat");
    addnav("Upper Torso Servo Voltage");
    addnav("Increase", "runmodule.php?module=racerobot&op=atkinc&from=" . $from);
    if ($atk > 0) {
        addnav("Decrease", "runmodule.php?module=racerobot&op=atkdec&from=" . $from);
    }
    addnav("Lower Torso Servo Voltage");
    addnav("Increase", "runmodule.php?module=racerobot&op=definc&from=" . $from);
    if ($def > 0) {
        addnav("Decrease", "runmodule.php?module=racerobot&op=defdec&from=" . $from);
    }
    addnav("Damage Repair Subsystem CPU Voltage");
    addnav("Increase", "runmodule.php?module=racerobot&op=healinc&from=" . $from);
    if ($heal > 0) {
        addnav("Decrease", "runmodule.php?module=racerobot&op=healdec&from=" . $from);
    }
    // addnav("Combat Analysis Module RAM Voltage");
    // addnav("Increase","runmodule.php?module=racerobot&op=buffinc&from=".$from);
    // if ($buff>0) addnav("Decrease","runmodule.php?module=racerobot&op=buffdec&from=".$from);
    addnav("Standby Mode");
    if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
        $scost = 400 * ($session['user']['maxhitpoints'] - $session['user']['hitpoints']);
        $spct = $scost * 100 / 1000000;
        addnav(array("Standby until Repaired (`Q%s%%`0)", $spct), "runmodule.php?module=racerobot&op=standby&til=repaired&from=" . $from . "", true);
    }
    if ($heat > 0) {
        $scost = 40 * $heat;
        $spct = $scost * 100 / 1000000;
        addnav(array("Standby until Cooled (`Q%s%%`0)", $spct), "runmodule.php?module=racerobot&op=standby&til=cooled&from=" . $from . "", true);
    }
    addnav("Close chest panel");
    switch ($from) {
        case "village":
            addnav("Return to the Outpost", "village.php");
            break;
        case "forest":
            addnav("Return to the Jungle", "forest.php");
            break;
        case "worldnav":
            addnav("Return to the Wilderness", "runmodule.php?module=worldmapen&op=continue");
            break;
    }
    $atk = get_module_pref("atk");
    $def = get_module_pref("def");
    $heal = get_module_pref("heal");
    $buff = get_module_pref("buff");
    $heat = get_module_pref("heat");
    output("`bCurrent settings:`b`n");
    output("Upper Torso Servo Voltage: +%sv`n", $atk * 10);
    output("Lower Torso Servo Voltage: +%sv`n", $def * 10);
    output("Damage Repair Subsystem CPU Voltage: +%sv`n", $heal * 10);
    // output("Combat Analysis Module RAM Voltage: +%sv`n",$buff*10);
    if (get_module_pref("atk") > 0) {
        $batk = get_module_pref("atk") / 10 + 1;
        apply_buff("robotatkoc", array("name" => "`7Overclock: Increased Upper Body Servo Power`0", "atkmod" => $batk, "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racerobot"));
    } else {
        strip_buff("robotatkoc");
    }
    if (get_module_pref("def") > 0) {
        $bdef = get_module_pref("def") / 10 + 1;
        apply_buff("robotdefoc", array("name" => "`7Overclock: Increased Lower Body Servo Power`0", "defmod" => $bdef, "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racerobot"));
    } else {
        strip_buff("robotdefoc");
    }
    if (get_module_pref("heal") > 0) {
        $bheal = get_module_pref("heal");
        apply_buff("robothealoc", array("name" => "`7Overclock: In-Combat Self-Repair Subsystem`0", "regen" => $bheal, "effectmsg" => "`#SYSTEM MESSAGE: {damage} POINTS OF DAMAGE AUTO-REPAIRED`0", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racerobot"));
    } else {
        strip_buff("robothealoc");
    }
    page_footer();
}
function goldmine_runevent($type)
{
    global $session;
    // The only type of event we care about are the forest.
    $from = "forest.php?";
    $hashorse = $session['user']['hashorse'];
    $horsecanenter = 0;
    $horsecandie = 0;
    $horsecansave = 0;
    if ($hashorse) {
        $horsecanenter = get_module_objpref('mounts', $hashorse, 'entermine');
        // See if we automatically tether;
        if (e_rand(1, 100) <= get_module_setting("alwaystether")) {
            $horsecanenter = 0;
        }
        if ($horsecanenter) {
            // The mount cannot die or save you if it cannot enter
            $horsecandie = get_module_objpref('mounts', $hashorse, 'dieinmine');
            $horsecansave = get_module_objpref('mounts', $hashorse, 'saveplayer');
        }
        require_once "lib/mountname.php";
        list($mountname, $lcmountname) = getmountname();
    }
    $session['user']['specialinc'] = "module:goldmine";
    $op = httpget('op');
    if ($op == "" || $op == "search") {
        output("`2You found an old abandoned mine in the depths of the forest.");
        output("There is some old mining equipment nearby.`n`n");
        output("`^As you look around you realize that this is going to be a lot of work.");
        output("So much so in fact that you will lose a forest fight for the day if you attempt it.`n`n");
        output("`^Looking around a bit more, you do notice what looks like evidence of occasional cave-ins in the mine.`n`n");
        addnav("Mine for gold and gems", $from . "op=mine");
        addnav("Return to the forest", $from . "op=no");
    } elseif ($op == "no") {
        output("`2You decide you don't have time for this slow way to gain gold and gems, and so leave the old mine behind and go on your way...`n");
        $session['user']['specialinc'] = "";
    } elseif ($op == "mine") {
        if ($session['user']['turns'] <= 0) {
            output("`2You are too tired to mine anymore..`n");
            $session['user']['specialinc'] = "";
        } else {
            // Horsecanenter is a percent, so, if rand(1-100) > enterpercent,
            // tether it.  Set enter percent to 0 (the default), to always
            // tether.
            if (e_rand(1, 100) > $horsecanenter && $hashorse) {
                $msg = get_module_objpref('mounts', $hashorse, 'tethermsg');
                if ($msg) {
                    output($msg);
                } else {
                    output("`&Seeing that the mine entrance is too small for %s`&, you tether it off to the side of the entrance.`n", $lcmountname);
                }
                // The mount it tethered, so it cannot die nor save the player
                $horsecanenter = 0;
                $horsecandie = 0;
                $horsecansave = 0;
            }
            output("`2You pick up the mining equipment and start mining for gold and gems...`n`n");
            $rand = e_rand(1, 20);
            switch ($rand) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    output("`2After a few hours of hard work you have only found worthless stones and one skull...`n`n");
                    output("`^You lose one forest fight while digging.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    $gold = e_rand($session['user']['level'] * 5, $session['user']['level'] * 20);
                    output("`^After a few hours of hard work, you find %s gold!`n`n", $gold);
                    $session['user']['gold'] += $gold;
                    debuglog("found {$gold} gold in the goldmine");
                    output("`^You lose one forest fight while digging.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                    $gems = e_rand(1, round($session['user']['level'] / 7) + 1);
                    output("`^After a few hours of hard work, you find `%%s %s`^!`n`n", $gems, translate_inline($gems == 1 ? "gem" : "gems"));
                    $session['user']['gems'] += $gems;
                    debuglog("found {$gems} gems in the goldmine");
                    output("`^You lose one forest fight while digging.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 16:
                case 17:
                case 18:
                    $gold = e_rand($session['user']['level'] * 10, $session['user']['level'] * 40);
                    $gems = e_rand(1, round($session['user']['level'] / 3) + 1);
                    output("`^You have found the mother lode!`n`n");
                    output("`^After a few hours of hard work, you find `%%s %s`^ and %s gold!`n`n", $gems, translate_inline($gems == 1 ? "gem" : "gems"), $gold);
                    $session['user']['gems'] += $gems;
                    $session['user']['gold'] += $gold;
                    debuglog("found {$gold} gold and {$gems} gems in the goldmine");
                    output("`^You lose one forest fight while digging.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 19:
                case 20:
                    output("`2After a lot of hard work you believe you have spotted a `&huge`2 `%gem`2 and some `6gold`2.`n");
                    output("`2Anxious to be rich, you rear back and slam the pick home, knowing that the harder you hit, the quicker you will be done....`n");
                    output("`7Unfortunately, you are quickly done in.`n");
                    output("Your over-exuberant hit caused a massive cave in.`n");
                    // Find the chance of dying based on race
                    $vals = modulehook("raceminedeath");
                    $dead = 0;
                    $racesave = 1;
                    if (isset($vals['racesave']) && $vals['racesave']) {
                        if ($vals['schema']) {
                            tlschema($vals['schema']);
                        }
                        $racemsg = translate_inline($vals['racesave']);
                        if ($vals['schema']) {
                            tlschema();
                        }
                    }
                    if (isset($vals['chance']) && e_rand(1, 100) < $vals['chance']) {
                        $dead = 1;
                        $racesave = 0;
                        $racemsg = "";
                    }
                    if ($dead) {
                        // The player has died, see if their horse saves them
                        if (isset($horsecansave) && e_rand(1, 100) <= $horsecansave) {
                            $dead = 0;
                            $horsesave = 1;
                        }
                    }
                    // If we are still dead, see if the horse dies too.
                    $session['user']['specialinc'] = "";
                    if ($dead) {
                        if (e_rand(1, 100) <= $horsecandie) {
                            $horsedead = 1;
                        }
                        output("You have been crushed under a ton of rock.`n`nPerhaps the next adventurer will recover your body and bury it properly.`n");
                        if ($horsedead) {
                            $msg = get_module_objpref('mounts', $hashorse, 'deathmsg');
                            if ($msg) {
                                output($msg);
                            } else {
                                output("%s`7's bones were buried right alongside yours.", $mountname);
                            }
                            global $playermount;
                            $debugmount = $playermount['mountname'];
                            debuglog("lost their mount, a {$debugmount}, in a mine collapse.");
                            $session['user']['hashorse'] = 0;
                            if (isset($session['bufflist']['mount'])) {
                                strip_buff("mount");
                            }
                        } elseif ($hashorse) {
                            if ($horsecanenter) {
                                output("%s`7 managed to escape being crushed.", $mountname);
                                output("You know that it is trained to return to the village.`n");
                            } else {
                                output("Fortunately you left %s`7 tethered outside.", $lcmountname);
                                output("You know that it is trained to return to the village.`n");
                            }
                        }
                        $exp = round($session['user']['experience'] * 0.1, 0);
                        output("At least you learned something about mining from this experience and have gained %s experience.`n`n", $exp);
                        output("`3You may continue to play tomorrow`n");
                        $session['user']['experience'] += $exp;
                        $session['user']['alive'] = false;
                        $session['user']['hitpoints'] = 0;
                        $gemlost = round(get_module_setting("percentgemloss") / 100 * $session['user']['gems'], 0);
                        $goldlost = round(get_module_setting("percentgoldloss") / 100 * $session['user']['gold'], 0);
                        debuglog("lost {$goldlost} gold and {$gemlost} gems by dying in the goldmine");
                        output("`^%s gold `&and `%%s %s`& were lost when you were buried!", $goldlost, $gemlost, translate_inline($gemlost == 1 ? "gem" : "gems"));
                        $session['user']['gold'] -= $goldlost;
                        $session['user']['gems'] -= $gemlost;
                        addnav("Daily News", "news.php");
                        addnews("%s was completely buried after becoming greedy digging in the mines.", $session['user']['name']);
                    } else {
                        if (isset($horsesave) && $horsesave) {
                            $msg = get_module_objpref('mounts', $hashorse, 'savemsg');
                            if ($msg) {
                                output($msg);
                            } else {
                                output("%s`7 managed to drag you to safety in the nick of time!`n", $mountname);
                            }
                        } elseif ($racesave) {
                            if (isset($racemsg) && $racemsg) {
                                output_notl($racemsg);
                            } else {
                                output("Through sheer luck, you manage to escape the cave-in intact!`n");
                            }
                        }
                        output("`n`&Your close call scared you so badly that you cannot face any more opponents today.`n");
                        debuglog("`&has lost all turns for the day due to a close call in the mine.");
                        $session['user']['turns'] = 0;
                    }
                    break;
            }
        }
    }
}
function implantlaser_dohook($hookname, $args)
{
    global $session, $resline;
    $spec = "HL";
    $name = "Skull-Mounted Laser";
    $ccode = "`\$";
    switch ($hookname) {
        case "dragonkill":
            set_module_pref("primary", 0);
            set_module_pref("secondary", 0);
            set_module_pref("status", 0);
            break;
        case "choose-specialty":
            if ($session['user']['dragonkills'] < 5) {
                break;
            }
            if ($session['user']['specialty'] == "" || $session['user']['specialty'] == '0') {
                addnav("{$ccode}{$name}`0", "newday.php?setspecialty={$spec}{$resline}");
                output("\"`5This one - goodness, it's rather heavy - actually bolts on to the side of your head, rather than going in the brain.  It's a `\$Skull-Mounted Laser`5, you see.  Most of the weight is taken up by the batteries - you get one small battery which is recharged every day, and one large battery that has to last you for your whole adventure.  It's a very, very powerful combat-orientated Implant, but you've got to keep an eye on your battery levels, or you'll be in trouble later on.\"`n`n");
            }
            break;
        case "set-specialty":
            if ($session['user']['specialty'] == $spec) {
                page_header($name);
                output("`\$Not all implants are as subtle as a chip in the brain.  You learn this after examining the housebrick-sized box jutting out of the side of your head.`n`n");
                output("It's painted black, and features a small aperature on the front.  The warning symbols for Laser Radiation and Oxidizing Element are displayed in yellow triangles just above your ear.`n`n");
                output("The user manual states that the laser's output power is pretty well infinitely-adjustable - however, taking it up too high will deplete the primary battery pretty well straight away, prompting the laser to begin draining the secondary battery.`n`nThe medic's warnings about the secondary battery come back to haunt you; use it sparingly, because it has to last you for a long time.");
                clear_module_pref("primary");
                clear_module_pref("secondary");
            }
            break;
        case "specialtycolor":
            $args[$spec] = $ccode;
            break;
        case "specialtynames":
            $args[$spec] = translate_inline($name);
            break;
        case "specialtymodules":
            $args[$spec] = "implantlaser";
            break;
        case "newday":
            if ($session['user']['specialty'] == $spec) {
                output("`nThe primary battery on your Head-Mounted Laser has been charged overnight, and is now at full capacity.`n");
                $primary = $session['user']['level'] * 2 + 20;
                set_module_pref("primary", $primary);
                set_module_pref("status", 0);
            }
            set_module_pref("status", 0);
            strip_buff('headlaser');
            break;
        case "forest":
            if ($session['user']['specialty'] == $spec) {
                if (get_module_pref("primary") > 0 || get_module_pref("secondary") > 0) {
                    addnav(array("{$ccode} `bSkull-Mounted Laser`b`0", ""));
                    addnav(array("Battery: (%s/%s)`0", get_module_pref("primary"), get_module_pref("secondary")), "");
                    addnav(array("Power output: %sKw`0", get_module_pref("powerlevel")), "");
                    addnav("Increase laser power`0", "runmodule.php?module=implantlaser&op=inc&from=forest");
                    if (get_module_pref("powerlevel") > 1) {
                        addnav("Decrease laser power`0", "runmodule.php?module=implantlaser&op=dec&from=forest");
                    }
                }
            }
            break;
        case "village":
            if ($session['user']['specialty'] == $spec) {
                if (get_module_pref("primary") > 0 || get_module_pref("secondary") > 0) {
                    addnav(array("{$ccode} `bSkull-Mounted Laser`b`0", ""));
                    addnav(array("Battery: (%s/%s)`0", get_module_pref("primary"), get_module_pref("secondary")), "");
                    addnav(array("Power output: %sKw`0", get_module_pref("powerlevel")), "");
                    addnav("Increase laser power`0", "runmodule.php?module=implantlaser&op=inc&from=village");
                    if (get_module_pref("powerlevel") > 1) {
                        addnav("Decrease laser power`0", "runmodule.php?module=implantlaser&op=dec&from=village");
                    }
                }
                set_module_pref("status", 0);
                strip_buff('headlaser');
            }
            break;
        case "worldnav":
            if ($session['user']['specialty'] == $spec) {
                if (get_module_pref("primary") > 0 || get_module_pref("secondary") > 0) {
                    addnav(array("{$ccode} `bSkull-Mounted Laser`b`0", ""));
                    addnav(array("Battery: (%s/%s)`0", get_module_pref("primary"), get_module_pref("secondary")), "");
                    addnav(array("Power output: %sKw`0", get_module_pref("powerlevel")), "");
                    addnav("Increase laser power`0", "runmodule.php?module=implantlaser&op=inc&from=worldnav");
                    if (get_module_pref("powerlevel") > 1) {
                        addnav("Decrease laser power`0", "runmodule.php?module=implantlaser&op=dec&from=worldnav");
                    }
                }
                set_module_pref("status", 0);
                strip_buff('headlaser');
            }
            break;
        case "fightnav-specialties":
            if ($session['user']['specialty'] == $spec) {
                // Evaluate the number of rounds that the battle has lasted thus far.  Because this is only called once per click, and the user can choose to play five rounds, ten rounds or to the end of the fight, we've got to get the number of rounds by looking at the remaining rounds left in the buff we set up the last time the user clicked to fight.
                if (has_buff("headlaser")) {
                    $roundsplayed = 1000 - $session['bufflist']['headlaser-roundtrack']['rounds'];
                    set_module_pref("primary", get_module_pref("primary") - get_module_pref("powerlevel") * $roundsplayed);
                    if (get_module_pref("primary") < 0) {
                        $discrepancy = get_module_pref("primary");
                        $discrepancy = $discrepancy - $discrepancy - $discrepancy;
                        debug($discrepancy);
                        set_module_pref("secondary", get_module_pref("secondary") - $discrepancy);
                        set_module_pref("primary", 0);
                        if (get_module_pref("secondary") < 0) {
                            set_module_pref("secondary", 0);
                            set_module_pref("status", 0);
                            strip_buff('headlaser');
                            strip_buff('headlaser-roundtrack');
                        }
                    }
                } else {
                    $roundsplayed = 0;
                    set_module_pref("status", 0);
                }
                apply_buff('headlaser-roundtrack', array("rounds" => 1000, "dmgmod" => 1));
                $script = $args['script'];
                $primary = get_module_pref("primary");
                $secondary = get_module_pref("secondary");
                if ($primary > 0 || $secondary > 0) {
                    addnav(array("{$ccode} `bSkull-Mounted Laser`b`0", ""));
                    addnav(array("Battery: %s (%s)`0", $primary, $secondary), "");
                    addnav(array("Power output: %sKw`0", get_module_pref("powerlevel")), "");
                    if (get_module_pref("status") == 0) {
                        if ($primary + $secondary > get_module_pref("powerlevel")) {
                            addnav(array("{$ccode} &#149; Turn on laser`0"), $script . "op=fight&skill={$spec}&l=on", true);
                        } else {
                            addnav("Not enough battery power to fire laser", "");
                        }
                        addnav(array("{$ccode} &#149; Increase laser power`0"), $script . "op=fight&skill={$spec}&l=inc", true);
                        if (get_module_pref("powerlevel") > 1) {
                            addnav(array("{$ccode} &#149; Decrease laser power`0"), $script . "op=fight&skill={$spec}&l=dec", true);
                        }
                    }
                    if (get_module_pref("status") == 1) {
                        addnav(array("{$ccode} &#149; Turn off laser`0"), $script . "op=fight&skill={$spec}&l=off", true);
                    }
                }
            }
            break;
        case "apply-specialties":
            if ($session['user']['specialty'] == $spec) {
                $skill = httpget('skill');
                $l = httpget('l');
                if ($skill == $spec) {
                    switch ($l) {
                        case "inc":
                            set_module_pref("powerlevel", get_module_pref("powerlevel") + 1);
                            output("`\$You reach up and twiddle the knobs on your housebrick-sized cranial implant.  You have `bincreased`b your laser's output power by one kilowatt, taking it up to %s.`n", get_module_pref("powerlevel"));
                            break;
                        case "dec":
                            set_module_pref("powerlevel", get_module_pref("powerlevel") - 1);
                            output("`\$You reach up and twiddle the knobs on your housebrick-sized cranial implant.  You have `bdecreased`b your laser's output power by one kilowatt, taking it down to %s.`n", get_module_pref("powerlevel"));
                            break;
                        case "on":
                            if (get_module_pref("secondary") > 0 || get_module_pref("primary") > 0) {
                                apply_buff('headlaser', array("startmsg" => "`\$Your laser steams into life, sending a beam of burning light towards {badguy}!", "name" => "`\$Head-Mounted Laser", "effectmsg" => "`\${badguy} yelps in pain as the laser burns into its body, doing `^{damage}`\$ points' worth of damage!", "rounds" => -1, "minioncount" => 1, "minbadguydamage" => ceil(get_module_pref("powerlevel") / 2), "maxbadguydamage" => ceil(get_module_pref("powerlevel") * 2), "schema" => "module-implantlaser"));
                                set_module_pref("status", 1);
                            } else {
                                output("Your laser's batteries are DEAD!");
                            }
                            break;
                        case "off":
                            set_module_pref("status", 0);
                            strip_buff('headlaser');
                            break;
                    }
                }
            }
            break;
        case "battle-defeat":
        case "battle-victory":
            if ($session['user']['specialty'] == $spec) {
                if (get_module_pref("status") == 1) {
                    set_module_pref("status", 0);
                    if (has_buff("headlaser")) {
                        $roundsplayed = 1001 - $session['bufflist']['headlaser-roundtrack']['rounds'];
                        set_module_pref("primary", get_module_pref("primary") - get_module_pref("powerlevel") * $roundsplayed);
                        if (get_module_pref("primary") < 0) {
                            set_module_pref("secondary", get_module_pref("secondary") - get_module_pref("powerlevel") * $roundsplayed);
                            set_module_pref("primary", 0);
                            if (get_module_pref("secondary") < 0) {
                                set_module_pref("secondary", 0);
                                set_module_pref("status", 0);
                                strip_buff('headlaser');
                                strip_buff('headlaser-roundtrack');
                            }
                        }
                    }
                    output("`n`\$Your head-mounted laser, seeing its target suitably chastised, switches off automatically.`n");
                }
                strip_buff('headlaser');
            }
            break;
    }
    return $args;
}
function staminacorecombat_applystaminabuff()
{
    //increments and applies the Exhaustion Penalty
    global $session;
    $amber = get_stamina();
    if ($amber < 100) {
        //Gives a proportionate debuff from 1 to 0.2, at 2 decimal places each time
        $buffvalue = round(($amber / 100 * 80 + 20) / 100, 2);
        if ($buffvalue < 1) {
            $buffmsg = "`0You're getting tired...";
        }
        if ($buffvalue < 0.8) {
            $buffmsg = "`4You're getting `ivery`i tired...`0";
        }
        if ($buffvalue < 0.6) {
            $buffmsg = "`\$You're getting `bexhausted!`b`0";
        }
        if ($buffvalue < 0.3) {
            $buffmsg = "`\$You're getting `bdangerously exhausted!`b`0";
        }
        apply_buff('stamina-corecombat-exhaustion', array("name" => "Exhaustion", "atkmod" => $buffvalue, "defmod" => $buffvalue, "rounds" => -1, "roundmsg" => $buffmsg, "schema" => "module-staminacorecombat"));
    } else {
        strip_buff('stamina-corecombat-exhaustion');
    }
    $red = get_stamina(0);
    if ($red < 100) {
        $death = e_rand(0, 100);
        if ($death > $red) {
            output("`\$Vision blurring, you succumb to the effects of exhaustion.  You take a step forward to strike your enemy, but instead trip over your own feet.`nAs the carpet of leaves and twigs drifts lazily up to meet your face, you close your eyes and halfheartedly reach out your hands to cushion the blow - but they sail through the ground as if it were made out of clouds.`nYou fall.`nUnconsciousness.  How you'd missed it.`0");
            $session['user']['hitpoints'] = 0;
        }
    }
    return true;
}
function ranksystem_applyrankbuff()
{
    $rank = get_module_pref("rank", "ranksystem");
    switch ($rank) {
        case 1:
            strip_buff('rank');
            break;
        case 2:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 1.1, "badguydefmod" => 1.1, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 3:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 1.25, "badguydefmod" => 1.25, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 4:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 1.5, "badguydefmod" => 1.5, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 5:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 2, "badguydefmod" => 2, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 6:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 4, "badguydefmod" => 4, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 7:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 10, "badguydefmod" => 10, "survivenewday" => 1, "schema" => "module-rank"));
            break;
        case 8:
            apply_buff('rank', array("rounds" => -1, "badguyatkmod" => 25, "badguydefmod" => 25, "survivenewday" => 1, "schema" => "module-rank"));
            break;
    }
}
function heidi_run()
{
    global $session;
    $op = httpget("op");
    $addgold = get_module_pref("addgold");
    $addgold *= round(min(1, $session['user']['dragonkills']) * max(1, $session['user']['dragonkills'] * 0.5 / $session['user']['maxhitpoints']));
    $addgold -= max(1000, $session['user']['maxhitpoints']);
    if ($addgold <= 0) {
        $addgold = 10 * $session['user']['level'];
    }
    $pvpchange = get_module_pref("pvpchange");
    $changeallowed = get_module_setting("changeallowed");
    $allowgift = get_module_setting("allowgift");
    $allowdp = get_module_setting("allowdp");
    $turnadd = get_module_setting("turnadd");
    $turnmult = get_module_setting("turnmult");
    $newdayturns = get_module_pref("newdayturns");
    $turngain = ceil($newdayturns * $turnmult / 100) + $turnadd;
    $gemspaid = get_module_pref("gemspaid");
    $dk = $session['user']['dragonkills'];
    page_header("Heidi's Place");
    villagenav();
    output("`&`c`bHeidi, the Well-wisher`b`c`n");
    if ($changeallowed) {
        addnav("Burn Blue Candle - lose 1 PvP", "runmodule.php?module=heidi&op=blue");
    }
    if ($allowdp && $session['user']['dragonkills'] > 10) {
        addnav("O?Ask about the Orange candles", "runmodule.php?module=heidi&op=orange");
    }
    if ($allowgift) {
        addnav(array("Make a Donation - %s gold", $addgold), "runmodule.php?module=heidi&op=give");
    }
    modulehook("heidi-start", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    if ($op == "") {
        output("`7You step into Heidi's small hut, gazing around at the multitude of colored candles that flicker from the shelves on every wall.`n`n");
        output("`7After a moment you are greeted by a pleasant-looking felyne with a smile on her face.`n`n");
        output("\"`&It is so lovely to see you, %s!", $session['user']['name']);
        output("`&Welcome, then, and reflect on the beauty of the well.`7\"`n`n");
        output("`7A small fountain trickles into what looks more like a pool than a well.");
        output("`7As Heidi whistles softly, crystals in the bottom of the pool begin to glow, eventually forming the numbers: %s.`n`n", $addgold);
        output("`7\"`&Perhaps ye have come to give! Or to burn a candle for a spell?`7\"");
    } elseif ($op == "give" && $session['user']['gold'] < $addgold && $allowgift) {
        // you don't have enough money.
        output("`7Heidi eyes you with concern.`n`n");
        output("\"`&Child, ye be trying to give, when ye have not the affluence to give.`7`n`n");
        output("`&Take comfort, for the mother sees inside thy heart today.`7\"`n`n");
        output("You're not so sure you understand who this mother is, but you realize that you haven't enough gold to donate what the well requests, and so you leave quietly.`n`n");
    } elseif ($op == "give" && $allowgift) {
        output("`7You lean forward, and place %s gold into the well.`n`n", $addgold);
        output("Heidi concentrates on a small candle for several moments, whispering words you cannot understand.`n`n");
        output("\"`&Somewhere, come the morning fair, someone less fortunate shall wake up with a gift of gold.`7`n`n");
        output("`&The pleasure in giving, be within you today!`7\" she exclaims.`n`n");
        debuglog("gave {$addgold} gold as an anonymous gift to someone less fortunate.");
        $session['user']['gold'] -= $addgold;
        apply_buff('heidi', array("name" => "`QUnselfishness`0", "rounds" => 15, "defmod" => 1.05, "survivenewday" => 1, "roundmsg" => "`QGiving to others makes you feel empowered.`0", "schema" => "module-heidi"));
    } elseif ($op == "orange") {
        output("`7Heidi smiles and motions to the small box of orange candles on a shelf nearby.`n`n");
        output("\"`&Orange is the color of change!");
        output("What's done in life is done, but we can mend bridges if we wish to make the change in ourselves.`7\"`n`n");
        if (!get_module_pref("pendingdp")) {
            output("`7For a cost of %s gems, you will be able to rechoose your dragon point allocation after new day.`n`n", $dk);
        }
        $gemsremain = $dk - $gemspaid;
        if (get_module_pref("pendingdp")) {
            output("`7Heidi looks at you deeply for a moment and then smiles tenderly, \"`&Child, child, you must give time for the past changes to take effect before trying again.`7\"`n`n");
        } elseif ($session['user']['gems']) {
            addnav("Payment");
            // User has enough to pay in full
            if ($session['user']['gems'] >= $gemsremain) {
                // You can always pay what you still owe if you have it.
                addnav(array("Pay in full (%s %s)", $gemsremain, translate_inline($gemsremain == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt={$gemsremain}");
            }
            // Don't make user pay in full if he doesn't want to
            if ($session['user']['gems'] < $gemsremain) {
                addnav(array("Pay an installment (%s %s)", $session['user']['gems'], translate_inline($session['user']['gems'] == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt=" . $session['user']['gems']);
            }
            if ($gemsremain > 25 && $session['user']['gems'] >= 25) {
                addnav(array("Pay an installment (%s %s)", 25, translate_inline("gems")), "runmodule.php?module=heidi&op=orangepay&amt=25");
            }
            // Give some text about the installment
            if ($gemspaid == 0 && ($dk > 25 || $session['user']['gems'] < $gemsremain)) {
                output("`7As your total price is %s gems you might not wish to pay in full immediately, and instead pay in installments.`n`n", $dk);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
            } elseif ($gemspaid) {
                output("`^You have paid %s gems so far and have %s remaining in order to rechoose your dragon points at new day.`n`n", $gemspaid, $gemsremain);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
                output("`\$Additionally, any buffs you have from visiting Tynan will be immediately reset.  Such is the cost of change.`n`n");
            }
        } else {
            // User doesn't have any gems on him.
            output("`7You don't have enough gems to pay right now.`n`n");
        }
    } elseif ($op == "orangepay") {
        $amt = httpget("amt");
        $gemspaid += $amt;
        $gemsremain = $dk - $gemspaid;
        set_module_pref("gemspaid", $gemspaid);
        if ($gemsremain) {
            debuglog("Spent {$amt} gems on dp reallocation installment with Heidi. {$gemspaid} spent in total.  {$gemsremain} left to pay.");
        } else {
            debuglog("Spent {$amt} gems to pay remaining amount on dp reallocation with Heidi.  {$dk} spent total.");
        }
        $session['user']['gems'] -= $amt;
        if ($gemsremain) {
            output("`7Heidi thanks you for the gems and reminds you that you have now paid %s of the %s total gems you owe.`n`n", $gemspaid, $dk);
        } else {
            output("`7Heidi thanks you for the payment and smiles.");
            output("She takes a small, orange candle, lights it and places it in a small silver holder, before whispering words that seem foreign to your ears.");
            output("She finally opens her eyes and reminds you that you will be able to rechoose your dragon point allocation at new day.`n`n");
            set_module_pref("gemspaid", 0);
            $hpcount = 0;
            $atcount = 0;
            $defcount = 0;
            reset($session['user']['dragonpoints']);
            while (list($key, $val) = each($session['user']['dragonpoints'])) {
                if ($val == "hp") {
                    $hpcount += 5;
                }
                if ($val == "at") {
                    $atcount++;
                }
                if ($val == "de") {
                    $defcount++;
                }
            }
            restore_buff_fields();
            $session['user']['maxhitpoints'] -= $hpcount;
            $session['user']['hitpoints'] -= $hpcount;
            $session['user']['attack'] -= $atcount;
            $session['user']['defense'] -= $defcount;
            set_module_pref("attack", 0, "tynan");
            set_module_pref("defense", 0, "tynan");
            set_module_pref("hitpoints", 0, "tynan");
            strip_buff("tynanSTAT");
            if ($session['user']['hitpoints'] <= 1) {
                $session['user']['hitpoints'] = 1;
            }
            // call the reset hook before we wipe the array just in case
            // something cares!
            modulehook("dkpointspentreset");
            $session['user']['dragonpoints'] = array();
            set_module_pref("pendingdp", 1);
            calculate_buff_fields();
        }
    } elseif ($session['user']['playerfights'] == 0 || $pvpchange >= $changeallowed) {
        // you have no PvP left today or have already burned the blue
        // enough today
        output("`7Heidi eyes you with a smile.`n`n");
        if ($session['user']['playerfights'] == 0) {
            output("\"`&'Tis all very well to want peace, when one has none extra to give!`7\"`n`n");
        } else {
            // No more burning allowed today.
            output("\"`&Your desire for peace is noble, but is misplaced at this time.`7\"`n`n");
        }
        output("\"`&Perhaps tomorrow ye will come to see me, before ye slay your enemies in fury?`7\"`n`n");
    } else {
        output("`7Heidi takes a small, sky-blue candle, lights it and places it in a small silver holder.");
        output("She regards you with a smile.`n`n");
        output("\"`&Your gesture of kindness to your fellow beings shall reward you.");
        output("Go in peace, warrior.`7\"`n`n");
        output("`6You `@gain`6 %s turns!`n`n", $turngain);
        $session['user']['turns'] += $turngain;
        $session['user']['playerfights']--;
        $pvpchange++;
        set_module_pref("pvpchange", $pvpchange);
        debuglog("exchanged one PvP fight for {$turngain} forest fights.");
        $newdayturns *= 0.75;
        // second and subsequent burns have lower benefit
        set_module_pref("newdayturns", $newdayturns);
    }
    modulehook("heidi-end", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    page_footer();
}
function implantspatialawareness_dohook($hookname, $args)
{
    global $session, $resline;
    $spec = "SA";
    $name = "Spatial Awareness";
    $ccode = "`Q";
    switch ($hookname) {
        case "dragonkill":
            set_module_pref("uses", 0);
            set_module_pref("skill", 0);
            break;
        case "choose-specialty":
            if ($session['user']['specialty'] == "" || $session['user']['specialty'] == '0') {
                addnav("{$ccode}{$name}`0", "newday.php?setspecialty={$spec}{$resline}");
                output("`5\"This, here, is a `QSpatial Awareness`5 implant.  As you grow in strength and combat efficacy, you'll learn how to use it in combination with your own heightened senses.  This Implant works just like the old Season One implants, if that means anything to you.  It's a very simple Implant, good for beginners.  It's only good for combat use.\"`n`n");
            }
            break;
        case "set-specialty":
            if ($session['user']['specialty'] == $spec) {
                page_header($name);
                output("`QInside your head is a tiny microcontroller that heightens your perception in combat.  It has a limited battery charge, but will recharge itself overnight.  As you level up in your combat skills, you'll unlock new abilities.`n`nRemember, this Implant doesn't do anything on its own, but complements your existing combat skill, so levelling up is the only way to make it more effective.");
            }
            break;
        case "specialtycolor":
            $args[$spec] = $ccode;
            break;
        case "specialtynames":
            $args[$spec] = translate_inline($name);
            break;
        case "specialtymodules":
            $args[$spec] = "implantspatialawareness";
            break;
        case "incrementspecialty":
            if ($session['user']['specialty'] == $spec) {
                $new = get_module_pref("skill") + 1;
                set_module_pref("skill", $new);
                $c = $args['color'];
                $name = translate_inline($name);
                output("`n%sYou gain a level in `&%s%s to `#%s%s!", $c, $name, $c, $new, $c);
                $x = $new % 3;
                if ($x == 0) {
                    output("`n`^You gain an extra use point!`n");
                    set_module_pref("uses", get_module_pref("uses") + 1);
                } else {
                    if (3 - $x == 1) {
                        output("`n`^Only 1 more skill level until you gain an extra use point!`n");
                    } else {
                        output("`n`^Only %s more skill levels until you gain an extra use point!`n", 3 - $x);
                    }
                }
                output_notl("`0");
            }
            break;
        case "newday":
            $bonus = getsetting("specialtybonus", 1);
            if ($session['user']['specialty'] == $spec) {
                $name = translate_inline($name);
                if ($bonus == 1) {
                    output("`n`2For having the %s%s`2 implant, you receive `^1`2 extra %s%s`2 use for today.`n", $ccode, $name, $ccode, $name);
                } else {
                    output("`n`2For having the %s%s`2 implant, you receive `^%s`2 extra %s%s`2 uses for today.`n", $ccode, $name, $bonus, $ccode, $name);
                }
            }
            $amt = (int) (get_module_pref("skill") / 3);
            if ($session['user']['specialty'] == $spec) {
                $amt = $amt + $bonus;
            }
            set_module_pref("uses", $amt);
            break;
        case "fightnav-specialties":
            $uses = get_module_pref("uses");
            $script = $args['script'];
            if ($uses > 0) {
                addnav(array("{$ccode}{$name} (%s points)`0", $uses), "");
                addnav(array("{$ccode} &#149; Requisition Search`7 (%s)`0", 1), $script . "op=fight&skill={$spec}&l=1", true);
            }
            if ($uses > 1) {
                addnav(array("{$ccode} &#149; Pressure Points`7 (%s)`0", 2), $script . "op=fight&skill={$spec}&l=2", true);
            }
            if ($uses > 2) {
                addnav(array("{$ccode} &#149; Nimble`7 (%s)`0", 3), $script . "op=fight&skill={$spec}&l=3", true);
            }
            if ($uses > 4) {
                addnav(array("{$ccode} &#149; StandStill`7 (%s)`0", 5), $script . "op=fight&skill={$spec}&l=5", true);
            }
            break;
        case "battle-victory":
            $name = "SA1";
            if (has_buff($name)) {
                $x = 10;
                $y = 40;
                $amount = e_rand($x, $y);
                $amount = $amount * $session['user']['level'];
                output("`Q`nUsing your powers of Spatial Awareness, you find an additional `^%s Requisition`Q dropped by less perceptive players!`0`n", $amount);
                $session['user']['gold'] += $amount;
                strip_buff($name);
            }
            break;
        case "apply-specialties":
            $skill = httpget('skill');
            $l = httpget('l');
            if ($skill == $spec) {
                if (get_module_pref("uses") >= $l) {
                    switch ($l) {
                        case 1:
                            apply_buff('SA1', array("startmsg" => "`QYou ramp up your awareness of your surroundings.  You notice all the coins that other contestants have left lying beneath leaves, under logs, all over the area.  You resolve to pick them up, just as soon as you've dispatched this foe...", "name" => "Requisition Search", "rounds" => -1, "schema" => "module-implantspatialawareness"));
                            break;
                        case 2:
                            apply_buff('SA2', array("startmsg" => "`QYou step back, parrying your enemy's furious thrusts, and take a second or two to look it up and down, locating its weakest points...", "name" => "`QPressure Points", "rounds" => 10, "wearoff" => "`QYour concentration fades, and your knowledge of {badguy}'s pressure points seems to fade away.", "atkmod" => 1.2, "roundmsg" => "`QYou strike {badguy} directly on a vital pressure point, causing serious damage!", "schema" => "module-implantspatialawareness"));
                            break;
                        case 3:
                            apply_buff('SA3', array("startmsg" => "`QYou breathe deeply, concentrate, plan a course of action that will leave your foe bewildered and unable to strike, and begin to move your feet...", "name" => "`QNimble", "rounds" => 10, "defmod" => 1.4, "roundmsg" => "`QYou move so fast that {badguy} can only land glancing blows!", "wearoff" => "`QYour body can no longer keep up with your mind - you're exhausted, and your Nimbleness wears off.", "schema" => "module-implantspatialawareness"));
                            break;
                        case 5:
                            apply_buff('SA5', array("startmsg" => "`QYou stop, meditate for a moment, and open your eyes.  {badguy} is running towards you, so slowly that it's like your foe is running through oil.  You smile, and launch attack after attack while time is slowed down.", "name" => "`QStandStill", "rounds" => 1, "minioncount" => round(e_rand(5, 10)), "minbadguydamage" => "round(<attack>*0.5,0);", "maxbadguydamage" => "round(<attack>,0);", "effectmsg" => "`QYou take advantage of your speeded-up state to attack {badguy}`Q again, causing a further `^{damage} `Qdamage!", "wearoff" => "`QYour concentration fades; {badguy} seems to speed up again, and lunges at you.", "schema" => "module-implantspatialawareness"));
                            break;
                    }
                    set_module_pref("uses", get_module_pref("uses") - $l);
                } else {
                    apply_buff('SA0', array("startmsg" => "Exhausted, you try to bluff.  'I can kill you with my mind,' you call out in what you hope is a sinister voice.  {badguy} looks at you for a minute, thinking, then shrugs.  Laughing, it swings at you again.", "rounds" => 1, "schema" => "module-implantspatialawareness"));
                }
            }
            break;
    }
    return $args;
}
function mysticalshop_buffs_stripbuff()
{
    if (get_module_pref("ring", "mysticalshop") == 0) {
        $id = get_module_pref("ringid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("amulet", "mysticalshop") == 0) {
        $id = get_module_pref("amuletid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("weapon", "mysticalshop") == 0) {
        $id = get_module_pref("weaponid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("armor", "mysticalshop") == 0) {
        $id = get_module_pref("armorid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("cloak", "mysticalshop") == 0) {
        $id = get_module_pref("cloakid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("glove", "mysticalshop") == 0) {
        $id = get_module_pref("gloveid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("boots", "mysticalshop") == 0) {
        $id = get_module_pref("bootid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("misc", "mysticalshop") == 0) {
        $id = get_module_pref("miscid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
    if (get_module_pref("helm", "mysticalshop") == 0) {
        $id = get_module_pref("helmid", "mysticalshop");
        $sql = "SELECT buffid FROM " . db_prefix("magicitems") . " WHERE id={$id}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $buffid = $row['buffid'];
        if ($buffid > 0) {
            strip_buff("mystical-{$buffid}");
        }
    }
}
function get_effect($item = false, $noeffecttext = "", $giveoutput = true)
{
    global $session;
    tlschema("inventory");
    $out = array();
    if ($item === false) {
        if ($noeffecttext == "") {
            $args = modulehook("item-noeffect", array("msg" => "`&Nothing happens.`n", "item" => $item));
            $out[] = sprintf_translate($args['msg']);
        } else {
            $out[] = sprintf_translate($noeffecttext);
        }
    } else {
        eval($item['execvalue']);
        if (isset($hitpoints) && $hitpoints != 0) {
            if (!isset($override_maxhitpoints)) {
                $override_maxhitpoints = false;
            }
            if ($hitpoints > 0) {
                if ($session['user']['hitpoints'] >= $session['user']['maxhitpoints'] && $override_maxhitpoints == false) {
                } else {
                    if ($session['user']['hitpoints'] + $hitpoints > $session['user']['maxhitpoints'] && $override_maxhitpoints == false) {
                        $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                        $out[] = sprintf_translate("`^Your hitpoints have been `@fully`^ restored.`n");
                    } else {
                        if ($override_maxhitpoints == false) {
                            $hitpoints = min($session['user']['maxhitpoints'] - $session['user']['hitpoints'], $hitpoints);
                        }
                        if ($hitpoints > 0) {
                            $session['user']['hitpoints'] += $hitpoints;
                            $out[] = sprintf_translate("`^You have been `@healed`^ for %s points.`n", $hitpoints);
                        }
                    }
                }
            } else {
                if ($hitpoints < 0) {
                    if ($session['user']['hitpoints'] + $hitpoints > 0) {
                        output("`^You `4loose`^ %s hitpoints.", abs($hitpoints));
                        $session['user']['hitpoints'] += $hitpoints;
                    } else {
                        if (!$killable) {
                            $session['user']['hitpoints'] = 1;
                            $out[] = sprintf_translate("`^You were `\$almost`^ killed.`n");
                        } else {
                            $experience = -$killable / 100;
                            $session['user']['hitpoints'] = 0;
                            $session['user']['alive'] = 0;
                            $out[] = sprintf_translate("`\$You die.`n");
                        }
                    }
                }
            }
        }
        if (isset($turns) && $turns != 0) {
            $session['user']['turns'] += $turns;
            debuglog("'s turns were altered by {$turns} by item {$item['itemid']}.");
            if ($turns > 0) {
                if ($turns == 1) {
                    $out[] = sprintf_translate("`^You `@gain`^ one turn.`n");
                } else {
                    $out[] = sprintf_translate("`^You `@gain`^ %s turns.`n", $turns);
                }
            } else {
                if ($session['user']['turns'] <= 0) {
                    $out[] = sprintf_translate("`^You `\$lose`^ all your turns.`n");
                    $session['user']['turns'] = 0;
                } else {
                    if ($turns == -1) {
                        $out[] = sprintf_translate("`^You `\$lose`^ one turn.`n");
                    } else {
                        $out[] = sprintf_translate("`^You `\$lose`^ %s turns.`n", abs($turns));
                    }
                }
            }
        }
        if (isset($attack) && $attack != 0) {
            $session['user']['attack'] += $attack;
            debuglog("'s attack was altered by {$attack} by item {$item['itemid']}.");
            if ($attack > 0) {
                $out[] = sprintf_translate("`^Your attack is `@increased`^ by %s.`n", $attack);
            } else {
                if ($session['user']['attack'] <= 1) {
                    $out[] = sprintf_translate("`^You `\$lose`^ all your attack except the strength of your bare fists.`n");
                    $session['user']['attack'] = 1;
                } else {
                    $out[] = sprintf_translate("`^Your attack is `\$decreased`^ by %s.`n", abs($attack));
                }
            }
        }
        if (isset($defense) && $defense != 0) {
            $session['user']['defense'] += $defense;
            debuglog("'s defense was altered by {$defense} by item {$item['itemid']}.");
            if ($defense > 0) {
                $out[] = sprintf_translate("`^Your defense is `@increased`^ by %s.`n", $defense);
            } else {
                if ($session['user']['defense'] <= 1) {
                    $out[] = sprintf_translate("`^You `\$lose`^ all your defense except the durability of your everpresent T-Shirt.`n");
                    $session['user']['defense'] = 1;
                } else {
                    $out[] = sprintf_translate("`^Your defense is `\$decreased`^ by %s.`n", abs($defense));
                }
            }
        }
        if (isset($charm) && $charm != 0) {
            $session['user']['charm'] += $turns;
            if ($charm > 0) {
                $out[] = sprintf_translate("`^Your charm is `@increased`^ by %s.`n", $charm);
            } else {
                if ($session['user']['charm'] <= 0) {
                    $out[] = sprintf_translate("`^You `\$lose`^ all your charm.`n");
                    $session['user']['charm'] = 0;
                } else {
                    $out[] = sprintf_translate("`^Your charm is `\$decreased`^ by %s.`n", abs($charm));
                }
            }
        }
        if (isset($maxhitpoints) && $maxhitpoints != 0) {
            if ($maxhitpoints > 0) {
                $session['user']['maxhitpoints'] += $maxhitpoints;
                $out[] = sprintf_translate("`^Your maximum hitpoints are permanently `@increased`^ by %s.`n", $maxhitpoints);
            } else {
                reset($session['user']['dragonpoints']);
                $hp = 0;
                while (list($key, $val) = each($session['user']['dragonpoints'])) {
                    if ($val == "hp") {
                        $dkhp++;
                    }
                }
                $minhp = $session['user']['level'] * 10 + $hp * 5;
                if ($session['user']['maxhitpoints'] + $maxhitpoints < $minhp) {
                    $maxhitpoints = $session['user']['maxhitpoints'] - $minhp;
                }
                if ($maxhitpoints < 0) {
                    $out[] = sprintf_translate("`^Your maximum hitpoints are permanently `\$decreased`^ by %s.`n", abs($maxhitpoints));
                    $session['user']['maxhitpoints'] += $maxhitpoints;
                }
            }
        }
        if (isset($uses)) {
            $modules = modulehook("specialtymodules");
            $names = modulehook("specialtynames");
            if (is_array($uses)) {
                while (list($key, $val) = each($uses)) {
                    if ($val > 0) {
                        if ($val == 1) {
                            $out[] = sprintf_translate("`^You `@gain`^ one point in %s.`n", $val, $names[$key]);
                        } else {
                            $out[] = sprintf_translate("`^You `@gain`^ %s points in %s.`n", $val, $names[$key]);
                        }
                    } else {
                        $val = min(abs($val), get_module_pref("uses", $modules[$key]));
                        if ($val == 1) {
                            $out[] = sprintf_translate("`^You `\$lose`^ one point in %s.`n", $val, $names[$key]);
                        } else {
                            $out[] = sprintf_translate("`^You `\$lose`^ %s points in %s.`n", $val, $names[$key]);
                        }
                        $val *= -1;
                    }
                    increment_module_pref("uses", $val, $modules[$key]);
                }
            } else {
                if ($uses == 'looseall') {
                    while (list($key, $val) = each($modules)) {
                        set_module_pref("uses", 0, $val);
                    }
                    $out[] = "`^You `\$lose all`^ uses in `\$all`^ specialties.`n";
                } else {
                    if (is_numeric($uses) && $uses > 0 && $session['user']['specialty'] != "") {
                        increment_module_pref("uses", $uses, $modules[$session['user']['specialty']]);
                        $out[] = sprintf_translate("`^You `@gain`^ %s points in %s.`n", $uses, $names[$session['user']['specialty']]);
                    } else {
                        if (is_numeric($uses) && $session['user']['specialty'] != "") {
                            $out[] = sprintf_translate("`^You `\$lose`^ %s points in %s.`n", $uses, $names[$key]);
                        }
                    }
                }
            }
        }
        if (isset($increment_specialty) && $increment_specialty > 0) {
            require_once "lib/increment_specialty.php";
            while ($increment_specialty) {
                increment_specialty("`^");
                $increment_specialty--;
            }
            $giveoutput = false;
        }
        if (isset($gems) && $gems != 0) {
            $session['user']['gems'] += $gems;
            debuglog("'s gems were altered by {$gems} by item {$item['itemid']}.");
            if ($gems > 0) {
                if ($gems == 1) {
                    $out[] = sprintf_translate("`^You `@gain`^ one gem.`n");
                } else {
                    $out[] = sprintf_translate("`^You `@gain`^ %s gems.`n", $gems);
                }
            } else {
                $gems = min(abs($gems), $session['user']['gems']);
                if ($gems == 1) {
                    $out[] = sprintf_translate("`^You `\$lose`^ one gem.`n", $gems);
                } else {
                    $out[] = sprintf_translate("`^You `\$lose`^ %s gems.`n", $gems);
                }
            }
        }
        if (isset($gold) && $gold != 0) {
            $session['user']['gold'] += $gold;
            debuglog("'s gold were altered by {$gold} by item {$item['itemid']}.");
            if ($gold > 0) {
                $out[] = sprintf_translate("`^You `@gain`^ %s gold.`n", $gold);
            } else {
                $gold = min(abs($gold), $session['user']['gold']);
                $out[] = sprintf_translate("`^You `\$lose`^ %s gold.`n", $gold);
            }
        }
        if (isset($experience) && $experience != 0) {
            if (is_float($experience)) {
                $bonus = round($session['user']['experience'] * $experience, 0);
            } else {
                $bonus = $experience;
            }
            $session['user']['experience'] += $experience;
            debuglog("'s experience was altered by {$bonus} by item {$item['itemid']}.");
            if ($bonus > 0) {
                $out[] = sprintf_translate("`^You `@gain`^ %s experience.`n", $bonus);
            } else {
                $bonus = min(abs($bonus), $session['user']['experience']);
                $out[] = sprintf_translate("`^You `\$lose`^ %s experience.`n", $bonus);
            }
        }
        if (isset($deathpower) && $deathpower != 0) {
            $session['user']['deathpower'] += $deathpower;
            if ($deathpower > 0) {
                $out[] = sprintf_translate("`^You `@gain`^ %s favor with `\$Ramius`0.`n", $deathpower);
            } else {
                $deathpower = min(abs($deathpower), $session['user']['deathpower']);
                $out[] = sprintf_translate("`^You `\$lose`^ %s favor with `\$Ramius`0.`n", $deathpower);
            }
        }
        if (isset($gravefights) && $gravefights != 0) {
            $session['user']['gravefights'] += $gravefights;
            if ($gravefights > 0) {
                $out[] = sprintf_translate("`^You `@gain`^ %s gravefights.`n", $gravefights);
            } else {
                $deathpower = min(abs($gravefights), $session['user']['gravefights']);
                $out[] = sprintf_translate("`^You `\$lose`^ %s gravefights.`n", $gravefights);
            }
        }
        if (isset($extraflirt) && is_module_active("lovers") && $extraflirt == true && get_module_pref("seenlover", "lovers")) {
            set_module_pref("seenlover", false, "lovers");
            $him = sprintf_translate("him");
            $her = sprintf_translate("her");
            require_once "lib/partner.php";
            $out[] = sprintf_translate("`^You miss %s`^ and want to see %s again.`n", get_partner(), $session['user']['sex'] ? $him : $her);
        }
        if (isset($extratravel) && is_module_active("cities") && $extratravel != 0) {
            increment_module_pref("traveltoday", -$extratravel, "cities");
            if ($extratravel > 0) {
                $out[] = sprintf_translate("`^You feel `@refreshed`^.");
                $out[] = sprintf_translate("`^You may travel %s times `@more`^ today.`n", $extratravel);
            } else {
                $out[] = sprintf_translate("`^You feel `\$tired`^.");
                $out[] = sprintf_translate("`^You may travel %s times `\$less`^ today.`n", $extratravel);
            }
        }
        if (isset($buff) && is_array($buff)) {
            require_once "lib/buffs.php";
            apply_buff("item-{$item['itemid']}", $buff);
            $out[] = sprintf_translate("`^Something feels strange within your body.`n");
        }
        if (isset($extrabuff) && is_array($extrabuff)) {
            require_once "lib/buffs.php";
            while (list($key, $val) = each($extrabuff)) {
                if (has_buff($key)) {
                    while (list($vkey, $vval) = each($val)) {
                        $session['bufflist'][$key][$vkey] += $vval;
                        $things = true;
                    }
                }
            }
            if ($things) {
                $out[] = sprintf_translate("`^You feel something strange happening.`n");
            }
        }
        if (isset($strip)) {
            require_once "lib/buffs.php";
            if (has_buff($strip)) {
                strip_buff($strip);
                $out[] = sprintf_translate("`^You have a weird feeling.`n");
            }
        }
    }
    foreach ($out as $index => $text) {
        if (is_array($text)) {
            foreach ($text as $sec => $text2) {
                $newout[] = $text2;
            }
        } else {
            $newout[] = $text;
        }
    }
    $args = modulehook("itemeffect", array("out" => $newout, "item" => $item));
    $out = $args['out'];
    if (count($out) == 0) {
        if ($noeffecttext == "") {
            $args = modulehook("item-noeffect", array("msg" => "`&Nothing happens.`n", "item" => $item));
            $out[] = sprintf_translate($args['msg']);
        } else {
            if ($giveoutput) {
                $out[] = sprintf_translate($noeffecttext);
            }
        }
    }
    $effect_text = join($out, "");
    tlschema();
    return $effect_text;
}