<?php
/*
 * rowbutt(number, playing style, attack troop, level)
 *
 * number: the warlord # of the currently selected NPC
 * playing style: casher, farmer
 * attack troop:  the main attack troop
 * level: not currently used, will later determine NPC 'toughness'
 *
 */
function rowbutt($num$playstyle$maintroop$npclevel){
    global 
$config$cterms$trplst$prdlst$tplst$time$warflag$turnout$playerdb;
    global 
$users$urace$uera$landgained$cashgained$foodgained$runesgained;
    global 
$condenseoutput$netincomeneg$netfoodneg$netleaderneg$networkerneg;
    global 
$usent$esent$uloss$eloss;
    global 
$targetlist;
    global 
$playstyle$maintroop;

    
$admin 0;    
    
$suid 0;    
    
$urace loadRace($users[race]);
    
$uera loadEra($users[era]);
    
$ctags loadClanTags();
    
$rtags loadRaceTags();
    
$etags loadEraTags();
    
$targetlist "";
    
reset($trplst);
    while (list(
$key$trp) = each($trplst)) {
        print 
"user troop $trp$usent[$trp]    enemy $trp$esent[$trp]   user loss $trp$uloss[$trp]    enemy $trp$eloss[$trp]<br>";
        
$usent[$trp] = $esent[$trp] = $uloss[$trp] = $eloss[$trp] = 0;
    }
    
$attacktax 20//tax rate while attacking
    
$cashtax 42//tax while cashing or foraging
    
if($playstyle == "casher"){
        
npcMarket(buyfoodall);
        
npcEco(1000);
        
$npcdowhat cash;
    }
    if(
$playstyle == "farmer"){
        
npcMarket(sellfoodall); //doesn't really sell all its food
        
npcEco(0100);
        
$npcdowhat food;
    }

    
//Run first run
    
if($users[turnsused] < 550){
        
npcTax($cashtax);
        
npcResourceCheck(550);
        
npcDo(land0550);
        print 
"$users[empire] scouted for 550 $cterms[turns]<br>";
    }else{
        
//Set tax
        
npcTax($attacktax);
        
//Nuke unneeded army
        
if($maintroop != "lndtrp")
            
npcMarket(selllndtrpall);
        if(
$maintroop != "flytrp")
            
npcMarket(sellflytrpall);
        if(
$maintroop != "seatrp")
            
npcMarket(sellseatrpall);
        if(
$maintroop != "armtrp")
            
npcMarket(sellarmtrpall);
        
sleep(10); //TEMP SLEEP
        //Got money off the market?  woot!    
        
if($users[savings] > 0){
            
$users[cash] += $users[savings];
            
$users[savings] = 0;
        }
        
//Got a loan?  Pay it.
        
if($users[loan] > 0){
            if(
$users[cash] > $users[loan]){
                
$users[cash] -= $users[loan];
                
$users[loan] = 0;
            }
        }
        
//Recovery Mode
        
if($users[land] < 1000){
            
npcMarket(sell$maintroopall);
            
npcDo(land1350);
        }
        
npcResourceCheck(0); //Checks for 0 cash / food to begin with, should never happen ideally
        //Begin Main Run
        //Check health
        
if (($users[health] < $maxhealth) && ($users[health] < 100))
            
npcDo(heal10);
        
//Clear out unwanted buildings
        
npcBuild(beginrun,$playstyle);
        
//Build in the style intended for running
        
npcBuild(attack$playstyle);
        
//Buy main troop type
        
$amount round($config[$maintroop][prod] * .20 $users[networth]);
        if(
$users[$maintroop] < $amount){
            
$previous $users[$maintroop];
            
npcMarket(buy$maintroop$amount $previous);
            
$bought $users[$maintroop] - $previous;
            print 
"Bought $uera[$maintroop]:  Had: $previous, Ideal: $amount, Bought: $bought<br>";
        }else{
            print 
"Didn't buy any $uera[$maintroop]:  Had: $users[$maintroop], Ideal: $amount<br>";
        }
        print 
"TURN USE - Prior to attack run:  $users[turns]";
        
//Begin attack run
        
print "Begin attack";
        while(
$users[turns]>300){
            
$npcrandom rand(1,5);
            if(
$npcrandom == 1)
                
npcDo(runes025);
            if(
$npcrandom 1){
                print 
"Entering npcAttack function using $maintroop";
                
npcAttack($maintroop5);
            }
            
$amount round($config[$maintroop][prod] * .20 $users[networth]);
            if(
$users[$maintroop] < $amount){
                
$previous $users[$maintroop];
                
npcMarket(buy$maintroop$amount $previous);
                
$bought $users[$maintroop] - $previous;
                print 
"While attacking, Bought $uera[$maintroop]:  Had: $previous, Ideal: $amount, Bought: $bought<br>";
            }

        }
        print 
"TURN USE - After attack run:  $users[turns]";
        
npcMarket(sell$maintroopall);
        
npcDo(heal10);
        
npcTax($cashtax);
        print 
"TURN USE - Prior to cashing:  $users[turns]";
        
//Reset Eco settings incase they'd been changed earlier in the run
        
if($playstyle == "casher"){
            
npcEco(1000);
        }
        if(
$playstyle == "farmer"){
            
npcEco(0100);
        }
        
//Determine number of turns we need to leave for the last two builds
        
$buildrate $users[land] * 0.015 4;
        
$buildrate round($urace[bpt] * $buildrate);
        
$destroyrate round(($users[land] * 0.02) + 2);
        
$destroyrate floor($urace[bpt] * $destroyrate);
        if(
$playstyle == "casher"){
            
$yesbuild "shops";
            
$nobuild "farms";
        }
        if(
$playstyle == "farmer"){
            
$yesbuild "farms";
            
$nobuild "shops";
        }
        
//the amount of markets/farms ($yesbuild) is first halved to make tents, then those are destroyed to make towers
        //So build / destroy are each a $yesbuild 
        
$howmany ceil($users[$yesbuild] / $buildrate) + ceil($users[$yesbuild] / $destroyrate);
        print 
"Saving Turns for Build:  $howmany";
        
$loopcount 10;
        while(
$users[turns] - $howmany >=  20 && $loopcount 0){  
            
npcDo($npcdowhat020);    
            
$loopcount -= 1;  //emergency loop break 'cause while loops scare me
        
}
        print 
"TURN USE - After cashing:  $users[turns]";
        
npcBuild(midrun$playstyle);
        print 
"TURN USE - After building for mercs buy:  $users[turns]";
        if (
$playstyle == "farmer"npcMarket(sellfoodround($users[food] * 0.9));
        
npcMarket(buyendrunall);
        
npcBuild(endrun$playstyle); //the endrun build now checks if the resources required are availible, if not it aborts
        
print "TURN USE - After building final structures:  $users[turns]";
    }
    
    
}

/*
 * npcDo(type, 0 = do exact / 1 = do until, turns )
 * cash, food, runes, land, 
 * heal, workers
 * war
 */
function npcDo($dotype$dountil$doturns){
    global 
$config$cterms;
    global 
$users$landgained$cashgained$foodgained$runesgained;
    global 
$condenseoutput;
    global 
$playstyle$maintroop;
    
    
sleep(10);  //PAUSE 10 seconds to setup turns
    
$users[online] = 1;
    
npcResourceCheck($doturns);

    
$condenseoutput "hidden";
    
$landgained 0;
    
$cashgained 0;
    
$foodgained 0;
    
$runesgained 0;
    
$priorturns $users[turns];
    
    if(
$dountil == 1){
        if(
$dotype == "heal"){
            print 
"Calculating Turns Health: $priorturns$doturns : ";
            
$doturns round((100 $users[health])/2);
            print 
"$doturns<br>";
        }else{    
            print 
"Calculating Turns: $priorturns$doturns : ";
            
$doturns $users[turns] - $doturns;
            print 
"$users[turns] are left, attempting to use $doturns<br>";
        }
    }
    
    if(
$doturns <= 0){
        print 
"Out of Turns!  Was trying to run $dotype <br>";
        
$dotype "";
    }
        
    if(
$dotype == "cash"){
        print 
"WE ARE ABOUT TO CASH DAMMIT $users[turns] : $doturns<br>";
        
$ecobuff "cashinc";
        
$bufflist[ecobuff] = $ecobuff;
        
$turns takeBuffTurns($doturns,0,$bufflist);    
        print 
"$users[empire] gained ".commas($cashgained).$cterms[cash] in $turns $cterms[turns]<br>";
        print 
"WE JUST CASHED DAMMIT $users[turns]<br>";
    }
    
    if(
$dotype == "food"){
        
$ecobuff "foodinc";
        
$bufflist[ecobuff] = $ecobuff;
        
$turns takeBuffTurns($doturns,0,$bufflist);    
        print 
"$users[empire] gained ".commas($foodgained).$cterms[food] in $doturns $cterms[turns]<br>";
    }
    
    if(
$dotype == "runes"){
        
takeTurns($doturnsrunes);    
        print 
"$users[empire] gained ".commas($runesgained).$uera[runes] in $doturns $cterms[turns]<br>";
    }
    
    if(
$dotype == "heal"){
        
$warbuff "heal";
        
$bufflist[warbuff] = $warbuff;    
        
$turns takeBuffTurns($doturns,0,$bufflist);    
        if(
$users[health] != 100){
            
$oldtax $users[tax];
            
npcTax(11);
            
$doturns += 100-$users[health];
            
$turns += takeTurns(100 $users[health], runes);
            print 
"$users[empire] gained ".commas($runesgained).$uera[runes] in $turns $cterms[turns]<br>";
            
npcTax($oldtax);
        }
        print 
"$users[empire] returned to full health in $turns $cterms[turns]<br>";
    }
    
    if(
$dotype == "workers"){
        
$indybuff "workers";
        
$bufflist[indybuff] = $indybuff;
        
$turns takeBuffTurns($doturns,0,$bufflist);    
        print 
"$users[empire] gained 'some' $cterms[workers] in $turns $cterms[turns]<br>";        
    }
    
    if(
$dotype == "land"){
        
$turns takeTurns($doturns,land);
        print 
"$users[empire] gained ".commas($landgained).$cterms[acres] of $cterms[land] in $turns $cterms[turns]<br>";
    }
    if(
$priorturns $doturns $users[turns]){
        print 
"For some reason this is happening<br>";
        
$turns takeTurns($users[turns] - ($priorturns $doturns), runes);
        print 
"$users[empire] gained ".commas($runesgained).$uera[runes] in $turns $cterms[turns]<br>";
    }
}

/*
 *
 *
 */
function npcAttack($attacktype$amount){
    include_once(
"rmilitary.php");
    global 
$cterms$users$urace$uera$usent$enemy$erace$eera$esent$playerdb$datetime$time$trplst$warflag$config;
    global 
$theme$ulwiz$erace$uloss$eloss$act$debug$debug_uloss$debug_eloss$config$warflag;

    global 
$tplst$bldlst$landloss;
    global 
$condenseoutput;
    global 
$playstyle$maintroop;
    global 
$sendall$targetlist;
    
$condenseoutput "hidden";
    
    
$sendall 1;
    
    
reset($trplst);
    while (list(
$key$trp) = each($trplst)) {
        if ((
$uloss[$trp] > || $eloss[$trp] > 0) && $trp != $attacktype) print "At the start of npcattack: Extra troops are dying ($attacktype$trp): uloss = $uloss[$trp], eloss = $eloss[$trp]<br>";
    }

    
//self checks
    
if($users[turns] > && $users[cash] > && $users[food] > && $users[health] >= 8){
        
//send all of the troop type
        
$usent[$attacktype] = $users[$attacktype];
        
//find target 
        
$targetchosen 0;
        
$targettries 0;
        
$target 0;
        
$nplayers sqleval("SELECT COUNT(*) FROM $playerdb;");
        while(
$targetchosen == && $targettries <= 50){
            
$target rand(1,$nplayers);
            
$enemy loadUser($target);
            
$erace loadRace($enemy[race]);
            
$eera loadEra($enemy[era]);
            
$users[gate] = $time 1//prepared raiders, may do it 'right' later.
            //target checks
            
print " (" $target ") ";
            if ((!(
$enemy[land] == 0)) && (!($enemy[disabled] == 2)) && (!($enemy[disabled] == 3)) && (!($enemy[turnsused] <= $config[protection])) && (!($enemy[vacation] > $config[vacationdelay])) && (!($target == $users[num])) && ($enemy[attacks] <= $theme[attack_limit])){
                if (
$target == $users[num]) print "Why are you hitting yourself?<br>";
                
$attackedbefore strpos($targetlist"(" $target ")");
                print 
"Potential target: $target";
                if(
$attackedbefore === true)
                    print 
"I've attacked this chap before:  $target:  $targetlist";
                
$netmult 20;
                if(
$enemy[networth]*.0001 $enemy[land] && $attackedbefore === false && !($enemy[networth] > $users[networth] * $netmult) && !($users[networth] > $enemy[networth] * $netmult) && $enemy[online] != 1){
                    
$targetchosen 1;
                    
sleep(25);  //PAUSE for 25 seconds to find a target
                
}
            }
            
$targettries += 1;
        }
        
        if(
$targettries >= 50)
            print 
"Tried to find a target, no go; $nplayers<br> ";
        
$npcfail 0;
        
$targetlist .= "(" $target ")";
        
        while(
$npcfail == && $amount >= && $targettries <= 100 && $targetchosen == 1){
            
sleep(2);  //PAUSE two seconds between attacks
            
npcResourceCheck(2);
            print 
"Target:  $target <br>";
            
$users[online] = 1;
            
$landloss 0;
            
//begin attack
            //code borrowed from military.php
                    
            
if (($enemy[era] != $users[era]) && ($users[gate] <= $time) && ($enemy[gate] <= $time))
                print 
"Need to $cterms[praiders] first!";
            
//NEEDS TO BE ADDRESSED...  unlikely with the landfat check, but still.
            
if ($theme[standards] > 0) {
                if ((
$enemy[land]-($enemy[cities]*1000) <= $theme[standards]) && ($attacktype != 'Standard'))
                    print 
"<br>Whatcha tryin' to do, kill 'em?<br>Sorry, gotta use Standard attacks under $theme[standards] acres<br>(city land not included)<br>";
            }
        
            
$warflag 0;
            
$netmult 20;
        
            
$uclan loadClan($users[clan]);
        
            if (
$enemy[clan]) {
                
ClanCheck();
                
$eclan loadClan($enemy[clan]);
            }
        
            if (
$enemy[networth] > $users[networth] * $netmult)
                print 
"Your Generals flatly refuse to attack such a strong opponent!";
            if (
$users[networth] > $enemy[networth] * $netmult)
                print 
"Your Generals politely refuse your orders to attack a defenseless $cterms[warlord]!";
            

            
ReadInput($attacktype);
            
            
Attack($attacktype);
        
            if (!
$landloss)
                
$landloss 0;
            if(
$landloss == 0//the NPC attack failed!
                
$npcfail 1;
            else
                
$amount -= 1;  //otherwise, yay
            
$newsdata "";
            
$xlst array_merge($tplst, array("peasants""wizards""cash"));
            
reset($xlst);
            while (list(
$key$trp) = each($xlst)) {
                if ((
$uloss[$trp] > || $eloss[$trp] > 0) && $trp != $attacktype) print "Extra troops are dying<br>";
                
$users[$trp] -= $uloss[$trp];
                
$enemy[$trp] -= $eloss[$trp];
                if (
$users[$trp] < 0)
                    
$users[$trp] = 0;
                if (
$enemy[$trp] < 0)
                    
$enemy[$trp] = 0;
            }
            if (
$attacktype == "workers") {
                
$users[peasants] += $eloss[workers] * 0.95;
            }
            
reset($xlst);
            while (list(
$key$trp) = each($xlst)) {
                if (
$uloss[$trp] > 0)
                    
$newsdata .= ";o$trp:" $uloss[$trp];
                if (
$eloss[$trp] > 0)
                    
$newsdata .= ";d$trp:" $eloss[$trp];
            }
            
            
$newsdata substr($newsdata1);
            switch (
$attacktype) {
                case 
'Standard':addNewsLand(302$users$enemy$landloss"$newsdata");
                    break;
                case 
'Surprise':addNewsLand(303$users$enemy$landloss"$newsdata");
                    break;
                case 
'workers':addNewsLand(308$users$enemy$landloss"$newsdata");
                    break;
                case 
'armtrp':addNewsLand(304$users$enemy$landloss"$newsdata");
                    break;
                case 
'lndtrp':addNewsLand(305$users$enemy$landloss"$newsdata");
                    break;
                case 
'flytrp':addNewsLand(306$users$enemy$landloss"$newsdata");
                    break;
                case 
'seatrp':addNewsLand(307$users$enemy$landloss"$newsdata");
                    break;
            }
            if (
$enemy[land] == 0)
                
addNews(301$users$enemy0);
            
$users[attacks] -= 2;
            if (
$users[attacks] < 0)
                
$users[attacks] = 0;
            
$users[offtotal]++;
            
$enemy[deftotal]++;
            if (
$landloss)
                
$users[offsucc]++;
            else
                
$enemy[defsucc]++;
            
$users[health] -= $theme[attack_health] + 2// the plus 2 accounts for the health gained when taking turns    
            
saveUserDataNet($users"networth " implode(" "$xlst) . " land " implode(" "$bldlst) . " freeland offsucc offtotal attacks health kills peasants runes online");
            
saveUserDataNet($enemy"networth " implode(" "$xlst) . " land " implode(" "$bldlst) . " freeland defsucc deftotal attacks peasants runes health");
            
taketurns(2,attack);
            if (
$enemy[attacks] > $theme[attack_limit]){
                print 
"$enemy[num] is maxed, stopped attacking";
                
$npcfail 1;
            }

        }
        if(
$users[freeland] > 0)
            
npcBuild(attack$playstyle);
        
npcDo(heal10);
    }
}


/*
 * npcBuild(what to do, what style of play)
 * what to do:  
 * beginrun: Set to begin the run, mostly demo towers and repair attack damage
 * attack: What to build while attacking
 * midrun: Convert to Camps, if applicable
 * endrun:  Towers up!
 *
 */
function npcBuild($npcRun$playstyle){
    global 
$users$urace$totalbuild$totaldestroyed$cterms;
    global 
$config$urace$buildcost$buildrate;    
    global 
$condenseoutput;

    
$condenseoutput "hidden";
    
$users[online] = 1;
    
sleep(20); //PAUSE for 20 while building 
    
    
$buildcost round($config[buildings] + ($users[land] * 0.1));
    
$buildrate $users[land] * 0.015 4;
    
$buildrate round($urace[bpt] * $buildrate);
    
$totalbuild $totaldestroyed 0;
    
$destroyrate round(($users[land] * 0.02) + 2);
    
$destroyrate floor($urace[bpt] * $destroyrate);
    
$salvage round(($config[buildings] + ($users[land] * .1)) / 5);

    
    if(
$playstyle == "casher"){
        
$yesbuild "shops";
        
$nobuild "farms";
    }
    if(
$playstyle == "farmer"){
        
$yesbuild "farms";
        
$nobuild "shops";
    }

    if(
$npcRun == "beginrun"){
        if(
$playstyle == "casher" || $playstyle == "farmer"){  
            
//Demolish tents and towers + misc, don't need them to run
            
$totaldestroyed $users[homes] + $users[towers] + $users[industry] + $users[barracks] + $users[$nobuild];
            
$users[homes] = $users[towers] = $users[industry] = $users[barracks] = $users[$nobuild] = 0
            
$users[freeland] += $totaldestroyed;
        }
    }
    
    if(
$npcRun == "attack"){
        if(
$playstyle == "casher" || $playstyle == "farmer"){
            
//80% Markets, 20% Huts
            //we're building on all the free land
            
$totalbuild $users[freeland]; 
            
//Clean slate to begin with
            
$users[labs] = 0;
            
$users[$yesbuild] = 0;
            
            
$npcbuild round($users[land]*.8);
            
$users[$yesbuild] = $npcbuild;
            
$users[labs] = $users[land] - $npcbuild;
            
$users[freeland] = 0;
        }
    }
    
    if(
$npcRun == "midrun"){
        if(
$playstyle == "casher" || $playstyle == "farmer"){
            
//40% Markets, 40% Camps, 20% Huts
            
$totalbuild $totaldemolish $users[$yesbuild]*.5
            
$users[labs] = 0;
            
$users[$yesbuild] = 0;
            
            
$npcbuild round($users[land]*.4);
            
$users[$yesbuild] = $npcbuild;
            
$users[barracks] = $npcbuild;
            
$users[labs] = $users[land] - $npcbuild*2;
            
$users[freeland] = 0;
        }        
        
    }
    
    if(
$npcRun == "endrun"){
        
//Pretty critical build, as it usually happens with a full army load
        
$cando 0;
        if(
$playstyle == "casher")
            
npcEco(20,80);
        if(
$playstyle == "farmer")
            
npcEco(80,20);
        
$urace loadRace($users[race]);
        
$cashIn getCashGain($users$urace);
        
$cashOut getCashLoss($users$urace);
        
$loanpayment round($users[loan] / 200);
        
$foodIn getFoodGain($users$urace);
        
$foodOut getFoodLoss($users$urace);
        
$netCash $cashIn $cashOut $loanpayment;
        
$netFood $foodIn $foodOut;
        
//Set Eco to the weakness, its just for a few turns
        
$howmany ceil($users[barracks] / $buildrate) + ceil($users[barracks] / $destroyrate);
        if(
$users[cash] + ($howmany $netCash) > && $users[food] + ($howmany $netFood) > 0)
            
$cando 1;
        
//at this point, its not worth selling off army to build a few towers
        //we'll just call it a run        
        
if(($playstyle == "casher" || $playstyle == "farmer") && $cando == 1){
            
//40% Markets, 40% Towers, 20% Huts
            
$totalbuild $totaldestroyed $users[barracks]; 
            
$users[towers] = $users[barracks];
            
$users[barracks] = 0;
        }
        
    }
    
$turns 0;
    if(
$totalbuild 0)
        
$turns += ceil($totalbuild $buildrate);
    if(
$npcRun != "endrun"//we took care of this earlier
        
npcResourceCheck($turns);    
    if(
$totalbuild 0){
        
takeTurns($turns,build);
        print 
"$users[empire] built $totalbuild $cterms[structure] in $turns $cterms[turns]<br>";
    }
    
$turns 0;
    if(
$totaldemolish 0)
        
$turns += ceil($totaldestroyed $destroyrate);
    if(
$npcRun != "endrun"//we took care of this earlier
        
npcResourceCheck($turns);    
    if(
$totaldemolish 0){
        
takeTurns($turns,demolish);
        print 
"$users[empire] destroyed $totaldestroyed $cterms[structure] in $turns $cterms[turns]<br>";
    }
    
    
saveUserData($users,"shops homes industry barracks labs farms towers freeland cash turns online");
}

/*
 * npcMarket
 *
 */
function npcMarket($dowhat$dowith$docount){
    global 
$users$config$urace$costs$buy$canbuy$playstyle;
    global 
$marketdb$time$uera;
    
$cost 0;
    
$users[online] = 1;
    
sleep(7); //PAUSE for 7 while buying stuff, normally individually so it really adds up
    
    
if($dowhat == buy && $dowith == "endrun"){
        
//buy off mercs
        //final buyup

        
npcgetCosts("armtrp");
        
npcgetCosts("lndtrp");
        
npcgetCosts("flytrp");
        
npcgetCosts("seatrp");        
        
        print 
"Buying off Mercs!<br>";
        print 
"Cash on hand: $users[cash]<br>";
        
        
$cashToSpend $users[cash] * 0.9//max cash to spend on troops
        
        
npcbuyUnits(armtrp);

        
$amount min(floor($cashToSpend 0.35 $costs[armtrp]), $users[pmkt_armtrp]);
        print 
"Amount of rats:  $amount<br>";

        
$users[cash] -= $amount*$costs[armtrp];
        
$users[armtrp] += $amount;
        
$users[pmkt_armtrp] -= $amount;
        
$canbuy[armtrp] -= $amount;
        print 
commas($amount) . $uera[armtrp] purchased for $" commas($amount*$costs[armtrp]) . ".<br>\n";
        
        
npcbuyUnits(lndtrp);
        
$amount min(floor($cashToSpend 0.2 $costs[lndtrp]), $users[pmkt_lndtrp]);
        print 
"Amount of weasels:  $amount";
        
$users[cash] -= $amount*$costs[lndtrp];
        
$users[lndtrp] = +$amount;
        
$users[pmkt_lndtrp] -= $amount;
        
$canbuy[lndtrp] -= $amount;
        print 
commas($amount) . $uera[lndtrp] purchased for $" commas($amount*$costs[lndtrp]) . ".<br>\n";

        
npcbuyUnits(flytrp);
        
$amount min(floor($cashToSpend 0.3 $costs[flytrp]), $users[pmkt_flytrp]);
        print 
"Amount of stoats:  $amount";
        
$users[cash] -= $amount*$costs[flytrp];
        
$users[flytrp] += $amount;
        
$users[pmkt_flytrp] -= $amount;
        
$canbuy[flytrp] -= $amount;
        print 
commas($amount) . $uera[flytrp] purchased for $" commas($amount*$costs[flytrp]) . ".<br>\n";

        
npcbuyUnits(seatrp);
        
$amount min(floor($cashToSpend 0.15 $costs[seatrp]), $users[pmkt_seatrp]);
        print 
"Amount of skiffs:  $amount";
        
$users[cash] -= $amount*$costs[seatrp];
        
$users[seatrp] += $amount;
        
$users[pmkt_seatrp] -= $amount;
        
$canbuy[seatrp] -= $amount;        
        print 
commas($amount) . $uera[seatrp] purchased for $" commas($amount*$costs[seatrp]) . ".<br>\n";


        
saveUserDataNet($users"networth cash food armtrp lndtrp flytrp seatrp armtrp pmkt_armtrp pmkt_lndtrp pmkt_flytrp pmkt_seatrp pmkt_food online");
        

        
        
        
    }    
    if(
$dowhat == buy && $dowith != "endrun"){
        
//Get Merc costs
        
npcgetCosts($dowith);
        
//try to buy off pub. market first
        //Eventually anyways
        /*$market = dbquery("SELECT * FROM $marketdb WHERE time<=$time AND type==$dowith ORDER BY price ASC;");
        while ($item = mysql_fetch_array($market)) {
            $iname = mysql_fetch_array(dbquery("SELECT empire FROM $playerdb where num=$item[seller]"));
            $iprice = $item[price];
            $iamount = $item[amount];
            
            if($iprice < $costs[$dowith])
                
            

        }*/
        //buy off mercs
        
$mkttype "pmkt_" $dowith;
        
//artifically increase food supply
        
$canbuy[food] = $canbuy[food]*10

        if(
$docount == "all")    
            
$amount $canbuy[$dowith];
        else
            
$amount $docount;
        
$cost $amount*$costs[$dowith];
        if(
$cost $users[cash]*.8)
            
$buy[$dowith] = $amount;
        else
            
$buy[$dowith] = ($users[cash] / $costs[$dowith]) *.8

        
npcbuyUnits($dowith);
        
$amount min($buy[$dowith], $users[$mkttype]);
        
$cost $amount*$costs[$dowith];
        
$users[cash] -= $cost;
        
$users[$dowith] += $amount;
        
$users[$mkttype] -= $amount;
        
$canbuy[$dowith] -= $amount;
        
saveUserDataNet($users"networth cash food armtrp lndtrp flytrp seatrp armtrp pmkt_armtrp pmkt_lndtrp pmkt_flytrp pmkt_seatrp pmkt_food online");
        print 
commas($amount) . $uera[$dowith] purchased for $" commas($cost) . ".<br>\n";

    }
    if(
$dowhat == "sell" || $dowhat == "panicsell"){
        
//getSalePrice is in funcs.  Why?  I donno.
        
$costs[armtrp] = getSalePrice(armtrp);
        
$costs[lndtrp] = getSalePrice(lndtrp);
        
$costs[flytrp] = getSalePrice(flytrp);
        
$costs[seatrp] = getSalePrice(seatrp);
        
$costs[food] = getSalePrice(food);
        
        if(
$dowhat != "panicsell"){
            
//Pub market sell first
            
$percent 0.845;
            
$goods dbquery("SELECT * FROM $marketdb WHERE type='$dowith' AND seller=$users[num] ORDER BY amount DESC;");
            while (
$market mysql_fetch_array($goods)) {
                
$onsale += $market[amount];
            }        
            
$basket[$dowith] = round(($users[$dowith] + $onsale) * $percent) - $onsale;
            if (
$basket[$dowith] < 0)
                
$basket[$dowith] = 0;
            if(
$docount == "all"){
                
$amount $basket[$dowith];
            }else{
                
$amount $docount;
                if(
$docount $basket[$dowith])
                    
$amount $basket[$dowith];
            }
            if(
$dowith == "food")
                
$amount $amount .6//should never sell _all_ its food
            
$price $config[$dowith][market]; //Sale price!
            
$users[$dowith] -= $amount;
            
$basket[$dowith] -= $amount;
            if(
$amount != 0){
                
dbquery("INSERT INTO $marketdb (type,seller,amount,price,time) VALUES ('$dowith',$users[num],$amount,$price," . ($time 3600 $config[market] - Min(($users[barracks] + $users[cities] * 500) / 1000 36005.5 3600)) . ");");
                
saveUserDataNet($users$dowith);
                print 
"Public Market: " commas($amount) . $uera[$dowith] sold;  ";
            }
        }

        
//Pvt market sell the rest
        
if($users[$dowith] > 0){
            
$amount floor(($config[bmperc] - $users["bmper" "$dowith"]) / 10000 $users[$dowith]);
            if(
$docount == "all"){
                
//amount is preset to the max, so no worries..  but we'll do a quick food check
                
if ($dowith == food && $amount $users[food]*.6)
                    
$amount $users[$food]*.6;  //should never sell _all_ its food
            
}else{
                
//otherwise, if we want to sell a specific amount
                
if($docount $amount)
                    
$amount $docount;                
            }
            
$cost $amount $costs[$dowith];
            
$users[cash] += $cost;
            
$users["bmper$dowith"] = $users["bmper$dowith"] + ($amount $users[$dowith]) * 10000;
            
$users["pmkt_$dowith"] += $amount mt_rand(0.200.66);
            
$users[$dowith] -= $amount;
            
saveUserDataNet($users"cash " $dowith);
            print 
"Private Market: " commas($amount) . $uera[$dowith] sold for $" commas($cost) . "<br>\n";
        }

    }    
}

function 
npcResourceCheck($howmany){
    global 
$users$playstyle$maintroop;

    if(
$users[cash] <= 0){
        print 
"Oops.  Out of Cash!<br>";    
        if(
$playstyle == "farmer")
            
npcMarket(panicsellfood$users[food]*.4);
        if(
$maintroop != "lndtrp")
            
npcMarket(panicselllndtrp$users[lndtrp]*.3);
        if(
$maintroop != "flytrp")
            
npcMarket(panicsellflytrp$users[flytrp]*.3);
        if(
$maintroop != "seatrp")
            
npcMarket(panicsellseatrp$users[seatrp]*.3);
        if(
$maintroop != "armtrp")
            
npcMarket(panicsellarmtrp$users[armtrp]*.3);
    }
    if(
$users[food] <= 0){
        print 
"Oops.  Out of Food!<br>";
        
npcMarket(buyfoodall);
    }    
    
    if(
$howmany 0){
        if (
$playstyle == "casher"){
            
npcEco(100,0);
        }
        elseif (
$playstyle == "farmer"){
            
npcEco(0,100);
        }
    
        
$urace loadRace($users[race]);

        
$foodIn getFoodGain($users$urace);
        
$foodOut getFoodLoss($users$urace);
        
$netFood $foodIn $foodOut;
        
        if((
$netFood 0) && (($users[food] + ($howmany $netFood)) < 0)){
            
npcMarket(sell$maintroopround($maintroop*.3));
            
npcMarket(buyfoodall);
            if (
$users[foodpct] < 80npcEco(20,80);
            print 
"Food is an issue.  Setting Eco settings 20 / 80";
            
//If its really this bad, its going to 3% anyways.  Nuke aux troops, sell gets rid of the max possible via public and private markets.
            
if($maintroop != "lndtrp")
                
npcMarket(selllndtrpall);
            if(
$maintroop != "flytrp")
                
npcMarket(sellflytrpall);
            if(
$maintroop != "seatrp")
                
npcMarket(sellseatrpall);
            if(
$maintroop != "armtrp")
                
npcMarket(sellarmtrpall);
            
$loopcount 5;
            
$foodIn getFoodGain($users$urace);
            
$foodOut getFoodLoss($users$urace);
            
$netFood $foodIn $foodOut//recalculate after all that happens
            
while(($netFood 0) && (($users[food] + ($howmany $netFood)) < 0) && ($loopcount 0)){
                
//I mean, what else is there to do?  
                //As many of the aux troops as possible are gone by now, we can sell off the $maintroop I guess
                //What's left to hold it back that can be jettisoned?  Leaders can't be sold, nor workers
                
npcMarket(sell$maintroopround($maintroop*.2));                
                
$loopcount -= 1;
                if(
$loopcount == 0)
                    print 
"Out of Food, CAN'T FIX  :(  screw it, we're pwned<br>";
                
$foodIn getFoodGain($users$urace);
                
$foodOut getFoodLoss($users$urace);
                
$netFood $foodIn $foodOut//recalculate after all that happens
            
}
        }
        
        
$cashIn getCashGain($users$urace);
        
$cashOut getCashLoss($users$urace);
        
$loanpayment round($users[loan] / 200);
        
$netCash $cashIn $cashOut $loanpayment;
        if((
$netCash 0) && (($users[cash] + ($howmany $netCash)) < 0)){
            
npcMarket(sell$maintroopround($maintroop*.3));
            
npcMarket(buyfoodall);
            if(
$users[cashpct] <= 20){
                print 
"This account is pretty screwed up, setting Eco settings to 50/50"//means either out of food or wont make next turn count with current food...  and now its out of cash.
                
npcEco(50,50);    //Comprimise!
            
}
            if(
$maintroop != "lndtrp")
                
npcMarket(selllndtrpall);
            if(
$maintroop != "flytrp")
                
npcMarket(sellflytrpall);
            if(
$maintroop != "seatrp")
                
npcMarket(sellseatrpall);
            if(
$maintroop != "armtrp")
                
npcMarket(sellarmtrpall);
            
$loopcount 5;
            
$cashIn getCashGain($users$urace);
            
$cashOut getCashLoss($users$urace);
            
$loanpayment round($users[loan] / 200);
            
$netCash $cashIn $cashOut $loanpayment;
            while((
$netCash 0) && (($users[cash] + ($howmany $netCash)) < 0) && ($loopcount 0)){
                
npcMarket(sell$maintroopround($maintroop*.2));                
                
$loopcount -= 1;
                if(
$loopcount == 0)
                    print 
"Out of Cash, CAN'T FIX  :(  screw it, we're pwned<br>";
                
$cashIn getCashGain($users$urace);
                
$cashOut getCashLoss($users$urace);
                
$loanpayment round($users[loan] / 200);
                
$netCash $cashIn $cashOut $loanpayment;
            }
        }
    }
}

/*
 * npcTax(New tax)
 * Update tax rate
 */
function npcTax($new_tax){
    global 
$users;
    
$users[tax] = $new_tax;
    
saveUserData($users"tax");
    print 
"$users[empire] Tax rate updated: $new_tax<br><br>";    
}

/*
 * npcEco(new cash rate, new food rate)
 * Update Economy rate
 */
function npcEco($cashpct$foodpct){
    global 
$users;
    
$users[cashpct] = $cashpct;
    
$users[foodpct] = $foodpct;
    
saveUserData($users"cashpct foodpct");
}

/*
 * Private market function
 * borrowed from pvtmarketbuy.php
 */
function npcbuyUnits($dowith) {
    global 
$costs$users$uera$buy$canbuy$cterms;
    
$amount $buy[$dowith];
    if (
substr($buy[$dowith], 01) == "$")
        
$amount floor(substr($buy[$dowith], 1) / $costs[$dowith]);

    
fixInputNum($amount);
    
$cost $amount $costs[$dowith];
    
$mkttype "pmkt_" $dowith;
}
/*
 * Same as pvtmarketbuy
 */
function npcgetCosts($dowith) {
    global 
$users$config$urace$costs$canbuy;
    
$mkttype "pmkt_" $dowith;
    
$costbonus $urace[mkt] * (- ($users[barracks] + $users[cities] * 500) / ($users[land]));
    if (
$costbonus 0.8 $urace[mkt])
        
$costbonus 0.8 $urace[mkt];
    if (
$dowith == food)
        
$costs[$dowith] = $config[$dowith][market];
    else {
        
$costs[$dowith] = round($config[$dowith][market] * $costbonus);
    }
    
$canbuy[$dowith] = floor($users[cash] / $costs[$dowith]);
    if (
$canbuy[$dowith] > $users[$mkttype])
        
$canbuy[$dowith] = $users[$mkttype];
}
?>