/* The main simulation-running code in Xconq.
   Copyright (C) 1986-1989, 1991-1999 Stanley T. Shebs.

Xconq is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.  See the file COPYING.  */

/* This is the main simulation-running code. */

#include "conq.h"
#include "kernel.h"
#include "kpublic.h"
#include "ai.h"

extern TaskOutcome execute_task_aux PARAMS ((Unit *unit, Task *task));

/* Functions in run2.c, only called from this file. */

extern void run_turn_start PARAMS ((void));
extern void run_restored_turn_start PARAMS ((void));
extern void run_turn_end PARAMS ((void));
static void compose_actionvectors PARAMS ((void));
static void init_movement PARAMS ((void));
static int move_some_units PARAMS ((int lim));
static int side_move_some_units PARAMS ((Side *side, int lim));
static int unit_still_acting PARAMS ((Unit *unit));
static int unit_still_acting_no_plan PARAMS ((Unit *unit));
static int move_one_unit_multiple PARAMS ((Unit *unit, int lim));

/* Priority of sides that are now moving. */

int curpriority;

/* Priority of units that are now moving. */

int cur_unit_priority;

/* Highest and lowest possible priority of unit (smallest and largest
   number). */

int highest_unit_priority;
int lowest_unit_priority;

int maintimeout = -1;

int paused = FALSE;

/* State variables. */
/* (I don't think all of these are strictly necessary) */

/* This becomes TRUE the first time run_game is executed. */

int gameinited = FALSE;

/* This is true only before the game actually starts. */

int beforestart = TRUE;

/* This is true only at the beginning of a turn. */

int at_turn_start = FALSE;

/* This is true after the game is over. */

int endofgame = FALSE;

/* This is true when the program may actually exit. */

int ok_to_exit;

/* This is set FALSE whenever the game state changes, and TRUE whenever
   the game has been saved. */

int gamestatesafe = TRUE;

/* This is TRUE after the designer has been mucking around, or if
   networked versions are found to be inconsistent. */

int compromised = FALSE;

int in_run_game = FALSE;

/* The time at which the game actually starts. */

time_t game_start_in_real_time;

/* The point in the turn at which players can actually do things. */

time_t turn_play_start_in_real_time;

int planexecs;

int taskexecs;

/* The rate at which AIs play when acting more slowly (so as
   not to overwhelm human players), expressed as plan executions
   per minute.  0 means "as fast as possible". */

int slow_play_rate = 240;

/* The rate at which AIs play when acting more quickly (such
   as when all humans are done with their moves). */

int fast_play_rate = 0;

/* The current rate at which AIs are playing. */

int current_play_rate;

/* Debugging counts for when run_game does nothing many times. */

static int nothing_count;

/* True when an event occurs and we need to check scorekeepers. */

int need_post_event_scores;

/* Flags that other code uses to signal the AI code that it ought
   to consider running something. */

int need_ai_init_turn;

int need_ai_planning;

int need_ai_task_reaction;

int need_ai_for_new_side;

int need_ai_finish_movement;

int debugging_state_sync;

void
init_run()
{
    int u;
    Unit *unit;
    Side *side;

    highest_unit_priority = 9999;
    lowest_unit_priority = -1;
    for_all_unit_types(u) {
        highest_unit_priority =
	  min(highest_unit_priority, u_action_priority(u));
        lowest_unit_priority =
	  max(lowest_unit_priority, u_action_priority(u));
        for_all_sides_plus_indep(side) {
	    if (side->action_priorities) {
		highest_unit_priority =
		  min(highest_unit_priority, side->action_priorities[u]);
		lowest_unit_priority =
		  max(lowest_unit_priority, side->action_priorities[u]);
	    }
        }
    }
    for_all_units(unit) {
        if (unit->extras) {
	    highest_unit_priority =
	      min(highest_unit_priority, unit_extra_priority(unit));
	    lowest_unit_priority =
	      max(lowest_unit_priority, unit_extra_priority(unit));
        }
    }
}

/* This function does a (small, usually) amount of simulation, then
   returns.  It can be run multiple times at any time, will not go
   "too far".  It returns the number of actions that were actually
   performed. Other important state changes (such a side finishing its
   turn or the turn ending) are also counted as actions, so that this
   function's callers will know that something was done. */

int
run_game(maxactions)
int maxactions;
{
    int numacted, numother, runtime, numdone, bump;
    long saved_randstate;
    time_t rungamestart, rungameend;
    Side *side;
    extern long randstate;
    char *activity = "run_game";

    in_run_game = TRUE;
    record_activity_start(activity, maxactions);
    if (Debug && numremotes > 0 && 0) {
	sprintf(spbuf, "states/%dstate%06da", my_rid, g_run_serial_number());
	debugging_state_sync = TRUE;
	write_entire_game_state(spbuf);
	debugging_state_sync = FALSE;
    }
    gameinited = TRUE;
    saved_randstate = randstate;
    time(&rungamestart);
    numacted = numother = planexecs = taskexecs = 0;
    need_ai_planning = FALSE;
    if (beforestart) {
	/* If we haven't started yet, see if it's time. */
	test_for_game_start();
	Dprintf("run_game: tested for game start.\n");
    }
    if (endofgame) {
	/* Nothing to do except wait for users to do exit commands. */
    	Dprintf("run_game: at end of game.\n");
    } else if (paused) {
	/* Don't do anything if we're paused. */
    	Dprintf("run_game: paused.\n");
    } else if (!beforestart) {
	if (at_turn_start) {
	    if (midturnrestore)
	      run_restored_turn_start();
	    else
	      run_turn_start();
	    check_all_units();
	    init_movement();
	    cur_unit_priority = highest_unit_priority;
	    compose_actionvectors();
	    update_all_progress_displays("", -1);
	    /* Game might have been ended by new turn init. */
	    test_for_game_end();
	    if (endofgame) {
	    	Dprintf("run_game: game ended by new turn init.\n");
	    	goto rungamereturn;
	    }
	    /* (should adjust this by recorded elapsed turn time) */
	    time(&turn_play_start_in_real_time);
	    at_turn_start = FALSE;
	    ++numother;
	    /* Might have local AIs that need to run, so give them a chance
	       now rather than after units start moving. */
	    need_ai_init_turn = TRUE;
	    need_ai_planning = TRUE;
	    goto rungamereturn;
	}
	/* If this game is running in realtime, update all clock displays. */
	if (realtime_game()) {
	    for_all_sides(side) {
		if (side->ingame && side_has_display(side)) {
		    update_clock_display(side, TRUE);
		}
	    }
	}
	/* If all sides are done acting, end the turn.  This will never be true
	   right at the start of a turn. */
	if (all_sides_finished() || exceeded_rt_per_turn()) {
	    run_turn_end();
	    Dprintf("run_game: at turn end.\n");
	    at_turn_start = TRUE;
	    ++numother;
	    need_ai_finish_movement = TRUE;
	} else {
	    /* Move some units around. */
	    numacted += move_some_units(maxactions);
	    if (cur_unit_priority < lowest_unit_priority) {
		/* Handle prioritized movement. */
		bump = TRUE;
		for_all_sides(side) {
		    if (!side->finishedturn
			&& units_still_acting(side)) {
			bump = FALSE;
		    }
		}
		if (bump) {
		    Dprintf("run_game: increment unit priority to %d\n",
			    cur_unit_priority + 1);
		    ++cur_unit_priority;
		    compose_actionvectors();
		    ++numother;
		}
	    } else {
		/* Possibly finish some sides' turns. */
		for_all_sides(side) {
		    if (!side->finishedturn
			&& ((!units_still_acting(side)
			     && side->autofinish
			     && !is_designer(side))
			    /* Sides with no display or AI finish
                               automatically. */
			    || (!side_has_display(side)
				&& !side_has_ai(side)))) {
			Dprintf("run_game: %s auto-finishes.\n",
				side_desig(side));
			finish_turn(side);
			++numother;
		    }
		}
	    }
	}
	check_realtime();
	test_for_game_end();
    }
rungamereturn:
    if (need_post_event_scores)
      check_post_event_scores();
    numdone = numacted + planexecs + taskexecs + numother;
    if (Debug) {
	if (numdone > 0) {
	    if (nothing_count > 0) {
		Dprintf("run_game: Did nothing %d times\n", nothing_count);
		nothing_count = 0;
	    }
	    Dprintf("run_game #%d: %d/%d actions", g_run_serial_number(),
		    numacted, maxactions);
	    if (planexecs > 0)
	      Dprintf(", %d plan execs", planexecs);
	    if (taskexecs > 0)
	      Dprintf(", %d task execs", taskexecs);
	    if (numother > 0)
	      Dprintf(", %d other", numother);
	    /* (also number of units considered?) */
	    Dprintf("\n");
	    if (numremotes > 0) {
		Dprintf("run_game: Randstate started at %ld, is now %ld\n",
			saved_randstate, randstate);
#if 1 /* use this for high-powered networking debugging */
		if (1 /* record each run_game states */) {
		    sprintf(spbuf, "states/%dstate%06d",
			    my_rid, g_run_serial_number());
		    debugging_state_sync = TRUE;
		    write_entire_game_state(spbuf);
		    debugging_state_sync = FALSE;
		}
#endif
	    }
	} else {
	    if (nothing_count >= 1000) {
		Dprintf("run_game: Did nothing %d times\n", nothing_count);
		nothing_count = 0;
	    } else {
		++nothing_count;
	    }
	}
    }
    time(&rungameend);
    runtime = idifftime(rungameend, rungamestart);
    if (runtime > 0)
      Dprintf("run_game: runtime seconds = %d\n", runtime);
    if (Debug && numremotes > 0 && 0) {
	sprintf(spbuf, ":states:state%06db", g_run_serial_number());
	debugging_state_sync = TRUE;
	write_entire_game_state(spbuf);
	debugging_state_sync = FALSE;
    }
    in_run_game = FALSE;
    set_g_run_serial_number(g_run_serial_number() + 1);
    record_activity_end(activity, numdone);
    return numdone;
}

/* See if game is ready to get underway for real.  Note that displays will
   work before the game has started, but game time doesn't move. */

void
test_for_game_start()
{
    int anydisplays = FALSE;
    Side *side;

    /* We must have at least one unit on a side that is being displayed
       before the game can start for real. */
    for_all_sides(side) {
	if (side_has_display(side)) {
	    anydisplays = TRUE;
	}
	if (side_has_units(side) && side_has_display(side)) {
	    /* Now we're really ready to roll. */
	    beforestart = FALSE;
	    at_turn_start = TRUE;
	    if (midturnrestore) {
		record_event(H_GAME_RESTARTED, ALLSIDES);
	    } else {
		record_event(H_GAME_STARTED, ALLSIDES);
		set_g_elapsed_time(0);
	    }
	    /* Record the game as starting NOW in real time. */
	    time(&game_start_in_real_time);
	    /* Adjust by any recorded elapsed time. */
	    game_start_in_real_time -= g_elapsed_time();
	    /* No need to look at any more sides, just get on with the game. */
	    return;
	}
    }
    if (!anydisplays) {
	init_warning("No sides have a display");
    }
}

/* This routine looks to see if the game is completely over. */

void
test_for_game_end()
{
    Side *side;

    /* Declare a draw if everybody is amenable. */
    if (all_others_willing_to_quit(NULL)) {
    	notify_all("All sides have agreed to declare a draw.");
    	all_sides_draw();
	end_the_game();
	return;
    }
    for_all_sides(side) {
    	/* If we have an active side being displayed, we're not done yet. */
	if (side->ingame && side_has_display(side))
	  return;
	/* (If no displayed sides have units, turns will whiz by) */
    }
    notify_all("All sides with displays are out of the game.");
    end_the_game();
}

/* This is true when all participating sides have finished their turn. */

int
all_sides_finished()
{
    Side *side;

    for_all_sides(side) {
	if (side->ingame
	    && !side->finishedturn) {
	    return FALSE;
	}
    }
    return TRUE;
}

/* This is true when AIs should move more quickly. */

int
all_human_only_sides_finished()
{
    Side *side;

    for_all_sides(side) {
	if (side->ingame
	    && side_has_display(side)
	    && !side_has_ai(side)
	    && !side->finishedturn) {
	    return FALSE;
	}
    }
    return TRUE;
}

/* Call this from interfaces to check on realtime details without actually
   going into run_game.  Will call back to interface if necessary. */

void
check_realtime()
{
    Side *side;

    if (!realtime_game())
      return;
    if (exceeded_rt_for_game()) {
	notify_all("Time has run out!");
	end_the_game();
    }
    if (g_rt_per_side() > 0) {
	for_all_sides(side) {
	    if (side->ingame && side->totaltimeused > g_rt_per_side()) {
		remove_side_from_game(side);
	    }
	}
    }
}

int
exceeded_rt_for_game()
{
    time_t now;

    if (g_rt_for_game() <= 0)
      return FALSE;
    time(&now);
    /* Note that the game start time is already adjusted for any
       elapsed time recorded when the game was last saved. */
    return (idifftime(now, game_start_in_real_time) > g_rt_for_game());
}

int
exceeded_rt_per_turn()
{
    time_t now;

    if (g_rt_per_turn() <= 0)
      return FALSE;
    time(&now);
    return (idifftime(now, turn_play_start_in_real_time) > g_rt_per_turn());
}

/* This returns true if the given side is still wanting to do stuff. */

int
units_still_acting(side)
Side *side;
{
    int curactor;
    Unit *unit;

    if (!side->ingame)
      return FALSE;
    /* Test current actor first, most likely to be still acting. */
    if (side->curactor_pos < side->actionvector->numunits) {
	unit = (side->actionvector->units)[side->curactor_pos].unit;
	if (unit_still_acting(unit) && side_controls_unit(side, unit))
	  return TRUE;
    }
    for (curactor = 0; curactor < side->actionvector->numunits; ++curactor) {
	unit = (side->actionvector->units)[curactor].unit;
	if (unit_still_acting(unit) && side_controls_unit(side, unit))
	  return TRUE;
    }
    return FALSE;
}

static void
init_movement()
{
    int i;
    Side *side;

    i = 1;
    curpriority = 9999;
    /* In the absence of any idea about how to handle actions by
       independent units, force their turn to be finished
       immediately. */
    indepside->finishedturn = TRUE;
    for_all_sides(side) {
	if (side->ingame) {
	    /* Record that this side was active during at least one turn. */
	    side->everingame = TRUE;
	    /* No units are waiting for orders initially. */
	    side->numwaiting = 0;
	}
	side->turnstarttime = time(0);
	/* Didn't really do input, but useful to pretend so. */
	side->lasttime = time(0);
	/* Calculate side priorities; do here so future versions can
	   set priorities dynamically. */
	if (g_use_side_priority()) {
	    if (side->priority < 0) {
		side->priority = i++;
	    }
	}
	side->busy = FALSE;
	if (side_has_display(side))
	  update_action_display(side, TRUE);
    }
    /* Set independent units to move after units on sides. */
    if (g_use_side_priority()) {
	if (indepside->priority < 0) {
	    indepside->priority = i;
	}
	for_all_sides_plus_indep(side) {
	    if (!side->finishedturn && side->priority < curpriority)
	      curpriority = side->priority;
	}
    }
}

static void
compose_actionvectors()
{
    int priority;
    Unit *unit;
    Side *side, *side2;

    for_all_sides_plus_indep(side) {
	if (side->actionvector == NULL)
	  side->actionvector = make_unit_vector(max(numunits, 100));
	clear_unit_vector(side->actionvector);
	for_all_side_units(side, unit) {
	    if (unit->act && unit->act->initacp > 0) {
		priority = unit_priority(unit);
		if (priority == cur_unit_priority) {
		    side->actionvector = add_unit_to_vector(side->actionvector, unit, 0);
		    /* Clear any delay flags. */
		    if (unit->plan)
		      unit->plan->delayed = FALSE;
		}
	    }
	    if (unit->plan) {
		unit->plan->execs_this_turn = 0;
	    }
	}
	Dprintf("Action vector for %s has %d units, at priority %d\n",
		side_desig(side), side->actionvector->numunits, cur_unit_priority);
    }
    /* Inform sides with displays of how many units are ready to act. */
    for_all_sides(side) {
	if (side_has_display(side)) {
	    for_all_sides(side2) {
		update_side_display(side, side2, TRUE);
	    }
	}
    }
}

int
unit_priority(unit)
Unit *unit;
{
    int pri;
    Side *side;

    pri = unit_extra_priority(unit);
    if (pri >= 0)
      return pri;
    side = (unit->side ? unit->side : indepside);
    if (side->action_priorities != NULL) {
	pri = side->action_priorities[unit->type];
	if (pri >= 0)
	  return pri;
    }
    return u_action_priority(unit->type);
}

/* Do some number of actions, up to a total of LIM per side.  Return
   the total number of actions performed. */

static int
move_some_units(lim)
int lim;
{
    int num = 0, sidenum;
    Side *side;

    for_all_sides_plus_indep(side) {
	if ((g_use_side_priority() ?
	     curpriority == side->priority :
	     TRUE)) {
	    sidenum = side_move_some_units(side, lim);
	    num += sidenum;
	}
    }
    return num;
}

/* Do some number of actions. */

static int
side_move_some_units(side, lim)
Side *side;
int lim;
{
    int num, foundanytomove, curactor0, curactor, numdelayed;
    Unit *unit;

    num = 0;
    curactor0 = 0;
    if (side->curactor_pos < side->actionvector->numunits
        && side->curactor == (side->actionvector->units)[side->curactor_pos].unit
        && side->curactor != NULL
        && side->curactor_id == ((side->actionvector->units)[side->curactor_pos].unit)->id)
      curactor0 = side->curactor_pos;
    if (numremotes > 0)
      curactor0 = 0;
  tryagain:
    foundanytomove = FALSE;
    numdelayed = 0;
    for (curactor = curactor0; curactor < side->actionvector->numunits; ++curactor) {
	unit = (side->actionvector->units)[curactor].unit;
	if (0 /*numremotes > 0*/)
	  Dprintf("Considering moving %s with plan %s\n",
		  unit_desig(unit), plan_desig(unit->plan));
	/* Count and skip over deliberately delayed units. */
	if (unit->plan && unit->plan->delayed) {
	    ++numdelayed;
	    continue;
	}
	current_play_rate = slow_play_rate;
	/* AIs should play as fast as possible if turns are sequential
	   or if the human players are all done. */
	if (g_use_side_priority() || all_human_only_sides_finished()) {
	    current_play_rate = fast_play_rate;
	}
	/* If the unit is keeping formation, then give it a chance to
	   adjust its position, even if it's not "still acting". */
	if (is_active(unit)
	    && (unit->side ?
		(unit->side->ingame && !unit->side->finishedturn) : TRUE)
	    && (unit->act && unit->act->acp > 0)
	    && (unit->plan && unit->plan->formation)) {
	    num += move_one_unit_multiple(unit, lim - num);
	    foundanytomove = TRUE;
	}
	if (unit->side
	    && unit->side->orders
	    && unit->plan
	    && unit->plan->tasks == NULL
	    && execute_standing_order(unit, FALSE)) {
	    /* We're not waiting because standing order execution will
	       shortly be allowed to fill in a task for real. */
	    set_waiting_for_tasks(unit, FALSE);
	    num += move_one_unit_multiple(unit, lim - num);
	    foundanytomove = TRUE;
	}
	if (unit_still_acting(unit)
	    && (unit->plan && !unit->plan->waitingfortasks)) {
	    num += move_one_unit_multiple(unit, lim - num);
	    foundanytomove = TRUE;
	} else if (unit_still_acting_no_plan(unit)) {
	    num += move_one_unit_multiple(unit, lim - num);
	    foundanytomove = TRUE;
	}
	if (unit_still_acting(unit)) {
	    foundanytomove = TRUE;
	}
	if (num >= lim) {
	    if (foundanytomove && unit != NULL) {
		side->curactor_pos = curactor;
		side->curactor = unit;
		side->curactor_id = unit->id;
	    } else {
		side->curactor_pos = 0;
		side->curactor = NULL;
		side->curactor_id = 0;
	    }
	    return num;
	}
    }
    /* If started in middle of list, rescan from beginning. */
    if (!foundanytomove && curactor0 > 0) {
	curactor0 = 0;
	goto tryagain;
    }
    /* Clear all the delay flags and rescan the action vector. */
    if (!foundanytomove && numdelayed > 0) {
	for (curactor = 0; curactor < side->actionvector->numunits; ++curactor) {
	    unit = (side->actionvector->units)[curactor].unit;
	    if (unit->plan)
	      unit->plan->delayed = FALSE;
	}
	curactor0 = 0;
	goto tryagain;
    }
    if (!foundanytomove && 0 /* not at max priority */) {
	/* (should recompose action vector for new priority?) */
    }
    side->curactor_pos = 0;
    side->curactor = NULL;
    side->curactor_id = 0;
    return num;
}

static int
unit_still_acting(unit)
Unit *unit;
{
    return (is_active(unit)
	    && (unit->side
		&& unit->side->ingame
		&& !unit->side->finishedturn)
	    && (unit->act
		&& unit->act->acp > 0)
	    && ((unit->plan
		&& !unit->plan->asleep
		&& !unit->plan->reserve)
		|| has_pending_action(unit)));
}

static int
unit_still_acting_no_plan(unit)
Unit *unit;
{
    return (is_active(unit)
	    && (unit->side
		&& unit->side->ingame
		&& !unit->side->finishedturn)
	    && (unit->act
		&& unit->act->acp > 0)
	    && has_pending_action(unit));
}

/* Do a single unit's actions, up to the given limit or until it runs
   out of things it wants to do (or something happens to it). */

int lastexecution = 0;

static int
move_one_unit_multiple(unit, lim)
Unit *unit;
int lim;
{
    int num = 0, buzz = 0, acp1;
    int rslt;

    /* If unit is incapable of acting right now, get out of here. */
    if (unit->act == NULL || unit->act->initacp < 1)
      return 0;
    acp1 = unit->act->acp;
    while (is_active(unit)
	   && (unit->act
	       && unit->act->acp > u_acp_min(unit->type))
	   && ((unit->plan
		&& !unit->plan->asleep
		&& !unit->plan->reserve
		&& !unit->plan->delayed
		&& !(need_ai_task_reaction
		     && unit->plan->last_task_outcome != TASK_UNKNOWN))
	       || has_pending_action(unit))
	   && num < lim
	   && buzz < lim) {
	if (numremotes > 0)
	  Dprintf("  Moving %s (%d/%d, buzz %d) with plan %s\n",
		  unit_desig(unit), num, lim, buzz, plan_desig(unit->plan));
	if (has_pending_action(unit)) {
	    /* Execute the action directly. */
	    rslt = execute_action(unit, &(unit->act->nextaction));
	    /* Clear the action.  Note that the unit might have changed
	       to a non-acting type, so we have to check for act struct. */
	    if (unit->act)
	      unit->act->nextaction.type = ACTION_NONE;
	    /* In any case, the game state is irrevocably altered. */
	    gamestatesafe = FALSE;
	    ++num;
	} else if (unit->plan != NULL) {
	    /* Even units that are asleep, in reserve, etc must execute
	       any standing orders that apply. */
	    if (unit->side
		&& unit->side->orders
		&& unit->plan->tasks == NULL
		&& execute_standing_order(unit, TRUE)) {
		planexecs += execute_plan(unit);
		gamestatesafe = FALSE;
		++buzz;
	    }
	    /* Similarly for formations. */
	    if (unit->plan->formation && move_into_formation(unit)) {
		planexecs += execute_plan(unit);
		gamestatesafe = FALSE;
		++buzz;
	    }
	    /* Flag so that we run AI code in the near future (after
	       run_game exits). */
	    if (side_has_ai(unit->side))
	      need_ai_planning = TRUE;
	    /* Get out of here if unit is set not to do anything on
	       its own. */
	    if (unit->plan->waitingfortasks
		|| unit->plan->asleep
		|| unit->plan->reserve
		|| unit->plan->delayed)
	      break;
	    /* Normal plan execution. */
	    planexecs += execute_plan(unit);
	    record_ms();
	    gamestatesafe = FALSE;
	    ++buzz;
	} else {
	    run_warning("Planless \"%s\" was asked to act", unit_desig(unit));
	    ++buzz;
	}
	/* If the unit is trying to do actions several times in this
	   loop and and none of them are succeeding, something is
	   wrong; blast the plan and eventually put the unit to
	   sleep, if the problem persists. */
	if (unit->act && unit->act->acp == acp1 && num > 1) {
	    /* Blast the action. */
	    unit->act->nextaction.type = ACTION_NONE;
	    /* Blast the plan. */
	    if (unit->plan)
	      unit->plan->type = PLAN_PASSIVE;
	    if (unit->plan && probability(5))
	      unit->plan->asleep = TRUE;
	    run_warning("\"%s\" trying multiple bad actions, clearing its plan",
			unit_desig(unit));
	}
    }
    return num;
}

/* This explicitly finishes out a side's activity for the turn. */

void
finish_turn(side)
Side *side;
{
    int nextpriority;
    Side *side2, *side3;

    /* Flag the side as being done for this turn. */
    side->finishedturn = TRUE;
    /* Stop counting down our time consumption. */
    side->totaltimeused += (time(0) - side->turnstarttime);
    if (g_use_side_priority()) {
	nextpriority = 9999;
	for_all_sides_plus_indep(side2) {
	    if (!side2->finishedturn
/*		&& side2->priority > curpriority */
		&& side2->priority < nextpriority) {
		nextpriority = side2->priority;
	    }
	    if (!side2->finishedturn && side2->priority < curpriority)
	      run_warning("%s not finished, but priority is %d, less than current %d",
			  side_desig(side2), side2->priority, curpriority);
	}
	if (nextpriority > curpriority)
	  curpriority = nextpriority;
    }
    /* Clue everybody in. */
    if (g_use_side_priority()) {
	/* Several sides may change, if current priority changes. */
	for_all_sides(side2) {
	    for_all_sides(side3) {
		update_side_display(side2, side3, TRUE);
	    }
	}
    } else {
	/* Only the turn-finishing side changes. */
	for_all_sides(side2) {
	    update_side_display(side2, side, TRUE);
	}
    }
    Dprintf("%s finished its turn.\n", side_desig(side));
}

void run_ai_plan_adjust PARAMS ((Side *side));

/* (should decide on useful return value and use, or make void) */

int
run_local_ai(when, maxplanning)
int when, maxplanning;
{
    Side *side;
    Unit *unit;
    char *activity = "run_local_ai";

    record_activity_start(activity, when);
    /* Only do this routine at a certain rate. */
    if (current_play_rate > 0
	&& !n_ms_elapsed(60000 / current_play_rate)
	) {
	record_activity_end(activity, 1);
	return 0;
    }
    if (need_ai_for_new_side) {
	for_all_sides(side) {
	    if (side_wants_ai(side) && !side_has_ai(side)) {
		init_ai(side);
	    }
	}
	need_ai_for_new_side = FALSE;
    }
    if (need_ai_init_turn) {
	for_all_sides(side) {
	    if (side_has_ai(side))
	      ai_init_turn(side);
	}
	need_ai_init_turn = FALSE;
    }
    if (need_ai_planning) {
	for_all_sides(side) {
	    if (side_has_ai(side) /* (should) and need planning for this side*/) {
		for_all_side_units(side, unit) {
		    if (is_active(unit)
			&& unit->plan
			&& unit->plan->aicontrol
			&& !unit->plan->asleep) {
			ai_decide_plan(side, unit);
#if 0 /* comment out until this is figured out */
			/* ...was in execute_plan - not ideal location, but
			   needs to be in this function somewhere... */
			/* Always reevaluate the plan before executing it! */
			ai_update_plan(side, unit);
			/* Deal with tactical emergencies such as
			   enemy units that suddenly appear nearby. */
			ai_handle_emergency(side, unit);
#endif
		    }
		}
	    }
	}
	need_ai_planning = FALSE;
    }
    if (need_ai_task_reaction) {
	for_all_sides(side) {
	    if (side_has_ai(side)) {
		for_all_side_units(side, unit) {
		    if (is_active(unit)
			&& unit->plan
			&& unit->plan->aicontrol
			&& unit->plan->last_task_outcome != TASK_UNKNOWN) {
			ai_react_to_task_result(side, unit, &(unit->plan->last_task),
						unit->plan->last_task_outcome);
			unit->plan->last_task_outcome = TASK_UNKNOWN;
		    }
		}
	    }
	}
	need_ai_task_reaction = FALSE;
    }
    if (1) {
	for_all_sides(side) {
	    if (side_has_ai(side) && !side->finishedturn) {
		run_ai_plan_adjust(side);
	    }
	}
    }
    if (need_ai_finish_movement) {
	for_all_sides(side) {
	    if (side_has_ai(side) && !side->finishedturn) {
		ai_finish_movement(side);
	    }
	}
	need_ai_finish_movement = FALSE;
    }
    record_activity_end(activity, 1);
    return 0;
}

void
run_ai_plan_adjust(side)
Side *side;
{
    int curactor, domore;
    Unit *unit;

    if (side->actionvector == NULL)
      return;
    domore = TRUE;
    for (curactor = 0; curactor < side->actionvector->numunits; ++curactor) {
	unit = (side->actionvector->units)[curactor].unit;
	if (unit->plan
	    && unit->plan->aicontrol) {
	    domore = ai_adjust_plan(side, unit);
	    if (!domore)
	      return;
	}
    }
}

void
set_play_rate(slow, fast)
int slow, fast;
{
    if (slow < 0 || fast < 0 || fast < slow) {
	run_warning("Bad play rates slow=%d fast=%d, ignoring", slow, fast);
	return;
    }
    slow_play_rate = slow;
    fast_play_rate = fast;
}

/* Resignation, possibly giving away any remaining units. */

void
resign_game(side, side2)
Side *side, *side2;
{
    /* Nothing to do if we're not in the game. */
    if (!side->ingame)
      return;
    notify_all_of_resignation(side, side2);
    side_loses(side, side2, -1);
}

/* This is true if there is any kind of realtime limit on the game. */

int
realtime_game()
{
    return (g_rt_for_game() > 0
    	    || g_rt_per_side() > 0
    	    || g_rt_per_turn() > 0);
}

/* Pass NULL to see if all sides are now willing to save the game. */

int
all_others_willing_to_save(side)
Side *side;
{
    Side *side2;

    for_all_sides(side2) {
	if (side != side2 && !side2->willingtosave)
	  return FALSE; 
    }
    return TRUE;
}

/* Pass NULL to see if all sides are now willing to declare a draw. */

int
all_others_willing_to_quit(side)
Side *side;
{
    Side *side2;

    for_all_sides(side2) {
	if (side != side2 && !side2->willingtodraw)
	  return FALSE; 
    }
    return TRUE;
}

/* This forces an end to the game directly. */

void
end_the_game()
{
    Side *side;

    Dprintf("The game is over.\n");
    /* Make sure everybody sees this. */
    notify_all("END OF THE GAME!");
    record_event(H_GAME_ENDED, ALLSIDES);
    /* Set the global that indicates the game is over for everybody. */
    endofgame = TRUE;
    end_history();
    /* (should compute final scoring) */
    record_into_scorefile();
    /* Done with internal state change, now echo onto displays. */
    for_all_sides(side) {
	if (!all_see_all)
	  side->may_set_see_all = TRUE;
    	if (side_has_display(side)) {
    	    update_turn_display(side, TRUE);
    	    /* (should update side's view of all sides?) */
    	    update_side_display(side, side, TRUE);
    	}
    }
    dump_statistics();
    /* We've done everything the kernel needs to have done; it's now up to
       the interface to decide when to exit. */
    ok_to_exit = TRUE;
}

/* 	Advanced unit and advance code for Xconq.
     	Copyright (C) 1998 Hans Ronne. */

extern void run_advanced_units(void);
extern void free_used_cells(Unit *unit);
extern void unit_advance_dialog(Unit *unit);
extern void global_advance_dialog(Side *side, Unit *unit, int advance);
extern void auto_pick_new_research(Unit *unit);

extern void unit_plan_dialog(Unit *unit);
extern void net_resume_build_task(Unit *unit, Unit *unit2, int run);
extern int has_advance_to_research PARAMS ((Side *side, int a));
extern int select_by_weight PARAMS ((int *arr, int numvals));
extern int unit_build_dialog(Unit *unit);

static void run_population(Unit *unit);
static void run_construction(Unit *unit);
static void run_research(Unit *unit);
static void allocate_used_cells(Unit *unit);

extern int auto_pick_new_build_task(Unit *unit);
extern void auto_pick_new_plan(Unit *unit);

/* TRUE if side has advance to research this advance. */

int
has_advance_to_research(side, a)
Side *side;
int a;
{
    int a2;

    for_all_advance_types(a2) {
	if (aa_needed_to_research(a, a2) && !has_advance(side, a2)) {
	    return FALSE;
	}
    }
    return TRUE;
}

/* Main city emulating routine. Called by run_turn_start in run2.c. */

void
run_advanced_units()
{
    Unit *unit;
		
    for_all_units(unit) {
	Side	*side;
	int	a, m, x, y, oldsize;

	/* Only do this for cities. */
	if (!u_advanced(unit->type))
	  continue;

	/* Units still under construction or off-area can't do anything. */
	if (!completed(unit) || !in_play(unit))
	  continue;

	/* Set size to 1 if not defined. */
	if (!unit->size)
	  unit->size = 1;
	oldsize = unit->size;

	/* Make sure the city's side can see everything in visible cells within its reach. */
	for_all_cells_within_reach(unit, x, y) {
	    if (!inside_area(x, y))
		continue;
	    if (terrain_visible(unit->side, x, y))
		see_exact(unit->side, x, y);
	}
	/* Break here if no material types exist. */
	if (!nummtypes)
	  continue;

	/* Make sure landuse is optimize before collecting materials. */
	allocate_used_cells(unit);

	/* Zero the production cache. */
	for_all_material_types (m)
	    unit->production[m] = 0;
	/* Collect materials from cells controlled by the city. */
	for_all_cells_within_reach(unit, x, y) {
	    int m;
	    if (!inside_area(x, y))
	  	continue;
	    if (user_at(x, y) == unit->id)
		for_all_material_types (m)
		    unit->production[m] += tm_production(terrain_at(x, y), m);
	}
	/* Support for city improvements. */

	/* Note: an occupant or facility will typically have either an
	   additive or a multiplicative effect on material
	   production. However, it is possible for it to have
	   both. The default additive effect is zero, and the default
	   multiplicative effect is 1 (100 %). If the multiplicative
	   effect is set to zero, the occupant will prevent all
	   production of the specified material. A negative additive
	   effect means that the occupant is consuming some material
	   each turn. */

	for_all_material_types(m) {
	    Unit *unit2;

	    /* First compute additive effect of each occupant/facility. */
	    for_all_occupants(unit, unit2)
	      unit->production[m] += um_occ_add_production(unit2->type, m);
	    /* Then compute additive effect of each completed advance. */
	    if (unit->side) {
		for_all_advance_types(a)
		  if (unit->side->advance[a] == DONE)
		    unit->production[m] += am_adv_add_production(a, m);
	    }
	    /* Then factor in multiplicative effect (in %) of each
               occupant/facility. */
	    for_all_occupants(unit, unit2)
	      unit->production[m] *= (float) um_occ_mult_production(unit2->type, m) / 100;
	    /* Then factor in multiplicative effect (in %) of each
               completed advance. */
	    if (unit->side) {
		for_all_advance_types(a)
		  if (unit->side->advance[a] == DONE)
		    unit->production[m] *= (float) am_adv_mult_production(a, m) / 100;
	    }
	    /* Finally add production to unit supply. */
	    unit->supply[m] += unit->production[m];
	    /* Borrow material from treasury if it exists. */
	    if (m_treasury(m)) {
		Side *sidex = (unit->side ? unit->side : indepside);

		unit->supply[m] += sidex->treasury[m];
		sidex->treasury[m] = 0; 			
	    }
	}
	/* Growth or starvation. */
	run_population(unit);
	/* Fixes crashes when the unit starved to death. */
	if (!in_play(unit))
	  continue;
	/* Optimize landuse again in case city size changed. */
	if (unit->size != oldsize) {
	    allocate_used_cells(unit);
	    /* Also reflect any changes of the city size text. */
	    for_all_sides(side) {
		if (side->see_all || side_sees_unit(side, unit) 
		    || side_tracking_unit(side, unit)) {
		    update_cell_display(side, unit->x, unit->y, UPDATE_ALWAYS);
		}
	    }
	}
	/* Run building tasks. */
	run_construction(unit);
	/* Do the research. */		
	run_research(unit);
	/* Return any borrowed material to treasury. */
	for_all_material_types(m) {
	    if (m_treasury(m)) {
		Side *sidex = (unit->side ? unit->side : indepside);
    
		sidex->treasury[m] += unit->supply[m];
		unit->supply[m] = 0; 			
	    }
	}
    }
}

/* Starve or grow city population depending on food supply. */

void
run_population(Unit *unit)
{
    int starved = FALSE;
    int u = unit->type;
    int a, m, u2;
	
    /* First consume necessary materials (food) in proportion to unit
       size. */
    for_all_material_types(m) {
	unit->supply[m] -= unit->size * um_consumption_per_size(u, m);
	if (unit->supply[m] < 0) {
	    /* Don't allow negative supply. */
	    unit->supply[m] = 0;
	    /* Trigger starvation. */
	    starved = TRUE;
	}
    }
    /* Starvation! */
    if (starved) {
	/* Shrink size by one. */
	unit->size -=1;
	/* Run warning. */
	if (unit->size > 0) {
	    notify(unit->side, "The people in %s are starving!", unit->name);			
	} else {
	    /* Kill the unit, but first return borrowed material to
               treasury. */
	    for_all_material_types(m) {
		if (m_treasury(m)) {
		    /* Copy of Stan's bug fix in run_advanced_units. */
  		    Side *sidex = (unit->side ? unit->side : indepside);
    
		    sidex->treasury[m] += unit->supply[m];
		    unit->supply[m] = 0; 			
		}
	    }
	    notify(unit->side, "%s is no more. The people starved to death.", unit->name);			
	    kill_unit(unit, H_UNIT_STARVED);
	}
	/* Done with handling starvation. */
	return;
    }

    /* Now check if we have enough supplies to grow in size. */
    for_all_material_types(m)
      if (unit->supply[m] < unit->size * um_consumption_to_grow(u, m))
	return;
    /* Then check if we have the required advances for the next size. */
    for_all_advance_types(a) {
	if ((unit->side == NULL || unit->side->advance[a] != DONE) 
	    && ua_size_limit_without_adv(u, a) <= unit->size) {
	    notify(unit->side, "%s needs %s advance to grow in size.", 
		   unit->name, a_type_name(a));			
	    return;
	}
    }
    /* Finally check if we have the required facilities for the next size. */
    for_all_unit_types(u2) {
	if (uu_size_limit_without_occ(u, u2) <= unit->size) {
	    int	hasocc = FALSE;
	    Unit	*unit2;

	    for_all_occupants(unit, unit2) {			
		if (unit2->type == u2) {
		    hasocc = TRUE;
		    break;
		}
	    }
	    if (!hasocc) {
		notify(unit->side, "%s needs %s unit to grow in size.", 
		       unit->name, u_type_name(u2));			
		return;
	    }
	}
    }				    	
    /* If we got this far we are ready for a size increase! */
    for_all_material_types(m)
      /* Use up more supplies as required to prepare growth. */
      unit->supply[m] -= unit->size * um_consumption_to_grow(u, m);
    /* Then increase the size. */
    unit->size += 1;
}

void
run_construction(Unit *unit)
{			
    int builds = unit->size;

    /* Skip if this is an indep which cannot build. */
    if (indep(unit) &! g_indep_may_build())
      return;
    /* Make sure we have a real plan. */
    if (unit->plan == NULL
	|| unit->plan->type == PLAN_NONE
	|| unit->plan->type == PLAN_PASSIVE) { 
	/* Pick a new plan if we lack one. */
	if (!indep(unit)
	    && side_has_display(unit->side)
	    && (!side_has_ai(unit->side) 
		|| !unit->plan->aicontrol)
	    && !unit->autoplan)
	  unit_plan_dialog(unit);
	else
	  auto_pick_new_plan(unit);
    }

    while (builds) {
	Unit *unit2 = NULL;
	int u2 = NONUTYPE;
	int limited = FALSE;
	int actionresult;
	TaskOutcome taskresult;
	int m;

	if (unit->plan
	    && unit->plan->tasks) {
	    unit2 = find_unit(unit->plan->tasks->args[1]);
	    u2 = unit->plan->tasks->args[0];
	}
	/* Check if we lack a build task or just completed one. */
	if (unit->plan->tasks == NULL
	    || unit->plan->tasks->type != TASK_BUILD
	    || unit->plan->last_task_outcome == TASK_IS_COMPLETE) {
	    /* Find any incomplete occupant that is hanging around.
	       This is also how we pick up old tasks after saving a
	       game.*/
	    unit2 = NULL;
	    for_all_occupants(unit, unit2) {
		if (in_play(unit2) && !fullsized(unit2))
		  break;
	    }
	    /* Resume building of incomplete occupant. */
	    if (is_unit(unit2)){
		net_resume_build_task(unit, unit2, 1);
		u2 = unit2->type;
	    } else {
		/* Else select a new unit type to build. */
		if (!indep(unit)
		    && side_has_display(unit->side)
		    && (!side_has_ai(unit->side) || !unit->plan->aicontrol)
		    && !unit->autobuild)
		  u2 = unit_build_dialog(unit);
		else
		  u2 = auto_pick_new_build_task(unit);
		/* Emergency exit. Happens if "Idle" is manually
		   selected or if the city is full. */
		if (!is_unit_type(u2))
		  return;
	    }
	}
	/* unit2 has either not been created or is complete. */
	if (unit2 == NULL || fullsized(unit2)) {
	    /* First check if there is enough supplies for creation. */	
	    for_all_material_types(m) {
		if (unit->supply[m] < um_consumption_on_creation(u2, m))
		  return;
	    }
	    /* Then consume materials as required. */
	    for_all_material_types(m) {
		unit->supply[m] -= um_consumption_on_creation(u2, m);
	    }
	    /* Give unit just enough acps for one create action. */
	    unit->act->acp = uu_acp_to_create(unit->type, u2); 

	    /* unit2 is still in progress. */
	} else {
	    /* Check if any material limits its construction. */
	    for_all_material_types(m) {
		if (um_consumption_per_cp(u2, m) > 0)
		  limited = TRUE;
		break;
	    }
	    if (limited) {
		/* First check if there is enough supplies for one build. */
		for_all_material_types(m) {
		    if (unit->supply[m] < um_consumption_per_cp(u2, m)) 
		      return;
		}
		/* Then consume materials as required. */
		for_all_material_types(m) {
		    unit->supply[m] -= um_consumption_per_cp(u2, m);
		}
		/* Else limit total builds to unit size as fallback. */
	    } else
	      --builds;
	    /* Give unit just enough acps for one build action. */
	    unit->act->acp = uu_acp_to_build(unit->type, u2); 
	}
						
	/* Necessary to enable execute_task. */
	need_ai_task_reaction = FALSE;
	/* Prepare the build action. */
	taskresult = execute_task(unit);
	/* Never happens, but check anyway. */
	if (taskresult == TASK_FAILED || taskresult == TASK_UNKNOWN) {
	    Dprintf("Task %s failed for %s!\n", 
		    task_desig(unit->plan->tasks), 
		    unit_desig(unit));
	    return;
	}
	/* Do not execute pending action if we lack one or need to
	   pick a new task!  The latter is important since we will
	   continue to build on the old unit and get an error if a new
	   build task has not been assigned. */
	if (has_pending_action(unit) && taskresult != TASK_IS_COMPLETE) {
	    actionresult = execute_action(unit, &unit->act->nextaction);
	    /* Never happens, but check anyway. */
	    if (actionresult == A_ANY_ERROR) {
		Dprintf("Action %s failed for %s!\n", 
			action_desig(&unit->act->nextaction), 
			unit_desig(unit));
		return;
	    }
	}
	/* Things have changed. */
	gamestatesafe = FALSE;
    }
}

/* Do research until supply of its limiting material is gone. */

void
run_research(Unit *unit)
{
    int m, a;

    /* Only units controlled by a side do research. */
    if (!unit->side)
      return; 
    /* First test if we are already done, and select new research in
       that case. */
    if (has_advance(unit->side, unit->curadvance) 
	|| unit->curadvance == NOADVANCE) {
	/* Set current advance to NOADVANCE to signal that we are idle. */
	unit->curadvance = NOADVANCE;
	/* Pick new research manually for human players. */
	if (side_has_display(unit->side)
	    && !side_has_ai(unit->side)
	    && !unit->autoresearch)
	  unit_advance_dialog(unit);
	/* Pick new research automatically for AIs. */
	else
	  auto_pick_new_research(unit);
    } 
    /* Only proceed if we now have a new advance. */
    a = unit->curadvance; 
    if (a >= 0) {
	int lim = PROPHI;

	/* Find the material whose supply limits current research. */
	for_all_material_types(m)
	  if (am_consumption_per_rp(a, m) > 0)
	    lim = min(lim, (float) unit->supply[m] / am_consumption_per_rp(a, m));
	/* Then do research to the limit. */
	unit->side->advance[a] += lim;				
	/* Reduce all supplies accordingly. */		
	for_all_material_types(m)
	  if (am_consumption_per_rp(a, m) > 0)
	    unit->supply[m] -= lim * am_consumption_per_rp(a, m);
	/* Check if research has been completed. */
	if (unit->side->advance[a] >= a_rp(a)) {
	    Unit *unit2;

	    /* Set current advance to done. */
	    unit->side->advance[a] = DONE;
	    /* Pick new research for all involved units. */
	    if (side_has_display(unit->side) && ! side_has_ai(unit->side)) {
		int idle = FALSE;

		for_all_side_units(unit->side, unit2) {
		    if (!u_advanced(unit2->type))
		      continue;
		    /* Reallocate units on auto that took part in this
                       advance. */
		    if (unit2->curadvance == a && unit2->autoresearch) 
		      auto_pick_new_research(unit2);
		    /* Detect idle units on non-auto. */
		    else if (unit2->curadvance == a)
		      idle = TRUE;
		}
		/* Run global advance dialog for idle non-auto units. */
		if (idle)
		  global_advance_dialog(unit->side, unit, a);
	    } else {
		for_all_side_units(unit->side, unit2) {
		    if (!u_advanced(unit2->type))
		      continue;
		    if (unit2->curadvance == a) 
		      auto_pick_new_research(unit2);
		}
	    }
	}
    }
}

/* Free all used cells and redistribute them for optimal limiting
   material production (usually food) if the city belongs to an AI or
   is independent. If it belongs to a human player, only allocate new
   used cells automatically. Don't change old allocations that may
   differ from automatic ones intentionally.  */

void
allocate_used_cells(Unit *unit)
{
    int	x, y, a, i, m, mlim = 0, lim = 0;
    int u = unit->type;
    Unit *unit2;

    /* Set max used cells to unit size. */
    unit->maxcells = unit->size;
    /* First compute additive effect of each occupant/facility. */
    for_all_occupants(unit, unit2)
      unit->maxcells += uu_occ_add_maxcells(u, unit2->type);
    /* Then compute additive effect of completed advances. */
    for_all_advance_types(a)
      unit->maxcells += ua_adv_add_maxcells(u, a);
    /* Then factor in multiplicative effect (in %) of each
       occupant/facility. */
    for_all_occupants(unit, unit2)
      unit->maxcells *= (float) uu_occ_mult_maxcells(u, unit2->type) / 100;
    /* Then factor in multiplicative effect (in %) of completed advances. */
    for_all_advance_types(a)
      unit->maxcells *= (float) ua_adv_mult_maxcells(u, a) / 100;
    	
    /* Check the number of used cells. */
    unit->usedcells = 0;
    for_all_cells_within_reach(unit, x, y) {
	if (!inside_area(x, y))
	  continue;
	if (user_at(x, y) == unit->id)
	  unit->usedcells += 1;
    }
    /* Find the limiting material for population maintenance. */
    for_all_material_types(m) {
	if (um_consumption_per_size(u, m) > lim) {
	    lim = um_consumption_per_size(u, m);
	    mlim = m;
	}
    }

    /* Free all cells within reach */
    for_all_cells_within_reach(unit, x, y) {
	/* Skip if not inside area */
	if (!inside_area(x, y))
	  continue;
	/* Free cells used by the unit itself if it is independent or
           played by an AI */
	if (user_at(x, y) == unit->id
	    && (!unit->side || side_has_ai(unit->side))) {
	    set_user_at(x, y, NOUSER);
	    unit->usedcells -= 1;
	} else if (user_at(x, y) != NOUSER && unit_at(x, y) != NULL) {
	    /* Also free cells used by enemy side if we have a unit in
               the cell */
	    for_all_stack(x, y, unit2) {
		if (unit2->side && unit2->side == unit->side) {
		    kick_out_enemy_users(unit->side, x, y);
		    break;
		}
	    }
	}
    }

    /* Then select new cells up to unit size */
    for (i = unit->usedcells + 1; i <= unit->maxcells; i++) {
	int tmpprod = 0;
	int tmpx = unit->x;
	int tmpy = unit->y;

	for_all_cells_within_reach(unit, x, y) {
	    /* Skip if not inside area */
	    if (!inside_area(x, y))
	      continue;
	    /* Skip if cell already is in use */
	    if (user_at(x, y) != NOUSER)
	      continue;
	    /* Skip if cell is invisible to unit */
	    if (!terrain_visible(unit->side, x, y))
	      continue;
	    /* Skip if untrusted side has a unit in the cell */
	    if (unit_at(x, y) != NULL) {
		int enemy = FALSE;
		for_all_stack(x, y, unit2) {
		    if (!trusted_side(unit->side, unit2->side)) {
			enemy = TRUE;
			break;
		    }
		}
		if (enemy)
		  continue;
	    }
	    /* Make this tmp used cell if it produces more limiting
	       material than previous tmp used cell or if the previous
	       tmp cell is already in use. */
	    if (tm_production(terrain_at(x, y), mlim) > tmpprod
		|| user_at(tmpx, tmpy) != NOUSER) {
		tmpprod = tm_production(terrain_at(x, y), mlim);
		tmpx = x;
		tmpy = y;
	    }
	}
	/* Make tmp used cell permanently used if it is unused */
	if (user_at(tmpx, tmpy) == NOUSER) {
	    set_user_at(tmpx, tmpy, unit->id);
	    unit->usedcells += 1;
	}
    }
}

void
kick_out_enemy_users(Side *side, int x, int y)
{
    Unit *unit;
	
    /* Return if nobody is using the cell. */
    if (user_at(x, y) == NOUSER)
      return;

    /* Else find the user. */
    unit = find_unit(user_at(x, y));

    /* Return if the user belongs to the same or a friendly side. */
    if (unit && trusted_side(unit->side, side))
      return;

    /* Mark the cell as unused. */
    set_user_at(x, y, NOUSER);
	
    /* Reduce the former user's cells. */
    if (unit)
      unit->usedcells -= 1;	
}

/* Free up all cells used by unit that passed away. */

void
free_used_cells(Unit *unit)
{
    int x, y;

    for_all_cells_within_reach(unit, x, y) {
	if (!inside_area(x, y))
	  continue;
	if (user_at(x, y) == unit->id) 
	  set_user_at(x, y, NOUSER);
    }
    unit->usedcells = 0;
}

/* Now picks new advance at random rather than by number. */

void
auto_pick_new_research(Unit *unit)
{
    int a;
    int type[MAXUTYPES];
    int numtypes = 0;

    /* Get researchable advance types. */
    for_all_advance_types(a) {
	if (has_advance_to_research(unit->side, a)
	    && !has_advance(unit->side, a)) {
	    /* Add to list of researchable advances. */
	    type[numtypes++] = a;
	}
    }
    if (numtypes)
      /* Pick one of them at random. */
      unit->curadvance = type[xrandom(numtypes)];
    else
      unit->curadvance = NOADVANCE;
}

int
auto_pick_new_build_task(Unit *unit)
{
    int prefs[MAXUTYPES] = {0};
    int enemy_city_near = FALSE;
    int x, y, x1, y1, u; 
    int city_has_shore = FALSE;
    int numtypes = 0;
    Unit *unit2;
	
    /* Reevaluate the current plan every time. */
    if (!indep(unit)
	&& side_has_display(unit->side)
	&& (!side_has_ai(unit->side) || !unit->plan->aicontrol)
	&& !unit->autoplan)
      unit_plan_dialog(unit);
    else
      auto_pick_new_plan(unit);

    /* Check if the unit borders on a water cell. */ 	
    for_all_cells_within_range(unit->x, unit->y, 1, x, y) {
	if (t_liquid(terrain_at(wrapx(x), y))) {
	    /* Also check if that water cell borders on another water cell.
	       (we don't want to build battleships in the city pond) */
	    for_all_cells_within_range(x, y, 1, x1, y1) {
		if (t_liquid(terrain_at(wrapx(x1), y1))
		    /* Don't count the first water cell. */
		    && (x != x1 || y != y1)) {
		    city_has_shore = TRUE;
		    break;
		}
	    }
	    if (city_has_shore)
	      break;				
	}
    }		

    /* Check if we have an enemy city within our tactical range. */
    for_all_units(unit2) {
	if (u_advanced(unit2->type)
	    && distance(unit->x, unit->y, unit2->x, unit2->y)
	    >= u_ai_tactical_range(unit->type)
	    && enemy_side(unit->side, unit2->side)) {
	    enemy_city_near = TRUE;
	    break;
	}
    }
	
    /* Calculate unit values. */	
    for_all_unit_types(u) {
	if (type_allowed_on_side(u, unit->side) 
	    && has_advance_to_build(unit->side, u)
	    && could_create(unit->type, u)
	    /* Don't build immobile units for which there is no room. */
	    && (mobile(u) || type_can_occupy(u, unit))
	    /* Don't build ships if we don't have a shore. */
	    && (!u_naval_mobile(u) || city_has_shore)) {
	    
	    switch (unit->plan->type) {
	      case PLAN_COLONIZING:
		prefs[u] = u_colonizer_worth(u);
		break;					
	      case PLAN_IMPROVING:			
		prefs[u] = u_facility_worth(u);
		break;					
	      case PLAN_EXPLORATORY:
		prefs[u] = u_explorer_worth(u);
		break;					
	      case PLAN_OFFENSIVE:
		if (enemy_city_near) {
		    /* Build siege units. */
		    prefs[u] = u_siege_worth(u);
		} else	{
		    /* Build attack units. */
		    prefs[u] = u_offensive_worth(u);
		}
		break;					
	      case PLAN_DEFENSIVE:
		prefs[u] = occ_can_defend_transport(u, unit->type) 
		  * u_defensive_worth(u);
		break;					
	      case PLAN_RANDOM:	
		prefs[u] = u_random_worth(u);
		break;					
	      case PLAN_NONE:
	      case PLAN_PASSIVE:
	      case NUMPLANTYPES:
		prefs[u] = 0;
		break;					
	    }
	}
	if (prefs[u] <= 0)
	  prefs[u] = 0;
	else ++numtypes;
    }			

    /* Try again with random choice if we found nothing to build. */
    if (numtypes == 0) {
	for_all_unit_types(u) {
	    if (type_allowed_on_side(u, unit->side) 
		&& has_advance_to_build(unit->side, u)
		&& could_create(unit->type, u)
		/* Don't build immobile units for which there is no room. */
		&& (mobile(u) || type_can_occupy(u, unit))
		/* Don't build ships if we don't have a shore. */
		&& (!u_naval_mobile(u) || city_has_shore)) {
		
		prefs[u] = u_random_worth(u);
		if (prefs[u] <= 0)
		  prefs[u] = 0;
		else ++numtypes;
	    }
	}
    }
			
    if (numtypes > 0) {
	/* Use prefs weight to pick unit type to build. */
	u = select_by_weight(prefs, numutypes);
	if (is_unit_type(u))
	  net_set_build_task(unit, u, 1); 
	else
	  u = NONUTYPE;
    } else
      u = NONUTYPE;
    return u;	
}

/* This is a rudimentary AI for advanced units. Lots of room for
   improvement! */

void
auto_pick_new_plan(Unit *unit)
{
    int my_advanced = 0, my_colonizers = 0, my_total = 0;
    int enemy_advanced = 0, enemy_colonizers = 0, enemy_total = 0;
    int defenders = 0, facilities = 0, mobiles = 0, invisible_cells = 0;
    int u = unit->type;
    int x, y, u2;
    Unit *unit2;
			
    /* Init plan if necessary. */
    if (!unit->plan)
      init_unit_plan(unit);	

    /* First count our facilities, defenders and mobile types. */
    for_all_occs_with_occs(unit, unit2) {
	if (u_facility(unit2->type))
	  facilities += 1;
	if (in_play(unit2)
	    && occ_can_defend_transport(unit2->type, unit->type)) 
	  defenders += 1;
	if (mobile(unit2->type))
	  mobiles += 1;
    }		
    /* Always build a defender first if we are undefended. */
    if (defenders < u_ai_min_defenders(unit->type)) {
	set_unit_plan_type(unit->side, unit, PLAN_DEFENSIVE);
	return;
    }	

    /* Check out the tactical neighbourhood. */
    for_all_cells_within_range(unit->x, unit->y, 
				 u_ai_tactical_range(unit->type), x, y) {
	if (!inside_area(x, y))
	  continue;
	if (!terrain_visible(unit->side, x, y))
	  invisible_cells +=1;
	unit2 = NULL;
	/* Important to count also occupants here. */
	for_all_stack_with_occs(x, y, unit2) {
	    /* Only count real units. */
	    if (!in_play(unit2))
	      continue;
	    /* Only count units that we can see. */
	    if (!unit_actually_visible(unit->side, unit2))
	      continue;
	    u2 = unit2->type;
	    /* First count own units. */
	    if (unit->side == unit2->side) {
		if (u_advanced(u2))
		  my_advanced += 1;
		else if (u_colonizer_worth(u2))
		  my_colonizers += 1;
		my_total += 1;
		/* Then count hostile units. */
	    } else if (enemy_side(unit->side, unit2->side)){
		if (u_advanced(u2))
		  enemy_advanced += 1;
		else if (u_colonizer_worth(u2))
		  enemy_colonizers += 1;
		enemy_total += 1;
	    }			
	}
    }

    /* Always build attackers if any enemy unit is near. */
    if (enemy_total > 0)
      net_set_unit_plan_type(unit->side, unit, PLAN_OFFENSIVE);
    /* Then build explorers if we have any invisible cells nearby. */
    else if (invisible_cells)
      net_set_unit_plan_type(unit->side, unit, PLAN_EXPLORATORY);
    /* Build colonizers if we have < 7 colonizers or places nearby. */
    else if (my_advanced + my_colonizers < 7)
      net_set_unit_plan_type(unit->side, unit, PLAN_COLONIZING);
    /* Build 50% facilities if there is room left. */
    else if (flip_coin() && facilities < u_facility_total_max(u))			
      net_set_unit_plan_type(unit->side, unit, PLAN_IMPROVING);
    /* Else build offensive units. */	
    else
      net_set_unit_plan_type(unit->side, unit, PLAN_OFFENSIVE);

    net_clear_task_agenda(unit->side, unit);
}
