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

/*
 * land.c
 *
 * land unit post-read and pre-write
 *
 */

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

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

	if (pp->lnd_ship >= 0 && pp->lnd_own && pp->lnd_effic >= LAND_MINEFF) {
		if (!getship(pp->lnd_ship, &theship) ||
		    (theship.shp_effic < SHIP_MINEFF) || 
		    (theship.shp_own != pp->lnd_own)){
			sprintf(buf, "%s sunk!\n", prland(pp));
			mpr(pp->lnd_own, buf);
			pp->lnd_own = 0;
			pp->lnd_flags |= LND_NOSYNC;
			putland(pp->lnd_uid, pp);
			putland(pp->lnd_uid, pp);
		} else {
			/* wooof!  Carriers are a pain */
			if (pp->lnd_mission){
				/*
				 *  If the unit is on a mission centered
				 *  on it's loc, the op-area travels with
				 *  the unit.
				 */
				if ((pp->lnd_opx == pp->lnd_x) &&
					(pp->lnd_opy == pp->lnd_y)){
					pp->lnd_opx = theship.shp_x;
					pp->lnd_opy = theship.shp_y;
				}
			}
			pp->lnd_x = theship.shp_x;
			pp->lnd_y = theship.shp_y;
		}
	}
	player->owner = (player->god || pp->lnd_own == player->cnum);
	return 1;
}

/*ARGSUSED*/
int
lnd_prewrite(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct	lndstr *lp = (struct lndstr *) ptr;
	struct	lndstr land;

	if (lp->lnd_effic < LAND_MINEFF){
		lp->lnd_own = 0;
	}
	lp->ef_type = EF_LAND;
	lp->lnd_uid = n;

	if (lp->lnd_flags & LND_NOSYNC) {
		lp->lnd_flags &= ~LND_NOSYNC;
	} else {
		getland(n, &land);
		prewrite_sync(&land, lp);
	}

	return 1;
}

int
lnd_init(n, ptr)
	int	n;
	s_char	*ptr;
{
	struct	lndstr *lp = (struct lndstr *) ptr;

	lp->ef_type = EF_LAND;
	lp->lnd_uid = n;
	lp->lnd_own = 0;
}

s_char *
prland(lp)
	struct	lndstr	*lp;
{
	return prbuf("%s #%d", lchr[lp->lnd_type].l_name, lp->lnd_uid);
}
