#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/subs/plane.c,v 2.3 1995/09/26 18:38:20 empire Exp $";
#endif

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

#include "misc.h"
#include "player.h"
#include "var.h"
#include "plane.h"
#include "ship.h"
#include "land.h"
#include "xy.h"
#include "file.h"
#include "nat.h"
#include "deity.h"

int
pln_postread(ptr)
	s_char	*ptr;
{
	struct	plnstr *pp = (struct plnstr *) ptr;
	struct	shpstr theship;
	struct	lndstr theland;
	s_char	buf[128];

	if (pp->pln_ship >= 0 && pp->pln_own && pp->pln_effic >= PLANE_MINEFF) {
		if (!getship(pp->pln_ship, &theship) ||
		    (theship.shp_own != pp->pln_own) ||
		    (theship.shp_effic < SHIP_MINEFF)){
			sprintf(buf, "%s sunk!\n", prplane(pp));
			mpr(pp->pln_own, buf);
			pp->pln_own = 0;
			pp->pln_flags |= PLN_NOSYNC;
			(void) putplane(pp->pln_uid, pp);
			(void) putplane(pp->pln_uid, pp);
		} else {
			/* wooof!  Carriers are a pain */
			if (pp->pln_mission){
				/*
				 *  If the plane is on a mission centered
				 *  on it's loc, the op-area travels with
				 *  the plane.
				 */
				if ((pp->pln_opx == pp->pln_x) &&
					(pp->pln_opy == pp->pln_y)){
					pp->pln_opx = theship.shp_x;
					pp->pln_opy = theship.shp_y;
				}
			}
			pp->pln_x = theship.shp_x;
			pp->pln_y = theship.shp_y;
		}
	}
	if (pp->pln_land >= 0 && pp->pln_own && pp->pln_effic >= PLANE_MINEFF) {
		if (!getland(pp->pln_land, &theland) ||
		    (theland.lnd_own != pp->pln_own) ||
		    (theland.lnd_effic < LAND_MINEFF)){
			sprintf(buf, "%s sunk!\n", prplane(pp));
			mpr(pp->pln_own, buf);
			pp->pln_own = 0;
			pp->pln_flags |= PLN_NOSYNC;
			(void) putplane(pp->pln_uid, pp);
			(void) putplane(pp->pln_uid, pp);
		} else {
			/* wooof!  Units are a pain, too */
			pp->pln_x = theland.lnd_x;
			pp->pln_y = theland.lnd_y;
		}
	}
	player->owner = (player->god || pp->pln_own == player->cnum);
	return 1;
}

/*ARGSUSED*/
int
pln_prewrite(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct	plnstr *pp = (struct plnstr *) ptr;
	struct	plnstr plane;

	if (pp->pln_effic < PLANE_MINEFF)
		pp->pln_own = 0;
	pp->ef_type = EF_PLANE;
	pp->pln_uid = n;

	if (pp->pln_flags & PLN_NOSYNC) {
		pp->pln_flags &= ~PLN_NOSYNC;
	} else {
		getplane(n, &plane);
		prewrite_sync(&plane, pp);
	}

	return 1;
}

int
pln_init(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct	plnstr *pp = (struct plnstr *) ptr;

	pp->ef_type = EF_PLANE;
	pp->pln_uid = n;
	pp->pln_own = 0;
}

s_char *
prplane(pp)
	struct	plnstr	*pp;
{
	return prbuf("%s #%d", plchr[pp->pln_type].pl_name, pp->pln_uid);
}
