#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/commands/demo.c,v 2.2 1995/08/02 03:38:35 empire Exp $";
#endif /* not lint */

/*
 * demo.c
 *
 * de-mobilize "n" military in a given sector.
 * You get to pay $5/mil for "GI Bill", and the
 * sector must have at least 60% efficiency.
 *
 * Dave Pare, 1986
 */

#include "misc.h"
#include "player.h"
#include "xy.h"
#include "deity.h"
#include "var.h"
#include "sect.h"
#include "nat.h"
#include "nsc.h"
#include "file.h"

/*
 * format: demo <SECTS> number
 *
 */

long do_demo();

int demo()
{
	struct	natstr *natp;
	long    cash;
	long    cost;
	int	number;
	s_char	*p;
	s_char	buf[1024];
	struct	nstr_sect nstr;

	natp = getnatp(player->cnum);
	cash = natp->nat_money;
	if (!snxtsct(&nstr, player->argp[1]))
		return RET_SYN;
	if ((p = getstarg(player->argp[2], "Number to de-mobilize : ", buf)) == 0)
		return RET_SYN;
	number = atoi(p);
	if (!(p = getstarg(player->argp[3], "New civilians on active reserve? (y/n) ", buf)))
		return RET_SYN;
	if (*p != 'y' && *p != 'n')
		return RET_SYN;
	cost = do_demo(natp, nstr, number, p, 0);
	if (chkmoney(cost, cash, player->argp[4]))
		return RET_SYN;
	return (int)do_demo(natp, nstr, number, p, 1);
}

long do_demo(natp, nstr, number, p, for_real)
	struct	natstr *natp;
	struct	nstr_sect nstr;
	int number;
	s_char	*p;
	int for_real;
{
	struct	sctstr sect;
	int	mil_demob;
	int	mil;
	int	civ;
	int	deltamil;
	int	reserves;
	long cost = 0;

	mil_demob = 0;
	reserves = 0;
	while (nxtsct(&nstr, &sect)) {
		if (!player->owner || sect.sct_effic < 60)
			continue;
		if ((mil = getvar(V_MILIT, (s_char *)&sect, EF_SECTOR)) == 0)
			continue;
		if (sect.sct_own != sect.sct_oldown)
			continue;
		civ = getvar(V_CIVIL, (s_char *)&sect, EF_SECTOR);
		if (number < 0){
			if ((deltamil = mil + number) <= 0)
				continue;
		}
		else if ((deltamil = min(mil, number)) <= 0)
			continue;
		civ += deltamil;
		mil -= deltamil;
		mil_demob += deltamil;
		if (!for_real) {
			cost += deltamil * 5;
			continue;
		}
		player->dolcost += deltamil * 5;
		pr("%d demobilized in %s (%d mil left)\n",
			deltamil, xyas(sect.sct_x, sect.sct_y, player->cnum), mil);
		if (*p == 'y')
			reserves += deltamil;
		putvar(V_MILIT, mil, (s_char *)&sect, EF_SECTOR);
		putvar(V_CIVIL, civ, (s_char *)&sect, EF_SECTOR);
		putsect(&sect);
	}
	if (!for_real)
		return cost;
	if (!mil_demob) {
		pr("No eligible sectors/military for demobilization\n");
		return (long)RET_FAIL;
	}
	pr("Total new civilians : %d\n", mil_demob);
	if (*p == 'y')
		pr("Military reserve stands at %d (up %d)\n",
			natp->nat_reserve + reserves, reserves);
	if (reserves > 0) {
		natp->nat_reserve += reserves;
		putnat(natp);
	}
	return RET_OK;
}
