#ifndef lint
static char *RCSid = "$Header: takeover.c,v 1.6 90/03/19 10:55:07 mr-frog Exp $";
#endif

/*
 * takeover.c
 *
 * take over from another power.
 * set up loyalty to new govt, old owner.
 *
 * Dave Pare, 1986
 */

#include "misc.h"
#include "var.h"
#include "sect.h"
#include "xy.h"
#include "nsc.h"
#include "nat.h"
#include "plane.h"
#include "ship.h"
#include "file.h"


int
takeover(sp, mil)
	register struct sctstr *sp;
	int	mil;
{
	register struct plnstr *pp;
	int	civ;
	int	che;
	int	che_count;
	int	oldche;
	int	n;
	struct	nstr_item ni;
	struct	plnstr p;

	pp = &p;
	snxtitem_dist(&ni, EF_PLANE, sp->sct_x, sp->sct_y, 0);
	while (nxtitem(&ni, (caddr_t)pp)) {
		if ((pp->pln_own == cnum) || (pp->pln_own == 0))
			continue;
		if (pp->pln_flags & PLN_LAUNCHED)
			continue;
		/*
		 * XXX If this was done right, planes could escape,
		 * flying to a nearby friendly airport.
		 */
		n = pp->pln_effic - (30 + (random() % 100));
		if (n < 0)
			n = 0;
		pp->pln_effic = n;
		if (pp->pln_effic < 10 || pp->pln_harden > 0) {
			pp->pln_effic = 0;
			pr(fmt("%s #%d blown up by the crew!\n",
				plchr[pp->pln_type].pl_name, ni.cur));
		}
		if (pp->pln_mobil > 0)
			pp->pln_mobil = 0;
		pp->pln_own = cnum;
		putplane(ni.cur, pp);
	}
	sp->sct_avail = 0;
	civ = getvar(V_CIVIL, (char *)sp, EF_SECTOR);
	oldche = get_che_value(getvar(V_CHE, (char *)sp, EF_SECTOR));
	/*
	 * create guerrillas from civilians
	 * how spunky are these guys?
	 * n: random number from -50:50 + 50
	 */
	n = (50 - sp->sct_loyal) + (random() % 100) - 50;
	che_count = 0;
	che = 0;
	if (n > 0 && sp->sct_own == sp->sct_oldown) {
		che_count = (civ * n/3000) + 5;
		if (che_count * 2 > civ)
			che_count = civ / 2;
		if (che_count > 0) {
			civ -= che_count;
			che_count += oldche;
			set_che_value(che, che_count);
			set_che_cnum(che, cnum);
			(void) putvar(V_CHE, che, (char *)sp, EF_SECTOR);
			(void) putvar(V_CIVIL, civ, (char *)sp, EF_SECTOR);
		}
	}
	if (sp->sct_oldown == cnum || civ == 0) {
		/*
		 * taking over one of your old sectors
		 */
		sp->sct_loyal = 0;
		sp->sct_oldown = cnum;
	} else {
		/*
		 * taking over someone else's sector
		 */
		sp->sct_loyal = 50;
	}
	sp->sct_own = cnum;
	return mil;
}

takeover_ship(sp, newown, hostile)
	register struct shpstr *sp;
	natid	newown;
	int	hostile;
{
	register struct plnstr *pp;
	struct	mchrstr *mp;
	struct	nstr_item ni;
	struct	plnstr p;

	mp = &mchr[sp->shp_type];
	sp->shp_own = newown;
	if ((mp->m_flags & (M_FLY|M_MSL)) == 0)
		return;
	pp = &p;
	snxtitem_all(&ni, EF_PLANE);
	while (nxtitem(&ni, (caddr_t)pp)) {
		if (pp->pln_ship != sp->shp_uid)
			continue;
		if (hostile) {
			if (pp->pln_effic > 10)
				pp->pln_effic = 10;
		} else {
			if (pp->pln_effic > 75)
				pp->pln_effic = 75;
		}
		pp->pln_mobil = 0;
		pp->pln_own = newown;
		putplane(ni.cur, pp);
	}
}
