#!/bin/awk -f

#	bdesmap [maps]
#
#	A program to change a bmap into a set of bdes commands.  Useful
#	for sharing map info.  Bmaps from multiple countries should be
#	produced using the same coordinate system.  If multiple maps are
#	given, the first map is assumed to be your current bmap, and will
#	not be overridden by later bmaps.
#
#	WARNINGS:
#	The ? character cannot be designated, so an alternate character
#	is "@" is used instead.
#	Has not been tested on a world as large as Riverworld.  May need
#	repairs.
#	Be sure to make a copy of your bmap, in case the script
#	generated by bdesmap is corrupt.
#

BEGIN {
  if (width=="") width=140;
  SUBSEP=",";
  firstbmap=1;
  maps=0;
}


/^bmap/ {    

  maps++;

  getline;
  header[0]=$0
  getline;
  header[1]=$0;

  colskip = match(header[0],"[0-9\-]");
  if (!colskip) printf("error reading bmap\n") >> "/dev/tty";
  columns = length(header[0])-colskip+1;
  
  left=substr(header[0],colskip,1)*10+substr(header[1],colskip,1);
  right=substr(header[0],length(header[0]),1)*10+substr(header[1],length(header[1]),1);
  left2=substr(header[0],colskip+1,1)*10+substr(header[1],colskip+1,1);
  right2=substr(header[0],length(header[0])-1,1)*10+substr(header[1],length(header[1])-1,1);
  
  if (left2<left) left = -left;
  if (right2>right) right = -right;

  getline;
  while (match($0,"[0-9\-]")<colskip) {
    y=$1;
    x=left;
    for (col=colskip;col<columns;col++) {
      if ( (x+y)/2 == int((x+y)/2) ) {
	des=substr($0,col,1);
	if (match(des,"[\?ABCDEFGHIJKLMNOPQRSTUVWXYZx]")) {
	  des="@";
	}
	if (match(des,"[s\/^cupdimghw\\*aojkftrnl+)!#=b%e]")) {
	  if (!firstbmap && bdes[x,y]!=des) changed[x,y]=1;
	  bdes[x,y]=des;
	} else if (des=="@" && ((x,y) in bdes)) {
	  if (bdes[x,y]==".") {
	    bdes[x,y]=des;
	    changed[x,y]=1;
	  }
	} else if (match(des,"[\.\-@]") && (!((x,y) in bdes) || override)) {
	  if (!firstbmap && bdes[x,y]!=des) changed[x,y]=1;
	  bdes[x,y]=des;
	}
      }
      x++;
      if (x>=width/2) x -= width;
    }
    getline;
  }
  firstbmap=0;
}

END {
  if (maps>1) {
    for (sect in changed) {
      printf("bdes %s %s\n",sect,bdes[sect]);
    }
  } else {
    for (sect in bdes) {
      printf("bdes %s %s\n",sect,bdes[sect]);
    }
  }
}

