function zapgrenade_use($args)
{
    global $session;
    debug("Applying Zap Grenade buff");
    apply_buff('zapgrenade', array("startmsg" => "`3You pull the pin on your grenade and toss it at {badguy}`3, shielding your eyes.  After a blinding flash, your foe is left dazed and confused!", "name" => "`^ZAP Grenade", "rounds" => e_rand(3, 7), "badguyatkmod" => 0.1, "badguydefmod" => 0.1, "roundmsg" => "{badguy} is blinded, deafened and thoroughly confused, and flails wildly while you pummel it!", "wearoff" => "{badguy}`3 feels some coherence return, and lunges at you!", "expireafterfight" => 1, "schema" => "iitems-catcher"));
    return $args;
}
function cakeordeath_run()
{
    global $session;
    page_header("Cake Or Death");
    switch (httpget("op")) {
        case "examine":
            // Tell the player what the deal with Cake Or Death is
            $counter = number_format(get_module_setting("counter"));
            output("`0A shiny wooden table sits back from the main street.  Behind it, a man sits idly reading the Improbable Island Enquirer.  Before him, sat on the table, is a large sponge cake.  Above him is a banner, displaying the name of his game:`b'`5Cake`0 or `4Death!`0'`b`n`nHe sees you pondering the sign, and calls over to you.  `b'`5Cake`0 or `4Death!`0  `b`5Cake`0 or `4Death!`0' he cries.  'Ninety-nine per cent chance of `b`5Cake`0`b!'`n`nIt's not often that an immaculately-dressed gentleman with glowing green eyes offers you a 99% chance of cake.  What would you like to do?");
            //add navs
            addnav("CAKE!", "runmodule.php?module=cakeordeath&op=play");
            addnav("Back away slowly", "village.php");
            break;
        case "play":
            $counter = get_module_setting("counter");
            addnav("Back to the Outpost", "village.php");
            if ($counter > 0) {
                output("The green-eyed gentleman hands you a slice of cake, on a paper plate.  You thank him, and walk away merrily wolfing down your prize.`n`nYou feel `5Full Of Cake!`0");
                set_module_setting("counter", get_module_setting("counter") - 1);
                apply_buff('tastycake', array("name" => "`5Full Of Cake`0", "rounds" => 10, "atkmod" => 1.1, "defmod" => 1.1, "roundmsg" => "`5The cake you ate earlier has boosted your energy!`n", "schema" => "module-cakeordeath"));
            }
            if ($counter <= 0) {
                output("The green-eyed gentleman hands you a slice of cake, on a paper plate.  You thank him, and walk away merrily wolfing down your prize.`n`nYou feel `5Full Of Cake!`0`n`nMoments later, the slow-acting poison starts to take effect.  The world begins to melt in front of you.  Grey spots dance on the edges of your vision.  Behind you, a green-eyed monster offers you another slice of cake, laughing and pointing.`n`nYou curse your luck as the hallucinations begin to kick in.");
                set_module_setting("counter", 100);
                apply_buff('failcake', array("name" => "`5Full Of FailCake`0", "rounds" => -1, "regen" => -10, "startmsg" => "`5You are walking on pink icing.  The sky is made of jam.  Your eyes are two cherries.  That cake was awesome.`0`n", "roundmsg" => "`5The poisoned cake saps your strength, and you lose ten hitpoints!`0`n", "schema" => "module-cakeordeath"));
                if (is_module_active("medals")) {
                    require_once "modules/medals.php";
                    medals_award_medal("failcake", "Failcake Fancier", "This player was unfortunate at the Cake or Death stand...", "medal_failcake.png");
                }
            }
            break;
    }
    page_footer();
}
function nicotinegum_use($args)
{
    $addiction = get_module_pref("addiction", "smoking");
    $betweensmokes = 250 - $addiction;
    set_module_pref("betweensmokes", $betweensmokes, "smoking");
    apply_buff("smoking", array("allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-smoking"));
    return $args;
}
function pub_newpittsburgh_drinks_dohook($hookname, $args)
{
    global $session;
    $drinks = array("brainhem" => array("price" => 35, "verbosename" => "Brain Hemorrhage"), "monstermash" => array("price" => 50, "verbosename" => "Monster Mash"), "specialsauce" => array("price" => 65, "verbosename" => "Special Sauce"));
    switch ($hookname) {
        case "pub_newpittsburgh_bartender":
            if ($session['user']['race'] == "Robot") {
                if ($session['user']['sex']) {
                    $lovelad = "lad";
                } else {
                    $lovelad = "love";
                }
                $args['text']['hello'] = "George looks you up and down, eyes sliding over your smooth glass skin.  \"`2You're a Robot, aren't you, " . $lovelad . "?`0\"`n`n\"`#That I am.  Are you going to tell me that you don't serve my type in here?`0\"`n`n\"`2On the contrary, Chuck, we'd be `ivery`i pleased to cater to our Robot customers, but we just don't have the power, y'see.  Setting up one of those fancy lamps just takes more amps than our genny can kick out.  You ask most of the pubs on the Island, it's the same way.`0\"`n`n\"`#I see.`0\"`n`n\"`2We've got games, though.  And telly.  You're more than welcome here, it's just...`0\" he shrugs his shoulders and spreads his hands.  \"`2I don't have anything to sell you that you'd want to buy.`0\"`n`n`#Fair enough`0, you suppose.";
            } else {
                $args['drinks'] = $drinks;
            }
            break;
        case "pub_newpittsburgh_drink":
            $drink = httpget("drink");
            switch ($drink) {
                case "brainhem":
                    $session['user']['gold'] -= 35;
                    output("\"`2All right Chuck,`0\" says George, bringing up a jar of pickled brains.  They look far too small to be human, even pickled - perhaps the size of rabbit brains.  The wrinkled grey things bob peacefully around as George carefully pours a measure of the fluid into a shot glass with the help of a funnel.`n`nThe liquid smells a lot like embalming fluid.`n`nTastes like it, too, albeit with a nice alcoholic glow.`n`n");
                    output("You feel `2Energetic!`0`n`n");
                    apply_buff('pub_newpittsburgh_brainhem', array("name" => "`2Brain Hemorrhage Fuzzies", "rounds" => 15, "defmod" => 1.12, "roundmsg" => "Thanks to your Brain Hemorrhage Fuzzies, your defensive movements are more fluid!", "wearoff" => "You feel the effects of the Brain Hemorrhage fade away.", "schema" => "pub_newpittsburgh"));
                    //require_once "modules/staminasystem/lib/lib.php";
                    //addstamina(5000);
                    break;
                case "monstermash":
                    $session['user']['gold'] -= 50;
                    output("George hands you a tall glass filled with artfully-swirled monster grey matter, garnished with a jolly little paper umbrella and a slice of brainstem.`n`n");
                    if ($session['user']['race'] != "Zombie") {
                        output("You take a sip.  It's... honestly, it's awful.  It tastes like a mix of chicken and beef fat, raw eggs, and blood.  Lots of blood.  Not meaning to be impolite you knock the glass back quickly, trying to ignore the cold, semi-solid lumps slowly sliding over your tongue and curling down your throat.`n`n");
                        output("You feel `4Sick and Grumpy!`0`n`n");
                        apply_buff('pub_newpittsburgh_monstermash', array("name" => "`2Monster Mash Grumps", "rounds" => 25, "atkmod" => 1.2, "roundmsg" => "`4The awful Zombie drink makes you feel `\$aggressive!", "wearoff" => "`4You feel the effects of the Monster Mash fade away.  Thank goodness for that.", "schema" => "pub_newpittsburgh"));
                        //require_once "modules/staminasystem/lib/lib.php";
                        //addstamina(5000);
                    } else {
                        output("You down the contents and lick your lips.`n`n");
                        output("You feel `2Energetic!`0`n`n");
                        //require_once "modules/staminasystem/lib/lib.php";
                        //addstamina(10000);
                        increment_module_pref("nutrition", 5, "staminafood");
                        apply_buff('pub_newpittsburgh_monstermash', array("name" => "`2Monster Mash", "rounds" => 25, "atkmod" => 1.2, "defmod" => 1.1, "roundmsg" => "`2The Monster Mash burns warmly in your stomach.  Both your attack and defence are increased!", "wearoff" => "`2The Monster Mash warmth has faded.  Oh well.", "schema" => "pub_newpittsburgh"));
                    }
                    break;
                case "specialsauce":
                    $session['user']['gold'] -= 65;
                    output("George pours you a short glass full of something from a thick blue bottle.  It's the only thing on the menu that doesn't mention brains, though you wonder if the odd blue liquid wasn't distilled from them.  It smells vaguely of formaldehyde, but has enough of a tongue-numbing alcoholic kick that you don't regret ordering it.`n`n");
                    output("You feel `2Warm!`0`n`n");
                    apply_buff('pub_newpittsburgh_specialsauce', array("name" => "`2Special Sauce Warmth", "rounds" => 30, "defmod" => 1.25, "atkmod" => 1.25, "roundmsg" => "That Zombie drink was awesome!  It's like time's slowed down!", "wearoff" => "You feel the effects of the Special Sauce fade away.", "schema" => "pub_newpittsburgh"));
                    break;
            }
            break;
    }
    return $args;
}
function monsterrepellentspray_use($args)
{
    global $session;
    if ($args['context'] == "fight") {
        apply_buff('rspray_fight', array("startmsg" => "`#You pull out a can of Monster Repellent Spray, and spray it liberally on the enemy!`n", "name" => "`^Repellent Spray Attack", "rounds" => 10, "badguyatkmod" => 0.4, "badguydefmod" => 0.4, "roundmsg" => "{badguy} is coughing, choking and all runny-nosed, and cannot attack or defend as effectively!", "wearoff" => "The effects of your Monster Repellent Spray seem to have worn off...`n", "expireafterfight" => 1, "schema" => "iitems-catcher"));
    } else {
        apply_buff('rspray_normal', array("name" => "`^Repellent Spray", "rounds" => -1, "badguyatkmod" => 0.8, "badguydefmod" => 0.8, "roundmsg" => "{badguy} can't stand the smell of your Monster Repellent Spray, and doesn't want to get too close!", "schema" => "iitems-catcher"));
        set_item_pref("encounterchance", 50, "worldmapen");
        output("You liberally douse yourself with an entire can of Monster Repellent Spray.  For the rest of this game day, your chances of encountering a monster on the Island Map have been halved, and monsters you do encounter will be reluctant to attack you as hard.`n`n");
    }
    return $args;
}
function improbabilitybomb_use($args)
{
    global $session;
    $effect = e_rand(1, 8);
    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" => "improbabilitybomb"));
    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" => "improbabilitybomb"));
            $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" => "improbabilitybomb"));
            $session['user']['gems']++;
            break;
        case 3:
        case 4:
            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" => "improbabilitybomb"));
            break;
        case 5:
            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" => "improbabilitybomb"));
            $session['user']['charm'] += 1;
            break;
        case 6:
            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" => "improbabilitybomb", "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" => "improbabilitybomb", "wearoff" => "The bomb fizzles out and sends out one last dying volley of sparks.", "expireafterfight" => 1));
            break;
        case 7:
            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" => "improbabilitybomb", "wearoff" => "`5The Purple Monster, seeing its business here concluded, disappears with a faint 'pop.'`0", "expireafterfight" => 1));
            break;
        case 8:
            $maxdmg = $session['user']['maxhitpoints'] * 2;
            if ($maxdmg < 500) {
                $maxdmg = 500;
            }
            $mindmg = $session['user']['hitpoints'] * 0.5;
            if ($maxdmg < 200) {
                $maxdmg = 200;
            }
            apply_buff('ibomb9', array("rounds" => 1, "minioncount" => 1, "mingoodguydamage" => $mindmg, "maxgoodguydamage" => $maxdmg, "effectmsg" => "`4Before the bomb even leaves your hand, it blows up in your face!  The explosion causes {damage} points!", "schema" => "improbabilitybomb", "expireafterfight" => 1));
            break;
    }
    return $args;
}
function pub_kittania_drinks_dohook($hookname, $args)
{
    global $session;
    $drinks = array("cider" => array("price" => 25, "verbosename" => "Vegetable Cider"), "tiggerbalm" => array("price" => 40, "verbosename" => "Tigger Balm"));
    switch ($hookname) {
        case "pub_kittania_bartender":
            if ($session['user']['race'] == "Robot") {
                $args['text']['hello'] = "Miu-Miu blinks.  \"`2Oh, I'm sorry love - we don't have anything for our, um...`0\" she struggles for a moment.  \"`2Our... organically-challenged - I mean our CPU-enhanced...`0\"`n`n\"`#You can say \"Robot,\" you know.  It's not taboo.`0\"`n`n\"`2Right you are, then,`0\" says Miu-Miu, visibly relieved.  \"`2But we `ihave`i got plenty of sun, and you're welcome to sit by the window if you want to charge yourself up, I suppose.`0\"`n`n\"`#Thank you.  I may take you up on that.`0\"`n`n\"`2Is there anything else I can help you with, love?`0\"`n`n";
            } else {
                $args['drinks'] = $drinks;
            }
            break;
        case "pub_kittania_drink":
            $drink = httpget("drink");
            switch ($drink) {
                case "cider":
                    $session['user']['gold'] -= 25;
                    output("\"`2All right love,`0\" says Miu-Miu, setting down the glass in front of you.  She leans forward and murmurs \"`2D'you want a mouse in that, petal?`0\"`n`n");
                    if ($session['user']['race'] == "KittyMorph") {
                        output("You grin, canines peeking out.  Miu-Miu smiles back before reaching under the counter, bringing up a small white mouse by its tail.`n`nThere were days when the custom would be to play with it for a while before dunking it in the cider, but these are more civilised times.  The mouse struggles for precisely one second, then floats serenely with a cross-eyed grin, tiny bubbles rising from its nose.  You knock back the cider and mouse before the bubbles reach the surface, as is the custom of your people these days.  As the mouse slides down your gullet, you wonder idly if political correctness has gone too far.  It's only a bloody `imouse.`i`n`nThere's a tiny jerk inside your stomach.  You grin at Miu-Miu.  \"`#I love it when they hiccup.`0\"`n`n");
                    } else {
                        output("You give Miu-Miu a long, thoughtful stare.  \"`#`iNo,`i`0\" you say, politely but firmly.`n`n\"`2Fair enough, love, fair enough.  Enjoy.`0\"`n`nThe cider tastes vaguely of apples and grass.`n`n");
                    }
                    output("You feel `2Energetic!`0`n`n");
                    apply_buff('pub_kittania_cider', array("name" => "`2Warm Cider Fuzzies", "rounds" => 15, "defmod" => 1.1, "roundmsg" => "Thanks to your Warm Cider Fuzzies, your defensive movements are more fluid!", "wearoff" => "You feel the effects of the Vegetable Cider fade away.", "schema" => "pub_kittania"));
                    //require_once "modules/staminasystem/lib/lib.php";
                    //addstamina(5000);
                    break;
                case "tiggerbalm":
                    $session['user']['gold'] -= 40;
                    if ($session['user']['race'] != "KittyMorph") {
                        output("Miu-Miu raises an eyebrow and gives you an appraising look, before shrugging and pouring a shot of thick green liquid.  \"`2You look big enough to handle it, so where's the harm, I suppose...  but you want to be careful with that stuff,`0\" she says.  \"`2Strictly speaking I'm only supposed to sell it to `ino don't knock it back in one`i - oh, never mind.`0\"`n`nA dribble of burning, herbal-tasting green fluid runs down your chin.  \"`#Gleeshuck,\"`0 you say, as your left eye slowly rotates towards the ceiling.`n`n");
                        output("You feel `4Violent!`0`n`n");
                        apply_buff('pub_kittania_tiggerbalm', array("name" => "`2Tigger Balm Shakes", "rounds" => 25, "atkmod" => 1.4, "defmod" => 0.8, "roundmsg" => "`4The Tigger Balm Shakes make you feel more `\$aggressive!", "wearoff" => "`4You feel the Tigger Balm Shakes fade away.  Thank goodness for that.", "schema" => "pub_kittania"));
                        //require_once "modules/staminasystem/lib/lib.php";
                        //addstamina(6000);
                    } else {
                        output("You sip gently at the thick, herbal-tasting green fluid.  The fluid is cold, but feels pleasantly warm as it goes down.`n`n");
                        output("You feel `2Energetic!`0`n`n");
                        //require_once "modules/staminasystem/lib/lib.php";
                        //addstamina(7000);
                        apply_buff('pub_kittania_tiggerbalm', array("name" => "`2Tigger Balm Warmth", "rounds" => 25, "atkmod" => 1.2, "defmod" => 1.1, "roundmsg" => "`2The Tigger Balm burns warmly in your stomach.  Both your attack and defence are increased!", "wearoff" => "`2The Tigger Balm warmth has faded.  Oh well.", "schema" => "pub_kittania"));
                    }
                    break;
            }
            break;
    }
    return $args;
}
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 watcher_quests_run()
{
    global $session;
    switch (httpget('plotpoint')) {
        case 1:
            page_header("Meanwhile, somewhere offshore...");
            output("`\$The Watcher`0 is in her control room, and about to boot her computer.  She yawns, setting her cup of tea down on the shelf next to the keyboard.  She takes a seat, puts her foot on the clutch, switches on the heating coils and presses the starter button.`n`nNothing happens.`n`n\"`7Arse,`0\" she mutters, remembering that the starter motor died a couple of days ago.  She takes a brief stroll around to the back of the computer, picking up the six-foot-long iron crank handle as she passes.`n`nWith a total electromechanical equivalent of one hundred and twenty eight kilobytes of memory, starting this three-ton supercomputer by hand requires three strong men, lots of sweat, and language that would make a sailor blush.  `\$The Watcher`0 inserts the crank handle, pushes her glasses up onto the bridge of her nose, grabs the handle, takes a firm stance and gives it a spin.`n`nThe five-litre diesel engine, currently running on used vegetable oil, coughs into life.  Its heavy, thumping compressions send little shockwaves through the floor.  `\$The Watcher`0 pulls out the crank handle, pats the computer's casing, and returns to her seat.`n`nNobody saw her start the machine, either today or yesterday.  She intends to let the technicians know about the broken starter motor, but it keeps slipping her mind.  Probably because people are already noticing little things about her.  People are already talking.  People's smiles already seem a little frozen when they wish her a good morning.  If they knew that she had just started a three-ton supercomputer by hand, the worry in their eyes might turn to naked fear, and her already-shrinking circle of close friends might just shrink a little more.  Of course, she could always lie - just go up to the technicians tomorrow morning, declare that the starter had just broken, and ask the strong tech lads to give a girl a hand.  One more little white lie probably wouldn't hurt.`n`nShe puts her foot on the clutch and wrenches the monitor into gear.  As she slowly lets the clutch up, a mounted arm begins to spin, generating a warm breeze onto `\$The Watcher`0's face.  Arranged in one straight row on the arm are a dozen flickering thumbnail-sized light bulbs.`n`n`\$The Watcher`0 noticed something was wrong about six months ago.  She was lifting herself by her arms on a pull-up bar as part of her morning exercise routine.  Her mind wandered as she listened to the waves crashing outside.  Within ten pull-ups she was remembering the hours she used to spend playing pirates with Paul Stevens, both of them no older than seven or eight.  The radio was announcing the time when she realised she'd been doing pull-ups for over an hour.`n`nAs the mounted arm spins faster and faster, words begin to form in the blur, generated by the rapidly-flickering lamps and `\$The Watcher`0's persistence of vision.  When they converge into a clear picture, `\$The Watcher`0 sets the auto-throttle and takes her foot off the clutch.`n`nEvery day that she remains near the Island, she grows stronger.  Even if she hasn't bothered to exercise, even if she's pushed herself so hard she should have been exhausted.  Even if she's stuffed her face with junk food, even if she's starved herself all day.  No matter what she does, she becomes more powerful with each passing minute.  And with every extra foot-pound of force she can generate, she feels a little more unsure of her own capacity to handle this sort of power - and a little more lonely.`n`nShe laces her fingers together, pushes them outwards with a series of satisfying cracks and pops, and begins to press keys, pull levers, push pedals.  The supercomputer responds with the clatter of a million relays and mechanical sequencers, audible even over the roar of the diesel engine.  Words and numbers appear in the air where the swinging monitor arm now spins at several thousand rotations per minute.`n`nAfter a few minutes, the analysis routine is complete.  One name appears in the list of results.  One contestant who seems to be gaining strength nearly as quickly as `\$The Watcher`0 did herself.  One person who might, perhaps, understand what is happening to `\$The Watcher`0.  One person with whom she could potentially share a secret.`n`n\"`7%s`7... Huh.  Bit of a funny name,`0\" says `\$The Watcher`0 quietly, \"`7but I'll be watching you.`0\"", $session['user']['name']);
            set_module_pref("plotpoint1", 1);
            addnav("Continue");
            addnav("Get on with it", "village.php");
            break;
        case 2:
            page_header("Something Improbable!");
            output("`0As you head into the Outpost, something big and black appears in front of you, moving at speed.  It impacts on your face, knocking you on your back.  As you push yourself up onto your elbows, you try to make sense of what just happened.`n`nYou're not `ientirely`i sure, but you think... as strange as it sounds... it might have been someone's arse.`n`nYou replay the scene - yup.  Someone's arse, in a black skirt.  You only know one person on this Island who wears a black skirt.`n`n`\$The Watcher`0 - or at least, the top half of her - leans out of the air.  Her bespectacled eyes lock onto yours, and her face lights up in a huge grin.  \"`7Hey, it's you!  Well, isn't this a coincidence!`0\"  She reaches out to you.  You extend a hand, ready for her to help you up and, perhaps, explain where her legs are - and why she just beat you to the ground with her now-invisible posterior.`n`nNothing of the sort happens.  Instead, `\$The Watcher`0 expertly steals a cigarette from your pocket, lights it, gives you a cheery wink and leans back, disappearing right before your eyes.`n`nYou lie for a moment, staring at the space she just occupied.`n`n\"`#RIGHT THEN!`0\" you cry, in the vain hope that `\$The Watcher`0 can still hear you.  Birds scatter from the trees.  \"`#So THAT'S the sort of day this is going to be!  OKAY!  Thanks for the heads-up!`0\"  You get to your feet.  \"`#I'll expect to be mugged by a floating pair of boobs any second now!`0\"`n`nA passing contestant looks your way, lip curled up in distaste.  \"`2Weirdo,`0\" she mutters, before continuing on her way.");
            set_module_pref("plotpoint2", 1);
            $session['user']['gems']--;
            addnav("Damn it.");
            addnav("Dust yourself off and head into the Outpost", "village.php");
            break;
        case 3:
            page_header("The Deal with the Turtleneck");
            output("\"`&What?`0\"`n`n\"`#I mean... um.\"  You swallow.  \"`#The turtleneck.  It seems that every time I see you, you're... well, it's the red turtleneck, every time.  I mean... aren't you a bit hot, in that?`0\"`n`n`\$The Watcher`0 frowns at you for a moment.  Then she smiles, sits back in her chair and chuckles softly.  \"`&Well, it's pretty much all marketing, mate.`0\"`n`n\"`#Marketing?`0\"`n`n`\$The Watcher`0 leans forwards, pushing her glasses up onto her nose.  \"`&Well, you see, it's like this.  Since this particular artform was created, women in my line of work have been expected to fall into one of two categories.  We're either useless pansies whose only function is to be kidnapped and then saved by powerful men; or, we're strong, capable warriors with amazing bodies.  But if you go for being strong and capable, you're expected to have a regrettable tendency to wear `ipreposterously`i impractical armour.  Since I didn't think I'd suit the \"useless pansy\" trope, I decided to opt for the latter anyway.`0\"`n`nYou blink.  You open your mouth, then close it again and choose your words carefully, sensing an awkward discussion in your near future - one that would probably, sooner or later, end up revolving around chainmail bikinis.  \"`#...preposterously impractical armour?`0\"`n`n\"`&A calf-length black skirt and a turtleneck?  In `ithis`i weather?`0\"`n`n\"`#Oh.`0\"`n`n\"`&It's a bloody `inylon`i skirt, too.  You wouldn't believe the amount of static electricity this thing generates.  I suppose I could top it all off with a black leather jacket, or a nice knitted scarf, if I wanted to go the whole hog.  But honestly, my heart just isn't in it.`0\"`n`n\"`#Yeah, that would be... yeah.`0\"  Something nags at you.  \"`#You mentioned something... you said \"since this artform was created.\"  Which artform is that, exactly?`0\"`n`n`\$The Watcher`0 frowns.  \"`&Televised post-EMP warfare.`0\"  She laughs.  \"`7What did you `ithink`i I was talking about?`0\"`n`n\"`#Never mind.`0\"`n`n\"`&I draw the line at the boots, though.  You've got to have practical boots.`0\"  She leans back and a pair of steel-toed black leather monoliths clomp onto the desk.  \"`&I mean, technically these are bloke's boots, but I've always had quite broad feet, and I find men's boots tend to hold up better than women's and I'm `ibabbling`i, aren't I.`0\"`n`nIt wasn't phrased as a question.  `\$The Watcher`0 looks down at her boots, and there's a somewhat awkward pause.  \"`#Not really,`0\" you say.`n`n\"`&It felt like it.`0\"  With a heavy `ithump,`i she sets her feet back onto the floor.  \"`&To me, anyway... it's kinda hard to tell, really.  Sorry.`0\"  She toys distractedly with a pen.  \"`&My conversation skills are rusty because nobody talks to me.`0\"`n`nThere was something very disconcerting about the way she said that last sentence.  Not whining; not complaining; not even seeking interaction, really.  Just stating a fact.  Symptom and cause.  Like it's something she's gotten thoroughly used to.`n`n\"`#Really?`0\"`n`n\"`&Yes.  I suppose people must think of me like they think of, oh, I don't know... let's say an undertaker, or a repairman, or... or an angry boss, or something.  Contract says I've gotta give you guys a rough time down here in the Pits, but...  Most of it is just for show, and it doesn't give much room for creativity, and when you live on a boat and you do a boring job, you don't end up with much to talk about on the rare occasions when someone `idoes`i come along and try to engage you.  It's just the same damned thing, day after day.  Honestly sometimes I feel like I'm `iprogrammed`i to do this stuff.`0\"`n`nThere's another awkward pause.  You wonder how you got here from turtlenecks.`n`n\"`&I mean, I tried, like, wearing weird necklaces and stuff,`0\" `\$The Watcher`0 continues.  \"`&You know, you wear something old or unusual or interesting, it's like a conversation prop, sort of thing.  Sooner or later somebody's gonna come along and say \"Hey, that's an interesting... thing,\" and you tell the story, and... well, it's a `istart,`i you know?  But that doesn't work when you're contractually obliged to scowl at people, and even if you weren't... people don't feel too talkative when they're beaten half to death and running on adrenaline.`0\"  She looks up at you.  \"`&I'm glad to see you're still managing to be sociable.`0\"`n`nYou smile nervously.  It's the only way you can smile, right now.  \"`#I try my best.`0\"`n`n`\$The Watcher`0 gives a little nervous laugh, and glances back towards a monitor.  \"`&Sorry.  Listen to me going on about my problems like I don't have a Retraining Vessel to run.  It's just I only ever see people when something goes wrong, y'know?`0\"`n`nYou sense yourself edging over a precipice.  Unable to stop yourself, the words are out of your mouth before you've had a chance to consider what you're letting yourself in for.`n`n\"`#Well, drop me a line sometime when things `iaren't`i going wrong.`0\"`n`n`\$The Watcher`0 looks back up at you.  She shows a little hopeful grin, and rests her chin on her hand.  \"`&Yeah?`0\"`n`n\"`#Yeah,`0\" you say, feeling your future changing as you speak.  \"`#We'll go get a beer or something.`0\"`n`n`\$The Watcher`0's grin spreads wider.  \"`&Heaven knows I could use one.`0\"`n`nYou smile at each other for a moment.  `\$The Watcher`0's smile is warm, relieved, and joyful.  Your own smile is doing a really, really good job of emulating hers.`n`n\"`&The only way to get here is to be knocked out,`0\" says `\$The Watcher`0.  \"`&So I'll come and see you, instead.`0\"  You suspect she's thinking something like `iI made a friend!  We'll talk about monsters and shotguns and boots and everything!`i  \"`&I'll drop you a line, like you say.`0\"`n`n\"`#Great,`0\" you reply.  \"`#I'll look forward to it.`0\"`n`n\"`&I'm gonna let you get back to the mainland, now.  Thanks for talking to me.  Only...`0\"`n`n\"`#Yes?`0\"`n`n\"`&Sorry in advance for the gas.  I've got to keep up appearances.  Network might be watching.`0\"`n`nYou nod.  \"`#Okay.`0\"`n`n\"`&Try to look surprised.`0\"  She leaps out of her chair, slams her hands down on the desk, and ejects the vapour into your face with a sound like a hissing cat.  You collapse gently to the floor, wondering how the hell you've managed to make such a dangerous friend.");
            addnav("What have you gotten yourself into?");
            addnav("Return to Improbable Island", "shades.php");
            $session['user']['resurrections']++;
            $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            $buffs = unserialize(get_module_pref("bufflist", "alternativeresurrect"));
            if (is_array($buffs)) {
                foreach ($buffs as $buff => $values) {
                    apply_buff($buff, $values);
                }
            }
            clear_module_pref("bufflist", "alternativeresurrect");
            set_module_pref("plotpoint3", 1);
            break;
    }
    page_footer();
}
function pub_squathole_drinks_dohook($hookname, $args)
{
    global $session;
    $drinks = array("mudwisearse" => array("price" => 5, "verbosename" => "Mudwisearse"), "wanker" => array("price" => 25, "verbosename" => "Wanker"));
    switch ($hookname) {
        case "pub_squathole_bartender":
            if ($session['user']['race'] == "Robot") {
                $args['text']['hello'] = "You try to smile.  \"`#It's nice to see a pub that caters to my type, outside of Cyber City that is.`0\"`n`n\"`2Only jokin',`0\" squeaks Chlamydia, in a happy little sing-song voice.  \"`2We don't 'ave anythin' fer Robots.  You c'n stick your dick in the light socket if yer like?  Call it twenny Req?`0\"`n`n";
                if ($session['user']['sex']) {
                    $args['text']['hello'] .= "\"`#I'm a female Robot.  I do not have a penis to put into your light socket.`0\"`n`n\"`2Sorry love, it's hard to tell wi' you lot.  I've got some jump leads, we could jus' clip 'em to yer t**s and -`0\"`n`n\"`#No, thank you.`0\"`n`n";
                } else {
                    $args['text']['hello'] .= "\"`#Thank you, but I am quite sensitively tuned.  The results of what you propose would be disasterous, both to your generator and to me.`0\"`n`n\"`2Ten Req?`0\"`n`n\"`#No, thank you.`0\"`n`n";
                }
            } else {
                $args['drinks'] = $drinks;
            }
            break;
        case "pub_squathole_drink":
            $drink = httpget("drink");
            switch ($drink) {
                case "mudwisearse":
                    $session['user']['gold'] -= 5;
                    output("Chlamydia hands you a jam jar that looks to be full of cloudy swampwater.  It tastes like someone's washed a few glasses of Wanker, and bottled the dishwater.  You hold your nose and take another sip, hoping for a buzz, but it looks like the best you can say about this drink is that it's liquid.`n`n");
                    output("You feel... `2honestly very little.`0`n`n");
                    apply_buff('pub_squathole_mudwisearse', array("name" => "`2Crappiest Beer Ever", "rounds" => 8, "atkmod" => 1.05, "roundmsg" => "The Mudwisearse you imbibed in Squat Hole has made you feel slightly more aggressive.  `iVery`i slightly more aggressive.", "wearoff" => "You feel the effects of the Vegetable Cider fade away.", "schema" => "pub_squathole"));
                    break;
                case "wanker":
                    $session['user']['gold'] -= 25;
                    output("\"`2'ere you go, Chuck, one lovely pint o' Wanker.`0\"  Chlamydia slops a stingy pint of beer into a glass that looks as if it was last washed in swamp water.  You take a sniff and choke down the taste and smell of moldy, festering laundry.  The alcohol should help sterilize the worst of it, you hope.`n`nAfter a few more swallows, you start to realise why it's called Wanker.`n`n");
                    output("You feel `\$`b`iFUCKING ENRAGED.`i`b`0`n`n");
                    apply_buff('pub_squathole_wanker', array("name" => "`4Wanker", "rounds" => 25, "atkmod" => 1.3, "roundmsg" => "`0The pint of `4Wanker`0 you imbibed in Squat Hole has filled you with muderous rage!", "wearoff" => "You feel the effects of the `4Wanker`0 slowly fade away.", "schema" => "pub_squathole"));
                    break;
            }
            break;
    }
    return $args;
}
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 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 racegobot_dohook($hookname, $args)
{
    //yeah, the $resline thing is a hack.  Sorry, not sure of a better way
    // to handle this.
    // Pass it as an arg?
    global $session, $resline;
    if (is_module_active("racerobot")) {
        $city = "Cyber City 404";
    } else {
        $city = getsetting("villagename", LOCATION_FIELDS);
    }
    $race = "Gobot";
    switch ($hookname) {
        case "racenames":
            $args[$race] = $race;
            break;
        case "raceminedeath":
            if ($session['user']['race'] == $race) {
                $args['chance'] = get_module_setting("minedeathchance");
            }
            break;
        case "chooserace":
            if ($session['user']['dragonkills'] < 7) {
                break;
            }
            output("`0<a href='newday.php?setrace={$race}{$resline}'>You point downwards, directing the gatekeeper's attention to your knobbly tyres.</a>`n`n ", true);
            addnav("`&Gobot`0", "newday.php?setrace={$race}{$resline}");
            addnav("", "newday.php?setrace={$race}{$resline}");
            break;
        case "setrace":
            if ($session['user']['race'] == $race) {
                output("\"Aha,\" says the gatekeeper, taking out his ledger.  \"Say no more.  Gee...\"`nThe roar of your engine cuts him off, and he looks up.`nHe stares in annoyance at the rapidly-diffusing cloud of dust stretching from his hut to the outpost gate.`n\"Well, that's just bloody rude,\" mutters the gatekeeper.  \"I didn't even get to see its face when I mis-spelled its race.  Ah, well...  Can't insult 'em all, I guess.\"`nHe goes back to his crossword.");
                if (is_module_active("cities")) {
                    set_module_pref("homecity", $city, "cities");
                    if ($session['user']['age'] == 0) {
                        $session['user']['location'] = $city;
                    }
                }
            }
            break;
            //	case "newday-intercept":
            //		if ($session['user']['race']==$race){
            //			if(get_module_pref("reset")==1){
            //				global $session;
            //				$session['user']['specialty'] = "";
            //				set_module_pref("reset",0);
            //				output("`#SYSTEM MESSAGE - FIRMWARE RECONFIGURATION SUBROUTINE INITIALISED.  LIST OF IMPLANTS AVAILABLE FOR EMULATION DISPLAYED BELOW.  AWAITING INPUT.`n`nADVISORY MESSAGE - PROFICIENCY IN USE OF CURRENTLY-EMULATED IMPLANT WILL BE RETAINED.`n`n`0");
            //			}
            //		}
            //		break;
        //	case "newday-intercept":
        //		if ($session['user']['race']==$race){
        //			if(get_module_pref("reset")==1){
        //				global $session;
        //				$session['user']['specialty'] = "";
        //				set_module_pref("reset",0);
        //				output("`#SYSTEM MESSAGE - FIRMWARE RECONFIGURATION SUBROUTINE INITIALISED.  LIST OF IMPLANTS AVAILABLE FOR EMULATION DISPLAYED BELOW.  AWAITING INPUT.`n`nADVISORY MESSAGE - PROFICIENCY IN USE OF CURRENTLY-EMULATED IMPLANT WILL BE RETAINED.`n`n`0");
        //			}
        //		}
        //		break;
        case "newday":
            if ($session['user']['race'] == $race) {
                racegobot_checkcity();
                $bonus = get_module_setting("bonus");
                $one = translate_inline("an");
                $two = translate_inline("two");
                $three = translate_inline("three");
                $word = $bonus == 1 ? $one : $bonus == 2 ? $two : $three;
                $fight = translate_inline("fight");
                $fights = translate_inline("fights");
                $args['turnstoday'] .= ", Race (gobot): {$bonus}";
                $session['user']['turns'] += $bonus;
                output("`n`&Because you are `7untiring`&, you gain `^four extra`& jungle fights for today!`n`0");
                apply_buff("racialbenefit1", array("name" => "`7Ultra-Lightweight Frame`0", "defmod" => "0.5", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                apply_buff("racialbenefit2", array("name" => "`7Lightning Fists`0", "atkmod" => "1.3", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                apply_buff("racialbenefit3", array("name" => "`7Auto-Repair Subroutine`0", "regen" => "ceil(<level>/3);", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "effectmsg" => "`#SYSTEM MESSAGE: {damage} POINTS OF DAMAGE AUTO-REPAIRED`0", "schema" => "module-racegobot"));
                apply_buff("racialbenefit4", array("name" => "`7Cold`0", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "tempstat-charm" => "- floor(<charm>*0.8)", "schema" => "module-racegobot"));
                set_module_pref("reset", 1);
                set_module_pref("uses", 4);
                set_module_pref("status", 2);
                set_module_pref("overdrive", 1);
            }
            break;
        case "fightnav-specialties":
            if ($session['user']['race'] == $race) {
                $uses = get_module_pref("uses");
                $status = get_module_pref("status");
                $overdrive = get_module_pref("overdrive");
                $script = $args['script'];
                if ($uses >= 1) {
                    addnav(array("Power Configuration`0", $uses), "");
                    if ($status == 2) {
                        addnav(array("`4Overclock`7`0", 1), $script . "op=fight&skill={$spec}&l=1", true);
                        addnav(array("`4Underclock`7`0", 1), $script . "op=fight&skill={$spec}&l=2", true);
                    }
                    if ($status == 1) {
                        addnav(array("`4Reset (currently Underclocked)`7`0", 1), $script . "op=fight&skill={$spec}&l=3", true);
                    }
                    if ($status == 3) {
                        addnav(array("`4Reset (currently Overclocked)`7`0", 1), $script . "op=fight&skill={$spec}&l=3", true);
                    }
                }
                if ($overdrive == 1) {
                    addnav(array("`4Engage OverDrive`0", 1), $script . "op=fight&skill={$spec}&l=5", true);
                }
            }
            break;
        case "apply-specialties":
            if ($session['user']['race'] == $race) {
                $skill = httpget('skill');
                $l = httpget('l');
                $dec = 1;
                if ($skill == $spec) {
                    if (get_module_pref("uses") >= 1) {
                        switch ($l) {
                            case 1:
                                apply_buff("racialbenefit3", array("startmsg" => "`#SYSTEM MESSAGE:  OVERCLOCKING IN EFFECT.  REROUTING POWER.  AUTO-REPAIR SUBROUTINE DISABLED`0", "name" => "`7Auto-Repair Subroutine - Disabled`0", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                apply_buff("racialbenefit2", array("startmsg" => "`#SYSTEM MESSAGE:  OVERCLOCKING IN EFFECT.  REROUTING POWER.  COMBAT SUBROUTINE ACCELERATED`0", "name" => "`7Lightning Fists - Enhanced`0", "atkmod" => "1.6", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                set_module_pref("status", '3');
                                break;
                            case 2:
                                apply_buff("racialbenefit3", array("startmsg" => "`#SYSTEM MESSAGE:  UNDERCLOCKING IN EFFECT.  REROUTING POWER.  AUTO-REPAIR SUBROUTINE ACCELERATED`0", "name" => "`7Auto-Repair Subroutine - Enhanced`0", "effectmsg" => "`#SYSTEM MESSAGE: {damage} POINTS OF DAMAGE AUTO-REPAIRED`0", "regen" => "ceil(<level>);", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                apply_buff("racialbenefit2", array("startmsg" => "`#SYSTEM MESSAGE:  UNDERCLOCKING IN EFFECT.  REROUTING POWER.  COMBAT SUBROUTINE DECELERATED`0", "name" => "`7Lightning Fists - Decelerated`0", "atkmod" => "0.8", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                set_module_pref("status", '1');
                                break;
                            case 3:
                                apply_buff("racialbenefit3", array("startmsg" => "`#SYSTEM MESSAGE:  POWER REROUTING DISABLED.  SYSTEM RESTORED TO FACTORY SETTINGS`0", "name" => "`7Auto-Repair Subroutine`0", "effectmsg" => "`#SYSTEM MESSAGE: {damage} POINTS OF DAMAGE AUTO-REPAIRED`0", "regen" => "ceil(<level>/3);", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                apply_buff("racialbenefit2", array("name" => "`7Lightning Fists`0", "atkmod" => "1.3", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racegobot"));
                                set_module_pref("status", '2');
                                break;
                            case 5:
                                apply_buff("overdrive", array("startmsg" => "`#SYSTEM MESSAGE:  BACKUP BATTERY ENGAGED.  OVERDRIVE ENABLED.`0", "name" => "`4OverDrive`0", "regen" => "<level>", "atkmod" => "1.5", "effectmsg" => "`#SYSTEM MESSAGE:  {damage} POINTS OF DAMAGE AUTO-REPAIRED BY OVERDRIVE SEQUENCE`0", "wearoff" => "`#SYSTEM MESSAGE:  BACKUP BATTERY DEPLETED.  OVERDRIVE DISABLED.", "rounds" => 5, "schema" => "module-racegobot"));
                                set_module_pref("overdrive", '0');
                        }
                    }
                }
            }
            break;
        case "validforestloc":
        case "validlocation":
            if (is_module_active("cities")) {
                $args[$city] = "village-{$race}";
            }
            break;
        case "count-travels":
            if ($session['user']['race'] == $race) {
                $args['available'] = $args['available'] + 15;
            }
            break;
        case "village":
            if ($session['user']['race'] == $race) {
                blocknav("runmodule.php?module=bloodbank");
            }
            break;
        case "potion":
            if ($session['user']['race'] == $race) {
                blocknav("healer.php?op=buy&pct=100&return=village.php");
                blocknav("healer.php?op=buy&pct=90&return=village.php");
                blocknav("healer.php?op=buy&pct=80&return=village.php");
                blocknav("healer.php?op=buy&pct=70&return=village.php");
                blocknav("healer.php?op=buy&pct=60&return=village.php");
                blocknav("healer.php?op=buy&pct=50&return=village.php");
                blocknav("healer.php?op=buy&pct=40&return=village.php");
                blocknav("healer.php?op=buy&pct=30&return=village.php");
                blocknav("healer.php?op=buy&pct=20&return=village.php");
                blocknav("healer.php?op=buy&pct=10&return=village.php");
                blocknav("healer.php?op=buy&pct=100");
                blocknav("healer.php?op=buy&pct=90");
                blocknav("healer.php?op=buy&pct=80");
                blocknav("healer.php?op=buy&pct=70");
                blocknav("healer.php?op=buy&pct=60");
                blocknav("healer.php?op=buy&pct=50");
                blocknav("healer.php?op=buy&pct=40");
                blocknav("healer.php?op=buy&pct=30");
                blocknav("healer.php?op=buy&pct=20");
                blocknav("healer.php?op=buy&pct=10");
            }
            break;
    }
    return $args;
}
function iitems_catcher_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "iitems-use-item":
            if ($args['player']['itemid'] == "zapgrenade") {
                apply_buff('zapgrenade', 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(3, 7), "badguyatkmod" => 0.1, "badguydefmod" => 0.1, "roundmsg" => "{badguy} is blinded, deafened and thoroughly confused, and flails wildly while you pummel it!", "wearoff" => "{badguy}`# feels some coherence return, and lunges at you!", "expireafterfight" => 1, "schema" => "iitems-catcher"));
            }
            if ($args['player']['itemid'] == "nicotinegum") {
                $addiction = get_module_pref("addiction", "smoking");
                $betweensmokes = 250 - $addiction;
                set_module_pref("betweensmokes", $betweensmokes, "smoking");
                apply_buff("smoking", array("allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-smoking"));
            }
            if ($args['player']['itemid'] == "oneshotteleporter") {
                require_once "modules/iitems/lib/lib.php";
                iitems_discard_item($args['player']['inv_key']);
                redirect("runmodule.php?module=iitems_catcher&item=oneshotteleporter");
            }
            if ($args['player']['itemid'] == "energydrink") {
                //handle Nutrition adding without invoking extra Edibles functionality
                increment_module_pref("nutrition", 5, "staminafood");
            }
            if ($args['player']['itemid'] == "monsterrepellentspray") {
                if (httpget('skill') == "iitems") {
                    //handle using the item in a fight
                    apply_buff('rspray_fight', array("startmsg" => "`#You pull out a can of Monster Repellent Spray, and spray it liberally on the enemy!`n", "name" => "`^Repellent Spray Attack", "rounds" => 10, "badguyatkmod" => 0.4, "badguydefmod" => 0.4, "roundmsg" => "{badguy} is coughing, choking and all runny-nosed, and cannot attack or defend as effectively!", "wearoff" => "The effects of your Monster Repellent Spray seem to have worn off...`n", "expireafterfight" => 1, "schema" => "iitems-catcher"));
                } else {
                    //handle using the item outside of a fight
                    apply_buff('rspray_normal', array("name" => "`^Repellent Spray", "rounds" => -1, "badguyatkmod" => 0.8, "badguydefmod" => 0.8, "roundmsg" => "{badguy} can't stand the smell of your Monster Repellent Spray, and doesn't want to get too close!", "schema" => "iitems-catcher"));
                    set_module_pref("encounterchance", 50, "worldmapen");
                    output("You liberally douse yourself with an entire can of Monster Repellent Spray.  For the rest of this game day, your chances of encountering a monster on the Island Map have been halved, and monsters you do encounter will be reluctant to attack you as hard.`n`n");
                }
            }
            if ($args['player']['itemid'] == "improbabilitybomb") {
                $effect = e_rand(1, 8);
                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" => "iitems-catcher"));
                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" => "iitems-catcher"));
                        $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" => "iitems-catcher"));
                        $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" => "iitems-catcher"));
                        break;
                    case 4:
                    case 5:
                        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" => "iitems-catcher"));
                        $session['user']['charm'] += 1;
                        break;
                    case 6:
                        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" => "iitems-catcher", "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" => "iitems-catcher", "wearoff" => "The bomb fizzles out and sends out one last dying volley of sparks.", "expireafterfight" => 1));
                        break;
                    case 7:
                        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" => "iitems-catcher", "wearoff" => "`5The Purple Monster, seeing its business here concluded, disappears with a faint 'pop.'", "expireafterfight" => 1));
                        break;
                    case 8:
                        $maxdmg = $session['user']['maxhitpoints'] * 2;
                        if ($maxdmg < 500) {
                            $maxdmg = 500;
                        }
                        $mindmg = $session['user']['hitpoints'] * 0.5;
                        if ($maxdmg < 200) {
                            $maxdmg = 200;
                        }
                        apply_buff('ibomb9', array("rounds" => 1, "minioncount" => 1, "mingoodguydamage" => $mindmg, "maxgoodguydamage" => $maxdmg, "effectmsg" => "`4Before the bomb even leaves your hand, it blows up in your face!  The explosion causes {damage} points!", "schema" => "iitems-catcher", "expireafterfight" => 1));
                        break;
                }
            }
            if ($args['player']['itemid'] == "cratesniffer") {
                output("`0You thumb the switch on your Crate Sniffer.  It buzzes and hisses for a moment, exhausting its primitive battery sending out a radio ping to nearby Crates.`n`n");
                $crates = unserialize(get_module_setting("crates", "iitemcrates"));
                debug($crates);
                $ploc = get_module_pref("worldXYZ", "worldmapen");
                list($px, $py, $pz) = explode(",", $ploc);
                $pxlow = $px - 3;
                $pxhigh = $px + 3;
                $pylow = $py - 3;
                $pyhigh = $py + 3;
                if (!is_array($crates)) {
                    $crates = array();
                }
                $count = 0;
                foreach ($crates as $key => $vals) {
                    if ($vals['loc']['x'] >= $pxlow && $vals['loc']['x'] <= $pxhigh && $vals['loc']['y'] >= $pylow && $vals['loc']['y'] <= $pyhigh) {
                        $count++;
                    }
                }
                output("It displays, weakly, the number `\$`b%s`b`0 in dull red LED's before its radio module catches fire.`n`n", $count);
            }
            break;
        case "newday":
            set_module_pref("encounterchance", 100, "worldmapen");
            break;
    }
    return $args;
}
function lovers_violet()
{
    global $session;
    $seenlover = get_module_pref("seenlover");
    $partner = get_partner();
    if ($seenlover == 0) {
        if ($session['user']['marriedto'] == INT_MAX) {
            if (e_rand(1, 4) == 1) {
                switch (e_rand(1, 4)) {
                    case 1:
                        $msg = translate_inline("being too busy serving these pigs,");
                        break;
                    case 2:
                        $msg = translate_inline("\"that time of month,\"");
                        break;
                    case 3:
                        $msg = translate_inline("\"a little cold...  *cough cough* see?\"");
                        break;
                    case 4:
                        $msg = translate_inline("men all being pigs,");
                        break;
                }
                output("You head over to cuddle %s`0 and kiss her about the face and neck, but she grumbles something about %s and with a comment like that, you storm away from her!`n`n", $partner, $msg);
                $session['user']['charm']--;
                output("`^You LOSE a charm point!");
            } else {
                output("You and %s`0 take some time to yourselves, and you leave the inn, positively glowing!", $partner);
                apply_buff('lover', lovers_getbuff());
                $session['user']['charm']++;
                output("`n`n`^You gain a charm point!");
            }
            $seenlover = 1;
        } elseif (httpget('flirt') == "") {
            output("You stare dreamily across the room at %s`0, who leans across a table to serve a patron a drink.", $partner);
            output("In doing so, she shows perhaps a bit more skin than is necessary, but you don't feel the need to object.");
            addnav("Flirt");
            addnav("Wink", "runmodule.php?module=lovers&op=flirt&flirt=1");
            addnav("Kiss her hand", "runmodule.php?module=lovers&op=flirt&flirt=2");
            addnav("Peck her on the lips", "runmodule.php?module=lovers&op=flirt&flirt=3");
            addnav("Sit her on your lap", "runmodule.php?module=lovers&op=flirt&flirt=4");
            addnav("Grab her backside", "runmodule.php?module=lovers&op=flirt&flirt=5");
            addnav("Carry her upstairs", "runmodule.php?module=lovers&op=flirt&flirt=6");
            addnav("Marry her", "runmodule.php?module=lovers&op=flirt&flirt=7");
        } else {
            $c = $session['user']['charm'];
            $seenlover = 1;
            switch (httpget('flirt')) {
                case 1:
                    if (e_rand($c, 2) >= 2) {
                        output("You wink at %s`0, and she gives you a warm smile in return.", $partner);
                        if ($c < 4) {
                            $c++;
                        }
                    } else {
                        output("You wink at %s`0, but she pretends not to notice.", $partner);
                    }
                    break;
                case 2:
                    output("You stroll confidently across the room toward %s`0.", $partner);
                    if (e_rand($c, 4) >= 4) {
                        output("Taking hold of her hand, you kiss it gently, your lips remaining for only a few seconds.");
                        output("%s`0 blushes and tucks a strand of hair behind her ear as you walk away, then presses the back side of her hand longingly against her cheek while watching your retreat.", $partner);
                        if ($c < 7) {
                            $c++;
                        }
                    } else {
                        output("You reach out to grab her hand, but %s`0 takes her hand back and asks if perhaps you'd like a drink.", $partner);
                    }
                    break;
                case 3:
                    output("Standing with your back against a wooden column, you wait for %s`0 to wander your way when you call her name.", $partner);
                    if (e_rand($c, 7) >= 7) {
                        output("She approaches, a hint of a smile on her face.");
                        output("You grab her chin, lift it slightly, and place a firm but quick kiss on her plump lips.");
                        if ($c < 11) {
                            $c++;
                        }
                    } else {
                        output("She smiles and apologizes, insisting that she is simply too busy to take a moment from her work.");
                    }
                    break;
                case 4:
                    output("Sitting at a table, you wait for %s`0 to come your way.", $partner);
                    if (e_rand($c, 11) >= 11) {
                        output("When she does so, you reach up and grab her firmly by the waist, pulling her down on to your lap.");
                        output("She laughs and throws her arms around your neck in a warm hug before thumping you on the chest, standing up, and insisting that she really must get back to work.");
                        if ($c < 14) {
                            $c++;
                        }
                    } else {
                        output("When she does so, you reach up to grab her by the waist, but she deftly dodges, careful not to spill the drink that she's carrying.");
                        if ($c > 0 && $c < 10) {
                            $c--;
                        }
                    }
                    break;
                case 5:
                    output("Waiting for %s`0 to brush by you, you firmly palm her backside.", $partner);
                    if (e_rand($c, 14) >= 14) {
                        output("She turns and gives you a warm, knowing smile.");
                        if ($c < 18) {
                            $c++;
                        }
                    } else {
                        output("She turns and slaps you across the face. Hard.");
                        output("Perhaps you should go a little slower.");
                        if ($c > 0 && $c < 13) {
                            $c--;
                        }
                    }
                    break;
                case 6:
                    if (e_rand($c, 18) >= 18) {
                        output("Like a whirlwind, you sweep through the inn, grabbing %s`0, who throws her arms around your neck, and whisk her upstairs to her room there.", $partner);
                        output("Not more than 10 minutes later you stroll down the stairs, smoking a pipe, and grinning from ear to ear.");
                        if ($session['user']['turns'] > 0) {
                            output("You feel exhausted!  ");
                            $session['user']['turns'] -= 2;
                            if ($session['user']['turns'] < 0) {
                                $session['user']['turns'] = 0;
                            }
                        }
                        addnews("`@%s`@ and %s`@ were seen heading up the stairs in the inn together.`0", $session['user']['name'], $partner);
                        if ($c < 25) {
                            $c++;
                        }
                    } else {
                        output("Like a whirlwind, you sweep through the inn, and grab for %s`0.", $partner);
                        output("She turns and slaps your face!");
                        output("\"`%What sort of girl do you think I am, anyhow?`0\" she demands! ");
                        if ($c > 0) {
                            $c--;
                        }
                    }
                    break;
                case 7:
                    output("%s`0 is working feverishly to serve patrons of the inn.", $partner);
                    output("You stroll up to her and take the mugs out of her hand, placing them on a nearby table.");
                    output("Amidst her protests you kneel down on one knee, taking her hand in yours.");
                    output("She quiets as you stare up at her and utter the question that you never thought you'd utter.");
                    output("She stares at you and you immediately know the answer by the look on her face.`n`n");
                    if ($c >= 22) {
                        output("It is a look of exceeding happiness.");
                        output("\"`%Yes!`0\" she says, \"`%Yes, yes yes!!!`0\"");
                        output("Her final confirmations are buried in a flurry of kisses about your face and neck.`n`n");
                        output("The next days are a blur; you and %s`0 are married in the abbey down the street, in a gorgeous ceremony with many frilly girly things.", $partner);
                        addnews("`&%s`& and %s`& are joined today in joyous matrimony!!!", $session['user']['name'], $partner);
                        $session['user']['marriedto'] = INT_MAX;
                        apply_buff('lover', lovers_getbuff());
                    } else {
                        output("It is a look of sadness.");
                        output("\"`%No`0,\" she says, \"`%I'm not yet ready to settle down`0.\"`n`n");
                        output("Disheartened, you no longer possess the will to do much of anything today.");
                        $session['user']['turns'] = 0;
                        debuglog("lost all turns after being rejected for marriage.");
                    }
            }
            if ($c > $session['user']['charm']) {
                output("`n`n`^You gain a charm point!");
            }
            if ($c < $session['user']['charm']) {
                output("`n`n`\$You LOSE a charm point!");
            }
            $session['user']['charm'] = $c;
        }
    } else {
        output("You think you had better not push your luck with %s`0 today.", $partner);
    }
    set_module_pref("seenlover", $seenlover);
}
 }
 tlschema();
 output("`2Hitpoints have been restored to `^%s`2.`n", $session['user']['maxhitpoints']);
 reset($session['user']['dragonpoints']);
 $dkff = 0;
 while (list($key, $val) = each($session['user']['dragonpoints'])) {
     if ($val == "ff") {
         $dkff++;
     }
 }
 if ($session['user']['hashorse']) {
     $buff = unserialize($playermount['mountbuff']);
     if (!isset($buff['schema']) || $buff['schema'] == "") {
         $buff['schema'] = "mounts";
     }
     apply_buff('mount', $buff);
 }
 if ($dkff > 0) {
     output("`n`2You gain `^%s`2 forest %s from spent dragon points!", $dkff, translate_inline($dkff == 1 ? "fight" : "fights"));
 }
 $r1 = e_rand(-1, 1);
 $r2 = e_rand(-1, 1);
 $spirits = $r1 + $r2;
 $resurrectionturns = $spirits;
 if ($resurrection == "true") {
     addnews(sprinft_translate("`&%s`& has been resurrected by %s`&.", $session['user']['name'], getsetting('deathoverlord', '`$Ramius')));
     $spirits = -6;
     $resurrectionturns = getsetting('resurrectionturns', -6);
     if (strstr($resurrectionturns, '%')) {
         $resurrectionturns = strtok($resurrectionturns, '%');
         $resurrectionturns = (int) $resurrectionturns;
function apply_skill($skill, $l)
{
    global $session;
    if ($skill == "godmode") {
        apply_buff('godmode', array("name" => "`&GOD MODE", "rounds" => 1, "wearoff" => "You feel mortal again.", "atkmod" => 25, "defmod" => 25, "invulnerable" => 1, "startmsg" => "`&`bYou feel godlike.`b", "schema" => "skill"));
    }
    modulehook("apply-specialties");
}
function peerpressure_runevent($type)
{
    global $session;
    $session['user']['specialinc'] = "module:peerpressure";
    // For translation reasons, you cannot really substitute in his/her
    // since the gender can change other things
    if ($session['user']['sex']) {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from her peers ringing in her ears.", $session['user']['name']);
    } else {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from his peers ringing in his ears.", $session['user']['name']);
    }
    output("`2Wandering the village, going about your business, you are suddenly surrounded by a group of villagers.");
    output("They wonder why such an experienced adventurer as yourself hasn't slain a dragon yet.");
    output("You mutter some embarrassed excuses but they aren't listening.");
    output("They crowd around you closer, and lift you up on their shoulders.");
    $isforest = 0;
    $vloc = modulehook('validforestloc', array());
    foreach ($vloc as $i => $l) {
        if ($session['user']['location'] == $l) {
            $isforest = 1;
            break;
        }
    }
    if ($isforest || count($vloc) == 0) {
        output("`n`nCheering your name the whole way, they carry you into the forest, and right to the mouth of a cave outside the town!`n`n");
    } else {
        $key = array_rand($vloc);
        output("`n`nCheering your name the whole way, they carry you far into the forest, and right to the mouth of a cave outside the town of %s!`n`n", $key);
        $session['user']['location'] = $key;
    }
    output("Still cheering your name, they put you down and eagerly wait for you to enter and slay that dragon.`n`n");
    output("You know that you'd never live it down if you tried to back out now.");
    output("Swallowing your fear as best you can, you enter the cave.");
    if (is_module_active("dragonplace")) {
        addnav("Enter the cave", "runmodule.php?module=dragonplace&op=cave");
    } else {
        addnav("Enter the cave", "dragon.php?nointro=1");
    }
    $session['user']['specialinc'] = "";
    checkday();
    //increment buffs, newday buffs, and heal... and probably throw people off in general
    $session['user']['specialinc'] = "module:peerpressure";
    apply_buff('peerpressure', array("name" => "`2Heroic Valor", "rounds" => 20, "atkmod" => 1 + get_module_pref("dayspast") / 100, "defmod" => 1 + get_module_pref("dayspast") / 100, "startmsg" => "`2You fight bravely, considering the pressure you're under.", "wearoff" => "`@The Green Dragon`2 has beaten and burnt the bravery out of you.", "schema" => "module-peerpressure"));
}
function gravebless_dohook($hookname, $args)
{
    global $session;
    $blesscost = get_module_setting("blesscost");
    $minrez = get_module_setting("minrez");
    $playerfavor = $session['user']['deathpower'];
    $playerrezzes = $session['user']['resurrections'];
    $blessed = get_module_pref("ramiusblessed");
    $cursed = get_module_pref("ramiuscursed");
    $ramiusarmor = get_module_pref("ramiusarmor");
    $ramiusweapon = get_module_pref("ramiusweapon");
    switch ($hookname) {
        case "dragonkilltext":
            if ($blessed || $cursed) {
                output("`n`nYou seem to hear a very faint humming noise, but as you look around for the source, it quickly fades to silence.");
            }
            set_module_pref("ramiusblessed", 0);
            set_module_pref("ramiuscursed", 0);
            set_module_pref("ramiusarmor", 0);
            set_module_pref("ramiusweapon", 0);
            set_module_pref("currmultiplier", 0);
            break;
        case "ramiusfavors":
            // only show the link if they have enough favor, haven't already
            // used it this DK, and have enough rezzes
            if ($playerfavor >= $blesscost && !($blessed || $cursed) && $playerrezzes >= $minrez) {
                require_once "lib/sanitize.php";
                addnav(array("%s Favors", sanitize(getsetting("deathoverlord", '`$Ramius'))));
                addnav(array("Seek a Blessing (%s favor)", $blesscost), "runmodule.php?module=gravebless&blessop=bless");
            }
            break;
        case "newday":
            $multiplier = get_module_pref("currmultiplier");
            $firstday = get_module_pref("firstday");
            if ($blessed) {
                if ($firstday) {
                    set_module_pref("firstday", 0);
                } else {
                    $basemult = get_module_setting("basemultiplier");
                    // start out with a quicker reduction, down to 20%
                    if ($multiplier > 0.2) {
                        $multiplier = round($multiplier - $basemult / 7, 2);
                    } else {
                        // flatten out the decay after 20%
                        $multiplier = round($multiplier * 0.75, 2);
                    }
                    if ($multiplier < 0.01) {
                        $multiplier = 0.01;
                        // bottoms out at 1% until DK
                    }
                    set_module_pref("currmultiplier", $multiplier);
                }
                $deathoverlord = getsetting("deathoverlord", "`\$Ramius");
                if ($ramiusarmor) {
                    $ramiusbuff = array("name" => array("%s`\$' Blessed Armor", $deathoverlord), "rounds" => -1, "defmod" => 1.25, "damageshield" => $multiplier, "roundmsg" => "`\$Your armor hums to life in response to the battle!", "effectmsg" => "`\$You feel a shock course through your armor as it deflects {damage} damage back to {badguy}!", "effectnodmg" => "", "effectfailmsg" => "", "schema" => "module-gravebless");
                } elseif ($ramiusweapon) {
                    $ramiusbuff = array("name" => array("%s`4' Blessed Weapon", $deathoverlord), "rounds" => -1, "atkmod" => 1.25, "lifetap" => $multiplier, "roundmsg" => "`\$Your weapon hums to life as you swing it at {badguy}!", "effectmsg" => "`\$You feel a shock course through your weapon as it heals you for {damage}!", "effectnodmg" => "", "effectfailmsg" => "", "schema" => "module-gravebless");
                } else {
                    debug("Error: Ramius bless flagged, but not armor or weapon (gravebless)");
                }
            } elseif ($cursed) {
                if ($firstday) {
                    set_module_pref("firstday", 0);
                } else {
                    $cursemult = get_module_setting("cursemultiplier");
                    $curserate = get_module_setting("curserate");
                    $multiplier += $curserate / 100;
                    // curses degrade linearly..
                    if ($multiplier > 0.99) {
                        $multiplier = 0.99;
                        // ..but don't go away completely until DK
                    }
                    set_module_pref("currmultiplier", $multiplier);
                }
                $deathoverlord = getsetting("deathoverlord", "`\$Ramius");
                if ($ramiusarmor) {
                    $ramiusbuff = array("name" => array("%s`\$' Cursed Armor", $deathoverlord), "rounds" => -1, "defmod" => $multiplier, "badguyatkmod" => 1.25, "roundmsg" => "`4Your armor hums to life in response to the battle!", "schema" => "module-gravebless");
                } elseif ($ramiusweapon) {
                    $ramiusbuff = array("name" => array("%s`\$' Cursed Weapon", $deathoverlord), "rounds" => -1, "atkmod" => $multiplier, "badguydefmod" => 1.25, "roundmsg" => "`4Your weapon hums to life as you swing it at {badguy}!", "schema" => "module-gravebless");
                } else {
                    debug("Error: Ramius curse flagged, but not armor or weapon (gravebless)");
                }
            } else {
                debug("neither blessed nor cursed are flagged (gravebless)");
            }
            if ($blessed || $cursed) {
                output("`nYou think you can hear a faint humming sound as you don your armor and grab your weapon. ");
                output("Your %s even feels slightly warmer to the touch than you remember.`n", translate_inline($ramiusarmor == 1 ? "armor" : "weapon"));
                apply_buff("ramiusbuff", $ramiusbuff);
            }
            break;
    }
    return $args;
}
     }
     $allprefs = unserialize(get_module_pref('allprefs'));
     $allprefs['counsel'] = 0;
     $allprefs['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefs));
     $allprefsm = unserialize(get_module_pref('allprefs', 'marriage', $session['user']['marriedto']));
     $allprefsm['counsel'] = 0;
     $allprefsm['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefsm), 'marriage', $session['user']['marriedto']);
     invalidatedatacache("marriage-marriedonline");
     invalidatedatacache("marriage-marriedrealm");
     require_once "lib/datetime.php";
     $time = date("Y-m-d H:i:s");
     set_module_objpref("marriage", $session['user']['marriedto'], "marriagedate", $time);
     set_module_objpref("marriage", $session['user']['acctid'], "marriagedate", $time);
     apply_buff('marriage-start', array("name" => "`@Marriage", "rounds" => 100, "wearoff" => "`&The elation wears off.", "defmod" => 1.83, "survivenewday" => 1, "roundmsg" => "`@You are elated at your marriage"));
     debuglog("proposal accepted from {$row['name']}");
     break;
 case "reject":
     $stuff = explode(',', get_module_pref('proposals'));
     $i = "";
     foreach ($stuff as $val) {
         if ($val != "" && $val != $target && $val != $session['user']['acctid']) {
             $i .= "," . $val;
         }
     }
     set_module_pref('proposals', $i);
     $stuff = explode(',', get_module_pref('proposals', 'marriage', $target));
     $i = "";
     foreach ($stuff as $val) {
         if ($val != "" && $val != $target && $val != $session['user']['acctid']) {
    db_query($sql);
    module_delete_objprefs('mounts', $id);
    $op = "";
    httpset("op", "");
    invalidatedatacache("mountdata-{$id}");
} elseif ($op == "give") {
    $session['user']['hashorse'] = $id;
    // changed to make use of the cached query
    $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$id}'";
    $result = db_query_cached($sql, "mountdata-{$id}", 3600);
    $row = db_fetch_assoc($result);
    $buff = unserialize($row['mountbuff']);
    if ($buff['schema'] == "") {
        $buff['schema'] = "mounts";
    }
    apply_buff("mount", $buff);
    $op = "";
    httpset("op", "");
} elseif ($op == "save") {
    $subop = httpget("subop");
    if ($subop == "") {
        $buff = array();
        $mount = httppost('mount');
        if ($mount) {
            reset($mount['mountbuff']);
            while (list($key, $val) = each($mount['mountbuff'])) {
                if ($val > "") {
                    $buff[$key] = stripslashes($val);
                }
            }
            $buff['schema'] = "mounts";
function oldchurch_run()
{
    global $session;
    page_header("Old Church");
    $op = httpget('op');
    $bloodgift = get_module_pref("bloodgift");
    if ($bloodgift == 1) {
        output("`7As you approach the old church, you are beset with troubling flashes of what happened last time you were here.");
        output("`n`nYou decide to come back another day.");
        villagenav();
    } elseif ($op == "") {
        output("`7An ancient church stands alone, apart from the other buildings, centuries-old scorchmarks marring the once grand walls and curling round the belltower.");
        output("`n`nA thin path winds its way up the hill between sinister-looking memorials covered in mist.");
        output("While the church has obviously been abandoned for a long time, the windows flicker with light from the inside and shadows can be seen dancing on the tall broken shards of glass which fill the windows.");
        addnav("Enter the Church", "runmodule.php?module=oldchurch&op=enter");
        addnav("Return to the Village", "village.php");
    } elseif ($op == "enter") {
        output("`3You make your way up the hill and edge through the sundered doors, taking in the wrecked interior.");
        output("A flickering torch inhabits an iron holder to one side, above a dusty font.");
        output("Beyond the shattered pews lies an altar which has fresh cloths on it and six candles burning dimly.`n`n");
        output("From out of a small door to one side of the altar walks a curiously hearty figure dressed in grey robes who, ignoring the desolate surroundings, opens his arms wide and bids you welcome to the church, \"`^Greetings, greetings, welcome to this little sanctuary. I am `5Capelthwaite`^, and it is good to see people once again visiting this holy place, feel free to look around. My apologies for the current... disarray... but the world is as the Gods decree it, and we must merely live with such things.`3\"");
        output("He casts an appraising eye over you and smiles even more broadly before continuing,");
        output("\"`^Naturally we are always in need of funds for various charitable projects, and if you wish to donate you will of course gain an appropriate reward.");
        output("For those as hardy an adventurer as you there are obviously other ways to earn a blessing if you are short of funds.`3\"");
        output("He smiles to himself and waits at the altar for your decision.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "belfry") {
        output("`7You walk to the back of the church and climb the unsteady steps up to the belfry, where a large rusted bell hangs from rotting timbers.");
        output("Though you'd expect to get a great view from up here, even the nearby buildings seem shrouded in fog.");
        $random = e_rand(1, 3);
        if ($random >= 2) {
            output("`n`nAs you hurry down from the belfry, you accidentally knock into the bell, which makes an eerily resonant sound as it tolls.");
        }
        output("Spooked slightly, you hurry down the stairs and back into the church.");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "font") {
        output("`\$As you wander over to the alcove by the door and look inside, there seem to be dark stains inside the font, as though it was not usually used for water.");
        output("`n`n`^Slightly troubled by this, you return to the main part of the church.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "donate") {
        output("`5Capelthwaite `^grins as you walk over to the donation plate, waiting to see how much you will put in before making any preparations.");
        $donate = array("donation" => "Donation,int");
        require_once "lib/showform.php";
        rawoutput("<form action='runmodule.php?module=oldchurch&op=afterdonate' method='POST'>");
        showform($donate, array(), true);
        addnav("", "runmodule.php?module=oldchurch&op=afterdonate");
        $give = translate_inline("Give Money");
        rawoutput("<input type='submit' class='button' value='{$give}'>");
        rawoutput("</form><br>");
        addnav("Change your mind", "runmodule.php?module=oldchurch&op=enter");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "afterdonate") {
        $donation = httppost('donation');
        if ($donation > $session['user']['gold'] || $donation < 0) {
            output("`5Capelthwaite `^looks somewhat grim as you try to persuade him that it is the spirit of giving which counts.`n`n");
            output("You are hastily ejected from the church.");
        } elseif ($donation >= $session['user']['level'] * 103) {
            output("`^As you put a hefty amount of gold in the bowl, `5Capelthwaite`^'s grin widens and he beckons you over to the altar for a blessing.");
            output("`n`nAfter muttering something a little too fast for you to catch, he places his hand on your head and blesses you.");
            output("`n`n`@You feel energy flowing through you!");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            $donated = get_module_pref("donated");
            apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => $donated ? 1.05 : 1.2, "defmod" => $donated ? 1.01 : 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            set_module_pref("donated", 1);
        } else {
            output("`^As the few coins you decided to spare rattle into the bowl, `5Capelthwaite`^'s grin turns sickening as he beckons you over to the altar.`n`n");
            output("After muttering something too low for you to catch, he places his hand on your head and places the enchantment on you.`n`n");
            output("`4Dark energy flows through you!");
            apply_buff('capelthwaite_curse', array("name" => "`5Capelthwaite's \"Blessing\"", "rounds" => 10, "wearoff" => "The burst of energy passes.", "atkmod" => 0.8, "defmod" => 0.9, "roundmsg" => "Dark Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            set_module_pref("donated", 1);
        }
        villagenav();
    } elseif ($op == "ritual") {
        output("`3You nervously inquire about another way that you could earn a blessing as `5Capelthwaite`3 looks on you magnanimously.`n`n");
        output("\"`^No need to be so nervous my friend, simply a short rite to honour the master, you'll feel fine the next day. Just take this potion and I'll take care of everything.`3\".`n`n");
        output("He holds out a small black potion he produced from somewhere for you to drink and smiles encouragingly.");
        addnav("Take the Potion", "runmodule.php?module=oldchurch&op=darkritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "darkritual") {
        output("`^Trusting in `5Capelthwaite`^'s friendly smile, you drink down the potion. You feel funny for a moment, then the world begins to swim before your eyes, and you black out.`n`n");
        $ritual = e_rand(1, 100);
        if ($ritual >= 100) {
            output("`7Though the potion sapped all will from your body, you remain conscious as you are dragged somewhere, hooded, by several people.");
            output("When the hood is removed you are in a cavern deep underground, trapped in what looks like some artist's rendition of the underworld.");
            output("You are dressed in a grey robe and placed on the edge of a smoke-filled circle with many others similarly outfitted.");
            output("For what seems like hours you are surrounded by chanting, smoke and the sensation of life being drained from your very soul.");
            output("Eventually you are dragged back up through some tunnels like a sack of grain before being dumped in front of the altar, where `5Capelthwaite`7 feeds you another potion.`n`n");
        } else {
            output("You dream of smoke and a glowing light.`n`n");
        }
        output("`^You regain your faculties with `5Capelthwaite`^ leaning over you, looking red-faced.");
        output("He quickly blesses you before helping you out of the church.`n`n");
        output("`@You feel energy flowing through you!`n`n");
        apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => 1.2, "defmod" => 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
        output("You hurry away from this place as fast as your unsteady legs can take you.");
        $ritualenergy = get_module_setting("ritualenergy");
        $ritualenergy++;
        set_module_setting("ritualenergy", $ritualenergy);
        set_module_pref("bloodgift", 1);
        if ($session['user']['turns'] >= 5) {
            $session['user']['turns']--;
        }
        $session['user']['hitpoints'] *= 0.5;
        if ($session['user']['hitpoints'] < 1) {
            $sesson['user']['hitpoints'] = 1;
        }
        villagenav();
    }
    page_footer();
}
function iitems_buffs_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "iitems-use-item":
            if ($args['master']['usebuff']) {
                $buff = array();
                if (isset($args['master']['buffname'])) {
                    $buff['name'] = stripslashes($args['master']['buffname']);
                }
                if (isset($args['master']['buffrounds'])) {
                    $buff['rounds'] = $args['master']['buffrounds'];
                } else {
                    $buff['rounds'] = 0;
                }
                if (isset($args['master']['buffwearoffmsg'])) {
                    $buff['wearoff'] = stripslashes($args['master']['buffwearoffmsg']);
                }
                if (isset($args['master']['buffstartmsg'])) {
                    $buff['startmsg'] = stripslashes($args['master']['buffstartmsg']);
                }
                if (isset($args['master']['buffeffectmsg'])) {
                    $buff['effectmsg'] = stripslashes($args['master']['buffeffectmsg']);
                }
                if (isset($args['master']['buffnodmgmsg'])) {
                    $buff['effectnodmgmsg'] = stripslashes($args['master']['buffnodmgmsg']);
                }
                if (isset($args['master']['buffeffectfailmsg'])) {
                    $buff['effectfailmsg'] = stripslashes($args['master']['buffeffectfailmsg']);
                }
                if (isset($args['master']['buffatkmod'])) {
                    $buff['atkmod'] = $args['master']['buffatkmod'];
                } else {
                    $buff['atkmod'] = 1;
                }
                if (isset($args['master']['buffdefmod'])) {
                    $buff['defmod'] = $args['master']['buffdefmod'];
                } else {
                    $buff['defmod'] = 1;
                }
                if (isset($args['master']['buffinvulnerable'])) {
                    $buff['invulnerable'] = $args['master']['buffinvulnerable'];
                }
                if (isset($args['master']['buffexpireafterfight'])) {
                    $buff['expireafterfight'] = $args['master']['buffexpireafterfight'];
                }
                if (isset($args['master']['buffregen'])) {
                    $buff['regen'] = $args['master']['buffregen'];
                }
                if (isset($args['master']['buffminioncount'])) {
                    $buff['minioncount'] = $args['master']['buffminioncount'];
                }
                if (isset($args['master']['buffminbadguydamage'])) {
                    $buff['minbadguydamage'] = $args['master']['buffminbadguydamage'];
                }
                if (isset($args['master']['buffmaxbadguydamage'])) {
                    $buff['maxbadguydamage'] = $args['master']['buffmaxbadguydamage'];
                }
                if (isset($args['master']['buffmingoodguydamage'])) {
                    $buff['mingoodguydamage'] = $args['master']['buffmingoodguydamage'];
                }
                if (isset($args['master']['buffmaxgoodguydamage'])) {
                    $buff['maxgoodguydamage'] = $args['master']['buffmaxgoodguydamage'];
                }
                if (isset($args['master']['bufflifetap'])) {
                    $buff['lifetap'] = $args['master']['bufflifetap'];
                }
                if (isset($args['master']['buffdamageshield'])) {
                    $buff['damageshield'] = $args['master']['buffdamageshield'];
                }
                if (isset($args['master']['buffbadguydmgmod'])) {
                    $buff['badguydmgmod'] = $args['master']['buffbadguydmgmod'];
                } else {
                    $buff['badguydmgmod'] = 1;
                }
                if (isset($args['master']['buffbadguyatkmod'])) {
                    $buff['badguyatkmod'] = $args['master']['buffbadguyatkmod'];
                } else {
                    $buff['badguyatkmod'] = 1;
                }
                if (isset($args['master']['buffbadguydefmod'])) {
                    $buff['badguydefmod'] = $args['master']['buffbadguydefmod'];
                } else {
                    $buff['badguydefmod'] = 1;
                }
                while (list($property, $value) = each($buff)) {
                    $buff[$property] = preg_replace("/\\n/", "", $value);
                }
                debug("Iitems_buffs is applying a buff");
                apply_buff($args['player']['itemid'], $buff);
            }
            break;
        case "iitems-superuser":
            output("`bIItems - Buffs`b`nApplies buffs when the item is used.  The variable \"usebuff\" must be set to true before a buff is applied - this is to avoid doing a lot of unnecessary work.  Beyond that, use standard buff variable names, prepending them with \"buff\" IE buffatkmod, buffdefmod, buffdmgshield etc etc.`n`n");
            break;
    }
    return $args;
}
function ferryman_runevent($type)
{
    global $session;
    $from = "forest.php?";
    $session['user']['specialinc'] = "module:ferryman";
    $op = httpget('op');
    // module settings
    $ferrycost = get_module_setting("ferrycost");
    $highferrycost = get_module_setting("highferrycost");
    $drownchance = get_module_setting("drownchance");
    $gaingemchance = get_module_setting("gaingemchance");
    $losegoldpercent = get_module_setting("losegoldpercent");
    $losegemamount = get_module_setting("losegemamount");
    $losehppercent = get_module_setting("losehppercent");
    $maxfavorgain = get_module_setting("maxfavorgain");
    set_module_pref("paidferry", 0);
    // encounter starts here
    if ($op == "" || $op == "search") {
        output("`2As you search through the forest for something to kill, you duck under some underbrush and hear the sound of water.");
        output("Looking for the source of the noise, you stumble out of the forest and you find yourself standing on the bank of a wide river.");
        output("Trying to come up with a way to cross, you glance upstream and notice what appears to be a small dock not too far away.`n`n");
        output("You make your way upstream where you find a cloaked figure standing next to a small boat tied to the dock.");
        output("Surely he could help you cross.");
        addnav("The Ferryman");
        addnav("Talk to the Figure", $from . "op=talkferryman");
        addnav("Go Back", $from . "op=ignoreferryman");
    } elseif ($op == "talkferryman") {
        output("`2You approach and the figure motions you onto the boat.");
        addnav("The Ferryman");
        addnav("Get Onboard", $from . "op=boardferry");
        addnav("Go Back", $from . "op=leaveferryman");
    } elseif ($op == "boardferry") {
        output("`2The figure points to a cup.");
        output("You see a sign that reads, \"`@%s gold to cross`2\".", $ferrycost);
        addnav("The Ferryman");
        addnav(array("Pay %s Gold", $ferrycost), $from . "op=payferry");
        addnav("Don't Pay", $from . "op=dontpayferry");
        addnav("Get Out", $from . "op=leaveferryman");
    } elseif ($op == "payferry") {
        if ($session['user']['gold'] < $ferrycost) {
            output("`2You dig through your pockets and pouches, but you can't find enough gold.`n`n");
            output("The ferryman waits expectantly.");
            addnav("The Ferryman");
            addnav("Board Anyway", $from . "op=dontpayferry");
            addnav("Leave", $from . "op=leaveferryman");
        } else {
            $session['user']['gold'] -= $ferrycost;
            debuglog("spent {$ferrycost} gold on ferryman");
            set_module_pref("paidferry", 1);
            output("`2The gold coins echo loudly as they fall into the cup.");
            output("The ferryman reaches out to a long pole.");
            output("Bony fingers grasp the pole and drive it deep into the water.");
            output("The ferry pushes off across the river.`n`n");
            output("About halfway across, the ferryman turns to you.");
            output("You see green glowing eyes shining from within the hood.`n`n");
            // Drop through gracefully to below to avoid a meaningless click.
            $op = "continueferry";
            httpset("op", $op);
        }
    } elseif ($op == "dontpayferry") {
        output("`2You get into the ferry without paying.");
        output("The ferryman waits for a short moment and then reaches out to a long pole.");
        output("Bony fingers grasp the pole and drive it deep into the water.");
        output("The ferry pushes off across the river.`n`n");
        output("About halfway across, the ferryman turns to you.");
        output("You see green glowing eyes shining from within the hood.`n`n");
        if ($session['user']['gold'] >= $highferrycost) {
            output("`n`nHe reaches out and points a bony finger at the cup. You hear a voice with a commanding tone demanding that you now pay `@%s `2gold.", $highferrycost);
            addnav("The Ferryman");
            addnav(array("Pay %s Gold", $highferrycost), $from . "op=payferrymore");
            addnav("Don't Pay", $from . "op=continueferry");
        } else {
            // Drop through below
            $op = "continueferry";
            httpset("op", $op);
        }
    }
    // Handle these ops seperately so we can drop out of the code above.
    if ($op == "continueferry" || $op == "payferrymore") {
        if ($op == "payferrymore") {
            $session['user']['gold'] -= $highferrycost;
            debuglog("paid {$highferrycost} to ferryman");
            set_module_pref("paidferry", 1);
        }
        // slightly better chance of a good outcome if paid
        if (get_module_pref("paidferry")) {
            $randferry = e_rand(1, 18);
        } else {
            $randferry = e_rand(1, 9);
        }
        switch ($randferry) {
            case 1:
                // nothing interesting happens
            // nothing interesting happens
            case 10:
            case 14:
            case 18:
                output("`2After peering at you for a moment, the ferryman turns back and resumes poling.");
                output("A short time later, you reach the other shore.`n`n");
                output("The ferryman waits patiently as you disembark and return to the forest.");
                break;
            case 2:
                // gain a short defensive buff
            // gain a short defensive buff
            case 11:
            case 15:
                output("`2A voice emanates from the figure and asks you how your fights in the forest have been going.");
                output("Surprised, you tell the ferryman about your day.");
                output("When you finish, he breaks into a song about you.");
                output("The song lifts your spirits and you arrive at the opposite riverbank without further incident.`n`n");
                output("`&You feel uplifted!");
                $ferrybuffrounds = e_rand(10, 15);
                $ferrybuff = array("name" => "`&Ferryman's Song", "rounds" => $ferrybuffrounds, "wearoff" => "`7The effects of the ferryman's song fade into memory.", "defmod" => 1.2, "atkmod" => 1.0, "roundmsg" => "`7You feel uplifted as you hum the ferryman's song!", "schema" => "module-ferryman");
                apply_buff("ferrymanbuff", $ferrybuff);
                $session['user']['specialinc'] = "";
                break;
            case 3:
                // gain a small amount of gold or gems
            // gain a small amount of gold or gems
            case 12:
            case 16:
                output("`2He peers at you for a moment, then turns back and continues to the other shore.");
                output("As you climb out of the boat, you notice an extra small leather pouch on your person!`n`n");
                $reward = e_rand(0, 100);
                if ($reward > $gaingemchance) {
                    $rewardamt = e_rand(10, 40);
                    $session['user']['gold'] += $rewardamt;
                    $rewardcol = "`^";
                    $rewardtype = "gold";
                } else {
                    $rewardamt = round(e_rand(1, 3), 0);
                    $session['user']['gems'] += $rewardamt;
                    $rewardcol = "`%";
                    if ($rewardamt == 1) {
                        $rewardtype = "gem";
                    } else {
                        $rewardtype = "gems";
                    }
                }
                $rewardstr = "{$rewardamt} {$rewardtype}";
                output("`&You have gained %s%s %s`&!", $rewardcol, $rewardamt, translate_inline($rewardtype));
                debuglog("gained {$rewardstr} from ferryman");
                $session['user']['specialinc'] = "";
                break;
            case 4:
                // gain a forest fight
            // gain a forest fight
            case 13:
            case 17:
                output("`2The eyes seem to look straight into your mind.");
                output("Unable to turn away, you feel yourself slipping into a trance.");
                output("As you approach the shore, you snap out of the trance and feel refreshed.");
                output("`&You gain some Stamina!");
                $session['user']['turns']++;
                $session['user']['specialinc'] = "";
                break;
            case 5:
                // fall out of the boat
                output("`2The ferryman starts moving towards you.");
                output("Suddenly, something hits the boat, sending you into the river!");
                addnav("The Ferryman");
                addnav("Swim for the Shore", $from . "op=swim");
                addnav("Climb Back In", $from . "op=climb");
                break;
            case 6:
                // lose some gold, gems, or HP
                output("`2Looking at the eyes, you find that you are unable to tear away your gaze from the hypnotic stare.`n`n");
                output("And then, darkness.`n`n");
                output("A short time later, you awaken.");
                output("You seem to have washed up on the other shore.");
                output("Not knowing exactly what happened, you decide it would best if you were to quickly leave this place.`n`n");
                $randloss = e_rand(1, 3);
                if ($randloss == 1 && $session['user']['gold'] > 0) {
                    $lostgold = round($session['user']['gold'] * $losegoldpercent / 100, 0);
                    output("`&In your haste, you drop `^%s gold`&!", $lostgold);
                    $session['user']['gold'] -= $lostgold;
                    debuglog("lost {$lostgold} gold from ferryman");
                } elseif ($randloss == 2 && $session['user']['gems'] > 0) {
                    $hasgems = $session['user']['gems'];
                    $lostgems = e_rand(1, $losegemamount);
                    if ($hasgems < $lostgems) {
                        output("`&In your haste, you drop all your gems!");
                        debuglog("lost {$hasgems} from ferryman");
                        $session['user']['gems'] = 0;
                    } else {
                        output("`&In your haste, you drop `%%s %s`&!", $lostgems, translate_inline($lostgems == 1 ? "gem" : "gems"));
                        $session['user']['gems'] -= $lostgems;
                        debuglog("lost {$lostgems} gems from ferryman");
                    }
                } else {
                    $losthp = round($session['user']['hitpoints'] * $losehppercent / 100, 0);
                    output("`&In your haste, you trip and do `\$%s %s of damage`& to yourself!", $losthp, translate_inline($losthp == 1 ? "point" : "points"));
                    $session['user']['hitpoints'] -= $losthp;
                }
                $session['user']['specialinc'] = "";
                break;
            case 7:
                // end up in underworld, gain some favor
                output("`2A dense fog rolls in out of nowhere and envelops the boat.");
                output("The bony hand of the ferryman reaches out and grasps your arm with a firm grip.");
                output("After a moment, the fog clears, only to be replaced with darkness.");
                output("As the ferryman steers toward the shore, you notice a figure standing there.");
                output("You suddenly realize that you have been ferried across the River Styx to the land of the dead!`n`n");
                output("%s`2 bids you welcome and seems pleased with your arrival.`n`n", getsetting("deathoverlord", '`$Ramius'));
                output("`&Because you have been physically transported to the underworld, you still have your gold.");
                addnav("Daily News", "news.php");
                addnews("`%%s `7was last seen aboard a small boat.`0", $session['user']['name']);
                $favorgain = e_rand(1, $maxfavorgain);
                $session['user']['alive'] = false;
                $session['user']['hitpoints'] = 0;
                $session['user']['deathpower'] += $favorgain;
                $session['user']['specialinc'] = "";
                break;
            case 8:
                // fight the ferryman!
                output("`2He seems to think for a moment, then turns back and resumes poling.");
                output("You relax and turn your attention back to the waters.`n`n");
                output("`2Suddenly, you hear a sharp whistling sound.");
                output("Looking up, you see the ferryman's pole swinging towards your head!");
                output("Quickly ducking, you manage to dodge the blow, but the ferryman starts swinging again!");
                addnav("The Ferryman");
                addnav("Duck and Fight", $from . "op=fightferryman");
                addnav("Duck and Run", $from . "op=fleeferryman");
                break;
            case 9:
                // ferryman hits them
                output("`2The ferryman starts moving towards you.");
                output("You start to edge away from him and he swings his ferry pole at you!");
                output("Not having much room to maneuver, he delivers a painful blow!`n`n");
                $randdmg = e_rand(2, round($session['user']['hitpoints'] / 2, 0));
                $session['user']['hitpoints'] -= $randdmg;
                output("`&You were struck for `\$%s %s of damage`&!`n`n", $randdmg, translate_inline($randdmg == 1 ? "point" : "points"));
                if ($session['user']['hitpoints'] <= 0) {
                    output("`n`&You have died!");
                    $lostgold = $session['user']['gold'];
                    $session['user']['alive'] = false;
                    $session['user']['hitpoints'] = 0;
                    $session['user']['gold'] = 0;
                    debuglog("lost {$lostgold} gold from dying at ferryman");
                    addnav("Daily News", "news.php");
                    addnews("`%%s `7was last seen aboard a small boat.`0", $session['user']['name']);
                } else {
                    output("`2You let out a yelp of pain and ready yourself to block another blow.");
                    output("Seemingly satisfied, the ferryman turns back and resumes poling.");
                    output("Rubbing the painful welt, you reach the other shore and decide to quickly get away from the ferryman.`n`n");
                }
                $session['user']['specialinc'] = "";
                break;
        }
    } elseif ($op == "swim" || $op == "climb") {
        if ($op == "swim") {
            output("`2You try swimming for the shore, but the weight of your gear prevents you from making much progress.");
        } else {
            output("`2You try to climb back in, but the weight of your gear prevents you from making much progress.");
        }
        $randdrown = e_rand(1, 100);
        if ($randdrown < $drownchance) {
            output("As you thrash about in the water, you notice the ferryman looking over at you from the boat.");
            output("A haunting sound drifts to you from the boat and you realize that the ferryman is laughing at your plight.");
            output("As you sink into the murky depths of the river, you hear naught but the ferryman's laughter echoing in your ears.`n`n");
            output("`&You have died!");
            $lostgold = $session['user']['gold'];
            $session['user']['alive'] = false;
            $session['user']['hitpoints'] = 0;
            $session['user']['gold'] = 0;
            debuglog("lost {$lostgold} gold from dying at ferryman");
            addnav("Daily News", "news.php");
            addnews("`%%s `7was last seen aboard a small boat.`0", $session['user']['name']);
        } else {
            output("`2The ferryman extends his pole to you and helps you back onboard.`n`n");
            output("Thankfully, the rest of the journey passes without incident and you arrive on the other shore.");
            output("The ordeal has left you intact, though a little tired.");
            if ($session['user']['turns'] > 0) {
                output("`n`n`&You have lost some Stamina!");
                $session['user']['turns']--;
            }
        }
        $session['user']['specialinc'] = "";
    } elseif ($op == "fightferryman" || $op == "fight" || $op == "run") {
        ferryman_fight();
    } elseif ($op == "fleeferryman") {
        output("`2You dodge the second blow and turn to run.");
        output("Looking at the murky waters all around, you realize you have nowhere to run and turn to face the ferryman!");
        addnav("The Ferryman");
        addnav("Fight", $from . "op=fightferryman");
    } elseif ($op == "ignoreferryman") {
        output("`2You decide to ignore the cloaked figure and return to the forest.");
        $session['user']['specialinc'] = "";
    } elseif ($op == "leaveferryman") {
        output("`2You decide not to take the ferryman's offer and return to the forest.");
        $session['user']['specialinc'] = "";
    }
    output("`0");
}
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 racekittymorph_dohook($hookname, $args)
{
    global $session, $resline;
    $city = "Kittania";
    $race = "Kittymorph";
    switch ($hookname) {
        case "racenames":
            $args[$race] = $race;
            break;
        case "changesetting":
            // Ignore anything other than villagename setting changes
            if ($args['setting'] == "villagename" && $args['module'] == "racekittymorph") {
                if ($session['user']['location'] == $args['old']) {
                    $session['user']['location'] = $args['new'];
                }
                $sql = "UPDATE " . db_prefix("accounts") . " SET location='" . addslashes($args['new']) . "' WHERE location='" . addslashes($args['old']) . "'";
                db_query($sql);
                if (is_module_active("cities")) {
                    $sql = "UPDATE " . db_prefix("module_userprefs") . " SET value='" . addslashes($args['new']) . "' WHERE modulename='cities' AND setting='homecity'" . "AND value='" . addslashes($args['old']) . "'";
                    db_query($sql);
                }
            }
            break;
        case "chooserace":
            if ($session['user']['dragonkills'] == 0) {
                break;
            }
            output("`0You smile, and turn around to show the gatekeeper your tail.  <a href='newday.php?setrace={$race}{$resline}'>\"Um... notice anything unusual?\"</a>`n`n", true);
            addnav("`&Kittymorph`0", "newday.php?setrace={$race}{$resline}");
            addnav("", "newday.php?setrace={$race}{$resline}");
            break;
        case "setrace":
            if ($session['user']['race'] == $race) {
                output("\"`6Oh, I see, right,`0\" says the gatekeeper, looking down at his ledger.  \"`6A kittymorph, then, okay, let's see, here...  Kay, eye, tee, ee, em, oh, are, eff.  Kittymorph.`0\"  He looks up again.  \"`6Um.  You can turn around again, now.`0\"`n`nYou oblige.  \"`#Sorry.`0\"`n`n\"`6Don't worry about it.  Have you always been like this?`0\"`n`n\"`#Since I was a kitten,`0\" you reply.  \"`#I don't know what that crazy woman back there was talking about; she says I fell out of a plane and hit my head.  Rubbish.`0\"`n`n\"`6Of course,`0\" says the gatekeeper, smiling.  \"`6You would have landed on your feet, wouldn't you?`0\"`n`n\"`#That's right.  Although...`0\"  You look down, puzzled.  \"`#Some things just don't add up...`0\" you mutter.`n`n\"`6Well, don't worry,`0\" says the gatekeeper.  \"`6Just head into town and get some nice clothes, and you'll sort everything out, I'm sure.  If you wear clothes, that is.`0\"`n`nYou grin.  \"`#When it suits me.`0\"  You saunter off through the gates.  You don't really know how to walk any other way.");
                if (is_module_active("cities")) {
                    set_module_pref("homecity", $city, "cities");
                    if ($session['user']['age'] == 0) {
                        $session['user']['location'] = $city;
                    }
                }
            }
            break;
        case "alternativeresurrect":
        case "stamina-newday":
            if ($session['user']['race'] == $race) {
                racekittymorph_checkcity();
                //Stamina buffs
                require_once "modules/staminasystem/lib/lib.php";
                apply_stamina_buff('kittymorph3', array("name" => "KittyMorph Bonus: Travelling Speed", "class" => "Travelling", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph4', array("name" => "KittyMorph Bonus: Cooking and Carcass Cleaning Expertise", "class" => "Meat", "costmod" => 0.7, "expmod" => 1.2, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph1', array("name" => "KittyMorph Penalty: Hunting Indifference", "class" => "Hunting", "costmod" => 1.1, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph2', array("name" => "KittyMorph Penalty: Combat Indifference", "class" => "Combat", "costmod" => 1.1, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph5', array("name" => "KittyMorph Penalty: Technical Ineptitude", "class" => "ScrapBots", "costmod" => 1.1, "expmod" => 0.8, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('raceclassy', array("name" => "KittyMorph Bonus: Classy Insults Proficiency", "action" => "Insults - Classy", "costmod" => 0.9, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('raceconfusing', array("name" => "KittyMorph Bonus: Confusing Insults Proficiency", "action" => "Insults - Confusing", "costmod" => 0.5, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                //combat buffs
                apply_buff("racialbenefit1", array("name" => "`7KittyMorph Penalty: Slender`0", "defmod" => "0.8", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racekittymorph"));
                apply_buff("racialbenefit2", array("name" => "`7KittyMorph Bonus: Claws`0", "atkmod" => "1.2", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racekittymorph"));
            }
            break;
        case "creatureencounter":
            if ($session['user']['race'] == $race) {
                //get those folks who haven't manually chosen a race
                racekittymorph_checkcity();
                if ($session['user']['armordef'] == 0) {
                    apply_buff("nudekitty", array("name" => "`7KittyMorph Bonus: Nude Fighting`0", "badguyatkmod" => 0.7, "badguydefmod" => 0.7, "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "roundmsg" => "Because you are fighting completely starkers, {badguy} is hilariously distracted and cannot attack or defend as effectively!", "expireafterfight" => 1, "schema" => "module-racekittymorph"));
                }
            }
            break;
        case "battle-victory":
            if ($session['user']['race'] == $race) {
                if (!$session['user']['alive']) {
                    debug($args['creatureexp']);
                    $args['creatureexp'] = round($args['creatureexp'] * 1.3);
                    debug($args['creatureexp']);
                }
            }
            break;
        case "validforestloc":
        case "validlocation":
            if (is_module_active("cities")) {
                $args[$city] = "village-{$race}";
            }
            break;
        case "moderate":
            if (is_module_active("cities")) {
                tlschema("commentary");
                $args["village-{$race}"] = sprintf_translate("City of %s", $city);
                tlschema();
            }
            break;
        case "villagetext":
            racekittymorph_checkcity();
            if ($session['user']['location'] == $city) {
                $args['text'] = array("`0You are standing in the heart of Kittania.  Though officially registered as a city, it only earned that title because there were so many sentient creatures living there.`n`nIn reality, the city is a very basic affair, little more than a pack living together in common conditions.  Kittymorphs are a little too lazy to build much.`n");
                $args['schemas']['text'] = "module-racekittymorph";
                $args['clock'] = "`n`0From the position of the sun in the sky, you reckon it's about `&%s`0.`n";
                $args['schemas']['clock'] = "module-racekittymorph";
                if (is_module_active("calendar")) {
                    $args['calendar'] = "`n`0Scrawled in dust on the floor is the current date, `&%s`0, `&%s %s %s`0.`n";
                    $args['schemas']['calendar'] = "module-racekittymorph";
                }
                $args['title'] = array("%s, Home of the Kittymorphs", $city);
                $args['schemas']['title'] = "module-racekittymorph";
                $args['sayline'] = "says";
                $args['schemas']['sayline'] = "module-racekittymorph";
                $args['talk'] = "`n`&Nearby some kittymorphs talk:`n";
                $args['schemas']['talk'] = "module-racekittymorph";
                $new = get_module_setting("newest-{$city}", "cities");
                if ($new != 0) {
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$new}'";
                    $result = db_query_cached($sql, "newest-{$city}");
                    $row = db_fetch_assoc($result);
                    $args['newestplayer'] = $row['name'];
                    $args['newestid'] = $new;
                } else {
                    $args['newestplayer'] = $new;
                    $args['newestid'] = "";
                }
                if ($new == $session['user']['acctid']) {
                    $args['newest'] = "`n`0As you wander your new home, you feel your jaw dropping at the wonderful smells around you.";
                } else {
                    $args['newest'] = "`n`0Wandering the village, jaw agape and buck naked, is `&%s`0.";
                }
                $args['schemas']['newest'] = "module-racekittymorph";
                $args['section'] = "village-{$race}";
                $args['stablename'] = "Mike's Chop Shop";
                $args['schemas']['stablename'] = "module-racekittymorph";
                $args['gatenav'] = "Outpost Gates";
                $args['fightnav'] = "Toothclaw Close";
                $args['marketnav'] = "The Cul-De-Sac of Sparkly Things";
                $args['tavernnav'] = "Distraction Avenue";
                $args['schemas']['gatenav'] = "module-racekittymorph";
                unblocknav("stables.php");
            }
            break;
        case "stablelocs":
            tlschema("mounts");
            $args[$city] = sprintf_translate("The Village of %s", $city);
            tlschema();
            break;
        case "stabletext":
            if ($session['user']['location'] != $city) {
                break;
            }
            $args['title'] = "Mike's Chop Shop";
            $args['schemas']['title'] = "module-racekittymorph";
            $args['desc'] = array("`6Just next door to the Clan Halls, a rather basic-looking set of stables has been erected.`n`n", array("As you head inside, you notice an obvious lack of the typical stable smell.  Apparently KittyMorphs, for all their laziness, like to keep things clean.`n`n\"`^Well hello there!  What can I do for you, my good %s?`6\" asks a grey-furred KittyMorph male whose name you're absolutely `icertain`i is not \"Mike.\"", translate_inline($session['user']['sex'] ? 'lady' : 'man', 'stables')));
            $args['schemas']['desc'] = "module-racekittymorph";
            $args['lad'] = "friend";
            $args['schemas']['lad'] = "module-racekittymorph";
            $args['lass'] = "friend";
            $args['schemas']['lass'] = "module-racekittymorph";
            $args['nosuchbeast'] = "`6\"`^Hmm.  Not heard of that one,`6\" Mike says apologetically.";
            $args['schemas']['nosuchbeast'] = "module-racekittymorph";
            $args['toolittle'] = "`6Mike looks over the handful of currency you offered.  \"`^Aha.  Well, the price for this %s, you see, was actually `&%s `^Requisition  and `%%s`^ cigarettes.  Maybe you miscounted?`6\"";
            $args['schemas']['toolittle'] = "module-racekittymorph";
            $args['replacemount'] = "`6You sadly watch Mike lead your %s`6 away, along with your cigarettes.  However, when he returns, he brings with him a nice new `&%s`6 which makes you feel a little better.";
            $args['schemas']['replacemount'] = "module-racekittymorph";
            $args['newmount'] = "`6You hand over your currency.  Within moments, you become the proud recipient of a lovely new `&%s`6!";
            $args['schemas']['newmount'] = "module-racekittymorph";
            $args['confirmsale'] = "`n`n`6Mike eyes your mount up and down, checking it over carefully.  \"`^Yes, yes, that's a really nice example, right there - are you quite sure you want to part with it?`6\"";
            $args['schemas']['confirmsale'] = "module-racekittymorph";
            $args['mountsold'] = "`6With but a single tear, you hand your %s`6 over to Mike.  The tear dries quickly, and the %s in hand helps you quickly overcome your sorrow.";
            $args['schemas']['mountsold'] = "module-racekittymorph";
            $args['offer'] = "`n`n`6Mike offers you `&%s`6 Requisition and `%%s`6 Cigarettes for %s`6.";
            $args['schemas']['offer'] = "module-racekittymorph";
            break;
    }
    return $args;
}
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();
}
	$bexp = floor(($row['brewexp'])/1000)+1;
	$brewprice = 10 * ($bexp + $drinkqual) * $session['user']['level'];	
	$session['user']['gold']-=$brewprice;
	
	output("`2You drink a frosty ale and seem to win enough courage to draw your weapon and fight everything in your way.`n`n");
	
	if($row['alerounds']==0)
		$rounds=1;
	else
		$rounds = ($row['alerounds'] * 2) * ($bexp + $drinkqual);
	
	apply_buff('User Inn Ale',
		array(
			"name"=>array("`5%s",$row['brewname']),
			"rounds"=>$rounds,
			"defmod"=>(($row['aledefense'] / 100) * ($bexp + $drinkqual)) + 0.95,
			"atkmod"=>(($row['aleattack'] / 50) * ($bexp + $drinkqual)) + 0.9,
			"roundmsg"=>array("`2The %s`2 you drank gives you enough courage to take on the whole world. Attack!!!",$row['brewname']),
			"schema"=>"module-dwinns",
		)
	);
	
	$sql = "UPDATE " . db_prefix("dwinns") . " SET logdrinks=logdrinks+$brewprice, drinks=drinks-1, statdrinksprofit=statdrinksprofit+$brewprice, statdrinks=statdrinks+1 WHERE dwid='$dwid'";
	db_query($sql);
		
	$drunk = get_module_pref("drunkeness","drinks");
	if($drunk < 0 || $drunk == "")
		$drunk = 0;
	$drunk += get_module_setting("aledrunk");
	set_module_pref("drunkeness",$drunk,"drinks");
	set_module_pref("harddrinks",get_module_pref("harddrinks","drinks")+1,"drinks");
	
function crying_runevent($type)
{
    global $session;
    $innname = getsetting("innname", LOCATION_INN);
    $op = httpget('op');
    $session['user']['specialinc'] = "module:crying";
    $from = "inn.php?";
    require_once "lib/partner.php";
    $partner = get_partner();
    if ($op == "") {
        output("`7As you are standing in %s, minding your own business, a woman begins to sob loudly.", $innname);
        output("You watch as she walks away from %s`7 and over to where her husband is sitting, crying, \"I lost it, and now HE has lost it too! We shall never afford another ring as beautiful as that one!\"`n`n", getsetting("barkeep", "`tCedrik"));
        output("You watch her as she wrings her hands and cries inconsolably.`n`n");
        output("Your hand strays to the piece of jewelry in your pocket, and you wonder whether you should return the ring to her.");
        output("After all, it might be very valuable, and perhaps you could sell it for gems.");
        output("You struggle with your conscience, wondering what to do.");
        set_module_pref("seentoday", 1);
        addnav("Return the Ring", $from . "op=give");
        addnav("Ignore the Lady", $from . "op=ignore");
        page_footer();
    } elseif ($op == "give") {
        set_module_pref("ring", 0, "breakin");
        $whathappens = e_rand(1, 5);
        output("You approach the lady and gently touch her shoulder.");
        output("As she turns around and faces you with teary eyes, you extend your hand and offer the ring.`n`n");
        output("Her eyes become saucers, and she grabs the ring in gratitude, before throwing her arms about you in ecstatic gratitude.`n`n");
        output("`&\"You are indeed a warrior of true noble heart! Please, accept this gift of my gratitude, and wear it with pride!\"");
        output("`7She grabs your wrist, and around it ties a leather band that carries a tiger's tooth.");
        output("You're a little hesitant to accept such a strange gift, but you don't want to offend her, so you thank her and walk away from her table.");
        set_module_pref("hasbracelet", 1);
        $upmatt = get_module_pref("upmatt");
        // need to check if matthias module exists on this server, and only award astute once
        if (is_module_active("matthias") && $upmatt == 0) {
            $astute = get_module_pref("astuteness", "matthias");
            $astute += 2;
            set_module_pref("astuteness", $astute, "matthias");
            set_module_pref("upmatt", 1);
        }
        if ($whathappens <= 2) {
            // Seth/Violet sees and approves
            output("`n`nFrom the other side of the room, %s`7 is watching.`n`n", $partner);
            if ($session['user']['sex'] == SEX_MALE) {
                output("She beams at you for your kindheartedness.`n`n");
            } else {
                output("He beams at you for your kindheartedness.`n`n");
            }
            output("`&You gain a charm point!");
            $session['user']['charm']++;
        } elseif ($whathappens == 3) {
            // Seth/Violet sees and disapproves
            output("`n`nFrom the other side of the room, %s`7 is watching.`n`n", $partner);
            if ($session['user']['sex'] == SEX_MALE) {
                output("She glares at you in jealous anger.`n`n");
            } else {
                output("He glares at you in jealous anger.`n`n");
            }
            output("You `4lose`7 a charm point!");
            if ($session['user']['charm'] > 0) {
                $session['user']['charm']--;
            }
        } elseif ($whathappens >= 4) {
            output("You are so tremendously happy at her reaction, that you feel fantastic!");
            // gain feelgood vibes (buff)
            apply_buff('feelgood', array("name" => "`%Feelgood Vibes", "rounds" => 15, "wearoff" => "You feel normal again.", "atkmod" => 1.05, "roundmsg" => "Your positivity helps you hit harder!", "schema" => "module-crying"));
        }
        $session['user']['specialinc'] = "";
    } elseif ($op == "ignore") {
        output("`n`7The lady is still sobbing, but hey, you're a heartless warrior, and you don't care. Right?`n");
        $session['user']['specialinc'] = "";
    }
}