#ifndef lint
static char *RCSid = "$Header: map.c,v 1.1 89/12/14 08:20:08 jay Exp $";
#endif /* not lint */

/*
 * map.c
 *
 * empire map: probably the most-used command in empire.
 *
 * Dave Pare, 1986
 */

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

map()
{
	extern	int aborted;
	extern	char *argp[];
	register char *ptr;
	struct	nstr_sect ns;
	struct	natstr *np;
	struct	sctstr sect;
	struct	range range;
	int	i;
	u_char	bitmap[WORLD_X*WORLD_Y/8];
	char	wmap[WORLD_Y][MAPWIDTH(1)];
	coord	y;
	char	what[64];
	char	*str;
	int	country, godmap=0;

	country = cnum;
	if(argp[1] == (char *) 0) {
		if ((str = getstring("(sects)? ")) == 0)
			return RET_SYN;
	}
	else {
		str = argp[1];
	}

	if(*str == '*') {
		sprintf(what, "%d:%d,%d:%d",
			-WORLD_X/2, WORLD_X/2-1,
			-WORLD_Y/2, WORLD_Y/2-1);
		if (!snxtsct(&ns, what))
			return RET_FAIL;
	}
	else
	if (!snxtsct(&ns, str))
		return RET_FAIL;

	if (god){
		godmap=1;
                if(argp[2] != (char *) 0){
                        country=atoi(argp[2]);
			godmap=0;
			if ((country < 0) || (country > MAXNOC)){
				country = cnum;
				godmap=1;
			}
		}
	}

	if (!godmap) {
		bzero((char *)bitmap, sizeof(bitmap));
		bitinit2(&ns, bitmap, country);
	}

	np = getnatp(country);
	/* zap any conditionals */
	ns.ncond = 0;
	xyrelrange(np, &ns.range, &range);
	border(&range, "     ", "");
	blankfill((char *)wmap, &ns.range, 1);
	while (nxtsct(&ns, &sect) && !aborted) {
		if (!godmap && !getbit(ns.x, ns.y, bitmap))
			continue;
		ptr = &wmap[ns.dy][ns.dx];
		if (sect.sct_type > SCT_MAXDEF)
			*ptr = '?';
		else {
			*ptr = dchr[sect.sct_type].d_mnem;
			switch (sect.sct_type) {
			case SCT_WATER:
			case SCT_RURAL:
			case SCT_MOUNT:
			case SCT_WASTE:
				break;
			default:
				if (sect.sct_own != country && !godmap)
					*ptr = '?';
				break;
			}
#if	defined(BMAP) || defined(AUTONAV)
		setbigmap(ns.x, ns.y, *ptr);
#endif
		}
	}
#if	defined(BMAP) || defined(AUTONAV)
	writebigmap();
#endif
	if (aborted)
		return RET_OK;
	for (y=ns.range.ly, i=0; i < ns.range.height; y++, i++) {
		int yval;

		yval = yrel(np, y);
		pr(fmt("%4d %s %-4d\n", yval, wmap[i], yval));
		if (y >= WORLD_Y)
			y -= WORLD_Y;
	}
	border(&range, "     ", "");
	return RET_OK;
}

int
bitinit2(np, bitmap, country)
        struct  nstr_sect *np;
        u_char  *bitmap;
	int	country;
{
        extern  int *bitmaps[];
        struct  sctstr sect;
        int     eff;

        while (nxtsct(np, &sect)) {
                if (sect.sct_own != country)
                        continue;
                eff = sect.sct_effic / 20;
                if (eff > 4)
                        eff = 4;
                setbitmap(np->x, np->y, bitmap, bitmaps[eff]);
        }
        snxtsct_rewind(np);
}
