#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/subs/nuke.c,v 2.4 1995/10/11 03:00:05 empire Exp $";
#endif

/*
 * nuke.c
 *
 * nuke post-read and pre-write
 *
 * Dave Pare, 1989
 */

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

/*ARGSUSED*/
int
nuk_postread(ptr)
	s_char	*ptr;
{
	struct	nukstr *np = (struct nukstr *) ptr;

	player->owner = (player->god || np->nuk_own == player->cnum);
	return 1;
}

/*ARGSUSED*/
int
nuk_prewrite(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct nukstr *np = (struct nukstr *) ptr;
	struct nukstr nuke;

	np->ef_type = EF_NUKE;
	np->nuk_uid = n;

	getnuke(n, &nuke);
	prewrite_sync(&nuke, np);

	return 1;
}

int
nuk_init(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct	nukstr *np = (struct nukstr *) ptr;

	np->ef_type = EF_NUKE;
	np->nuk_uid = n;
	np->nuk_own = 0;
}

void
nuk_add(x, y, type, num)
	coord	x,y;
	int	type;
	int	num;
{
	struct	nukstr nuke;
	struct	sctstr sect;
	struct	nstr_item nstr;
	int	found;
	int	nuk_uid;
	natid	own;

	/* getsect in case of world wraparound */
	getsect(x, y, &sect);
	if (!(own = sect.sct_own))
		return;
	x = sect.sct_x;
	y = sect.sct_y;

	/*
	 * either find a stockpile in x,y or add a new one
	 */
	snxtitem_all(&nstr, EF_NUKE);
	nuk_uid = -1;
	while (found = nxtitem(&nstr, (s_char *)&nuke)) {
		if (nuke.nuk_own == own) {
			/* getsect in case of world wraparound */
			getsect(nuke.nuk_x, nuke.nuk_y, &sect);
			if (sect.sct_x == x && sect.sct_y == y) {
				nuk_uid = nstr.cur;
				break;
			}
		}
		if (!nuke.nuk_own)
			nuk_uid = nstr.cur;
	}
	if (!found) {
		if (nuk_uid < 0) {
			ef_extend(EF_NUKE, 50);
			nuk_uid = nstr.cur;
		}
		bzero((s_char *)&nuke, sizeof(nuke));
		nuke.nuk_x = x;
		nuke.nuk_y = y;
		nuke.nuk_ship = -1;
		nuke.nuk_n = 0;
		nuke.nuk_own = own;
	}
	nuke.nuk_types[type] += num;
	nuke.nuk_n += num;

	putnuke(nuk_uid, &nuke);

}

nuk_delete(np, type, num)
	struct	nukstr *np;
	int	type;
	int	num;
{
	if (np->nuk_types[type] < num)
		num = np->nuk_types[type];
	np->nuk_types[type] -= num;
	np->nuk_n -= num;
	if (np->nuk_n <= 0)
		np->nuk_own = 0;
	putnuke(np->nuk_uid, np);
}
