#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/commands/upgr.c,v 2.4 1995/10/22 20:50:09 empire Exp $";
#endif /* not lint */

/*
 * upgr.c
 *
 * upgrade tech of ships.
 *
 * Dave Pare, 1986
 */

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

upgr()
{
	struct	sctstr sect;
	struct	natstr *natp;
	struct	nstr_item ni;
	struct	shpstr ship;
	struct	mchrstr *mp;
	int	n;
	int	tlev;
	int	w_p_eff;
	int	points;
	int	rel;
	long    cash;

	if (!snxtitem(&ni,EF_SHIP, player->argp[1]))
		return RET_SYN;
        ni.flags &= ~(EFF_OWNER);
	natp = getnatp(player->cnum);
	cash = natp->nat_money;
	tlev = (int) natp->nat_level[NAT_TLEV];
	n = 0;
	while (nxtitem(&ni, (s_char *) &ship)) {
		getsect(ship.shp_x, ship.shp_y, &sect);
		if (sect.sct_own != player->cnum)
			continue;
		rel=getrel(getnatp(ship.shp_own),sect.sct_own);
		if ((rel < FRIENDLY) && (sect.sct_own != ship.shp_own)){
			pr("You are not on friendly terms with the owner of ship %d!\n",
				ship.shp_own);
			continue;
		}
		if (!player->owner || sect.sct_type != SCT_HARBR || sect.sct_effic < 60)
			continue;
		n++;
		mp = &mchr[ship.shp_type];
		w_p_eff = ((mp->m_lcm / 2) + mp->m_hcm);
		points = sect.sct_avail * 100 / w_p_eff;
		if (points < 20) {
		    pr("Not enough available work in %s to upgrade a %s\n",
				xyas(sect.sct_x, sect.sct_y, player->cnum),
				mp->m_name);
			pr(" (%d available work required)\n",
				1 + (w_p_eff * 20)/100);
			continue;
		}
		if (ship.shp_effic < 60) {
			pr("%s is too damaged to upgrade!\n", prship(&ship));
			continue;
		}
		if (ship.shp_tech >= tlev) {
			pr("%s tech: %d, yours is only %d\n", prship(&ship),
			   ship.shp_tech, tlev);
			continue;
		}
		if (mp->m_cost * .15 + player->dolcost > cash) {
			pr("You don't have enough money to upgrade %s!\n",
			   prship(&ship));
			continue;
		}

		sect.sct_avail = (sect.sct_avail * 100 - w_p_eff * 20) / 100;
		ship.shp_effic -= 35;
		ship.shp_tech = tlev;
		ship.shp_mission = 0;
		putship(ship.shp_uid, &ship);
		putsect(&sect);
		player->dolcost += (double) mp->m_cost * .15;
		pr("%s upgraded to tech %d, at a cost of %d\n", prship(&ship),
		   ship.shp_tech,
		   (int)(mp->m_cost * .15));
		if (ship.shp_own != player->cnum)
			wu(0,ship.shp_own,"%s upgraded by %s to tech %d, at a cost of %d\n", prship(&ship),
			   cname(player->cnum),
			   ship.shp_tech, (int)(mp->m_cost * .15));
	}
	if (n == 0) {
		pr("No ships\n");
		return RET_SYN;
	}
	return RET_OK;
}
