#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/lib/update/finish.c,v 2.2 1995/10/11 03:05:54 empire Exp $";
#endif

/*
 * finish.c
 *
 * finish the update
 *
 * 
 * from PSL Empire, 1985
 * and Dave Pare, 1986
 * and ts, 1992-3
 */

#include <math.h>
#include "misc.h"
#include "var.h"
#include "sect.h"
#include "nat.h"
#include "item.h"
#include "news.h"
#include "file.h"
#include "xy.h"
#ifdef	FALLOUT
#include "path.h"
#endif	/* FALLOUT */
#include "distribute.h"


finish_sects()
{
	extern	long pops[];
	register struct sctstr *sp;
	struct	natstr *np;
	int	n;
	int	vec[I_MAX+1];
	int	changed;
	s_char	*paths[WORLD_X][WORLD_Y];
	double	imcost[WORLD_X][WORLD_Y], excost[WORLD_X][WORLD_Y];

	bzero(paths, sizeof(paths));
	for (n=0; sp = getsectid(n); n++) {
		if (sp->sct_type == SCT_WATER)
			continue;
		if (sp->sct_own == 0)
			continue;
		np = getnatp(sp->sct_own);
		if (np->nat_money < 0)
			continue;
		changed = 0;
		if (getvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR) > 0)
			changed += dodeliver(sp, vec);
		if (changed)
			putvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR);
	}

	logerror("assembling paths...");
	assemble_dist_paths(paths, imcost, excost);
	logerror("done assembling paths\n");

	logerror("exporting...");
	for (n=0; sp = getsectid(n); n++) {
		if (sp->sct_type == SCT_WATER)
			continue;
		if (sp->sct_own == 0)
			continue;
		np = getnatp(sp->sct_own);
		if (np->nat_money < 0)
			continue;
		changed = 0;
		getvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR);
		changed += dodistribute(sp,vec,EXPORT,
			paths[sp->sct_x][sp->sct_y],
			imcost[sp->sct_x][sp->sct_y],
			excost[sp->sct_x][sp->sct_y]);
		if (changed)
			putvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR);
	}
	logerror("done exporting\n");
	logerror("importing...");
	for (n=0; sp = getsectid(n); n++) {
		if (sp->sct_type == SCT_WATER)
			continue;
		if (sp->sct_own == 0)
			continue;
		np = getnatp(sp->sct_own);
		if (np->nat_money < 0)
			continue;
		changed = 0;
		getvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR);
		changed += dodistribute(sp,vec,IMPORT,
			paths[sp->sct_x][sp->sct_y],
			imcost[sp->sct_x][sp->sct_y],
			excost[sp->sct_x][sp->sct_y]);
		if (changed)
			putvec(VT_ITEM, vec, (s_char *)sp, EF_SECTOR);
	}
	logerror("done importing\n");

	logerror("freeing paths...");
	free_dist_paths(paths);
	logerror("done freeing paths\n");
}
