#ifndef lint
static char *RCSid = "$Header: arm.c,v 1.8 89/09/28 02:08:35 mr-frog Exp $";
#endif /* not lint */

/*
 * arm.c
 *
 * arm planes (missiles) with nuclear devices
 *
 * Dave Pare, 1986
 */

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

int
arm()
{
	extern	char *argp[];
	struct	nchrstr *ncp;
	struct	plchrstr *plc;
	struct	plnstr pl;
	struct	nukstr nuke;
	char	*p;
	int	pno;
	int	nuketype;
	int	nukenum;
	int	len;
	int	i;
	struct	nstr_item ni;

	if ((p = getstarg(argp[1], "Arm plane: ")) == 0 || *p == 0)
		return RET_SYN;
	pno = atoi(p);
	if (pno < 0 || !getplane(pno, &pl) || pl.pln_own != cnum)
		return RET_FAIL;
	if ((p = getstarg(argp[2], "Device type: ")) == 0)
		return RET_SYN;
	len = strlen(p);
	for (i=0, ncp = nchr; i<N_MAXNUKE; i++, ncp++) {
		if (strncmp(ncp->n_name, p, len) == 0)
			break;
	}
	if (i >= N_MAXNUKE) {
		pr("No such nuke type!\n");
		return RET_SYN;
	}
	nuketype = i;
	if (pl.pln_nukeamt > 0 && pl.pln_nuketype != nuketype) {
		pr("All devices on a missile or plane must be identical\n");
		return RET_FAIL;
	}
	nukenum = -1;
	snxtitem_all(&ni, EF_NUKE);
	while (nxtitem(&ni, (char *)&nuke)) {
		if (nuke.nuk_own != cnum)
			continue;
		if (nuke.nuk_x != pl.pln_x || nuke.nuk_y != pl.pln_y)
			continue;
		nukenum = ni.cur;
		break;
	}
	if (nukenum < 0) {
		pr("You don't own any nukes in that sector.\n");
		return RET_FAIL;
	}
	if (nuke.nuk_types[nuketype] == 0) {
		pr("No nukes of that type in that sector.\n");
		return RET_FAIL;
	}
	p = getstarg(argp[3], "Number of devices: ");
	if (p == 0 || *p == 0 || (i = atoi(p)) < 0)
		return RET_FAIL;
	if (i > nuke.nuk_types[nuketype])
		i = nuke.nuk_types[nuketype];
	plc = &plchr[pl.pln_type];
#ifdef	CONVASAT
	if ((plc->pl_flags & (P_O | P_M)) == (P_O | P_M)) {
		pr(fmt("%s cannot carry nuclear devices!\n",plc->pl_name));
		return RET_FAIL;
	}
#endif	CONVASAT
	if (plc->pl_load < ncp->n_weight * (i + pl.pln_nukeamt)) {
		pr(fmt("%s cannot carry %d %s devices!\n", plc->pl_name,
			i + pl.pln_nukeamt, ncp->n_name));
		return RET_FAIL;
	}
	pl.pln_nukeamt += i;
	pl.pln_nuketype = nuketype;
	putplane(pno, &pl);
	nuke.nuk_types[nuketype] -= i;
	nuke.nuk_n -= i;
	if (nuke.nuk_n <= 0)
		nuke.nuk_own = 0;
	putnuke(nukenum, &nuke);
	pr(fmt("%s #%d armed with %d %s warhead%s.\n",
		plc->pl_name, pl.pln_uid, pl.pln_nukeamt,
		nchr[nuketype].n_name, splur(pl.pln_nukeamt)));
	return RET_OK;
}
