#!/bin/sh
# vim:set ts=4 ai wm=0 syntax=awk:
#
# (c) Tomasz Surmacz
# Skrypt poprawiający odwzorowanie/narożniki (a czasem nazwę) map
# kalibracyjnych serii 3cd.  Oprócz poprawionych plików .map dopisuje
# do pliku "mv-all" komendę mv zmieniającą nazwę pliku map tak, by
# druga liczba w nazwie (od 1 do 144) była zawsze 3-cyfrowa (w razie
# potrzeby poprzedzona zerami), podobnie jak nazwy plików jpg. Po 
# zakończeniu konwersji można wykonać "sh -x mv-all", by pozmieniać
# w ten sposób nazwy plików .map

if [ "$1" == "-c" ]; then
	cd="$2";
	shift;
	shift;
fi;

if [ $# -lt 1 ]; then
	echo "Skladnia: $0 [-c num] m-xx-yy-z.map"
	echo "	num: numer CD dopisywany na początku nazwy mapy"
	exit 1;
fi

name=$1;

if [ ! -f $name ]; then
	echo "Nie moge otworzyc $name";
	exit 2;
fi

sname=`echo "$name" | sed 's/.map$//'`
mv "$name" "$sname".bak

if [ ! -f "$sname".bak ]; then
	echo "cos nie tak - backup"
	exit 3;
fi

cat "$sname".bak | sed \
	-e 's/,19.99998,/,      20,/' \
	-e 's/,49.99998,/,      50,/' \
	-e 's/,40.00002,/,      40,/' \
	-e 's/,10.00002,/,      10,/' | \
	dos2unix | awk -F, '
BEGIN {
	fname="'$name'";
	cd="'$cd'";
	if (length(cd)>0) {
		cd = cd "/";
	};
	#margines dodawany/odejmowany od punktów kalibracji, by uzyskać punkty ramki
	margin=20;
	# drive="";
	drive="E:\\";
	marX[1]=-margin; marX[2]= margin; marX[3]= margin; marX[4]=-margin;
	marY[1]=-margin; marY[2]=-margin; marY[3]= margin; marY[4]= margin;

	nname=gensub(/([mn]-[0-9]*-)([0-9]-[a-d]-.*map)/, "\\100\\2", 1, fname);
	nname=gensub(/([mn]-[0-9]*-)([0-9][0-9]-[a-d]-.*map)/, "\\10\\2", 1, nname);
	if (fname != nname) {
		printf ("mv -i \"%s\" \"%s\"\n", fname, nname) >> "mv-all";
	} else {
		printf ("# mv -i \"%s\" \"%s\"\n", fname, nname) >> "mv-all";
	}
}

function gridsetup () {
	GridSetup=1;
	printf("LL Grid Setup\n");
	printf("LLGRID,No,1 Min,Yes,255,16711680,0,1 Min,0,16777215,8,1,Yes,x\n");
	# Other Grid Setup
	# GRGRID,Yes,1 Km,Yes,12632256,255,1 Km,255,16777215,8,0,Yes,No,Yes,x
};

function othergridsetup () {
	OtherGridSetup=1;
	printf("Other Grid Setup\n");
	printf("GRGRID,No,1 Km,Yes,12632256,255,1 Km,255,16777215,8,0,Yes,No,Yes,x\n");
}

# KRS42 lub PL42 wymaga utworzenia pliku datums.dat o zawartości:
#	KRS42,15,23,-124,-82
# lub lepiej:
#	PL42,15,23.74,-123.83,-81.81
function datum() {
	printf("Pulkovo 1942 (2),WGS 84,   0.0000,   0.0000,WGS 84\n");
	# printf("KRS42,WGS 84,   0.0000,   0.0000,WGS 84\n");
	# printf("PL42,WGS 84,   0.0000,   0.0000,WGS 84\n");
}

/^OziExplorer/ { # nagłówek
	print $0;

	getline;	# M-33-35-c.jpg Wroclaw-Wschod
	# można by tylko wtedy, gdy w nazwie w mapie nie ma spacji:
	#mname=fname;
	# sub(/([mn]-[0-9]*-[0-9]*-[a-d])-(.*)/, "\1 \2", mname);
	mname=gensub(/([mn]-[0-9]*-[0-9]*-[a-d])-(.*)/, "\\1 \\2", 1, fname);
	sub(/.(map|bak)$/, "", mname);

	if (index($0, " ")>1) {
		gsub(/.jpg /, " ", $0);
		mname=$0;
	}
	if (length(cd)>0) {
		# printf ("cd = %s, mname=<%s>\n", cd, mname) >> "/dev/stderr";
		sub(/^[^ ]*\//, "", mname);
		mname=cd "" mname;
		# printf ("cd = %s, mname=<%s>\n", cd, mname) >> "/dev/stderr";
	}
	printf("%s\n", mname);
	
	getline;	# Q:\m-33-35-c.jpg
	n=split($0, tb, /[\\:]/);
	# dodanie wiodących zer do drugiego numerka w nazwie jpg
	jpgname=gensub(/([mn]-[0-9]*-)([0-9]-[a-d].jpg)/, "\\100\\2", 1, tb[n]);
	jpgname=gensub(/([mn]-[0-9]*-)([0-9][0-9]-[a-d].jpg)/, "\\10\\2", 1, jpgname);
	printf("%s%s\n", drive, jpgname);

	next;
}

/^Point0[1234]/ {	# Poprawianie narożników mapy - na razie zapamiętujemy dane
	x=$3;
	y=$4;
	if ( x<800 && y<800 ) { pt=1; } else
	if ( x>=800 && y<800 ) { pt=2; } else
	if ( x>=800 && y>=800 ) { pt=3; } else
	{ pt=4; }

	# narożniki mapy zawsze są numerowane w kierunku:  12
	# więc trzeba dostosować się bez względu na        43
	# kolejność numerowania punktów kalibracji.

	pttabX[pt]=x;
	pttabY[pt]=y;
	pttabLatD[pt]=$7;
	pttabLatM[pt]=$8;
	pttabLonD[pt]=$10;
	pttabLonM[pt]=$11;
	print $0;
	# printf("##DEBUG: %s %s %s %s\n", pttabLatD[pt], pttabLatM[pt], pttabLonD[pt], pttabLonM[pt]);
	next;
}

/Map Projection/ { # Odwzorowanie merkatora
	printf("Map Projection,Transverse Mercator,PolyCal,No,AutoCalOnly,No,BSBUseWPX,No\n");
	next;
}

/Projection Setup/ { # parametry odwzorowania - osobne dla arkuszy 33 i 34
	if (fname ~ /[mnMN]-33/) {
		falseE="35";
		central="15";
	} else {
		falseE="45";
		central="21";
	}
	printf("Projection Setup,     0.000000000,    %s.000000000,     1.000000000,      %s00000.00,            0.00,,,,,\n", central, falseE);
	next;
}

/^WGS 84,/ {
	datum();
	next;
}

/^Pulkovo 19/ {
	datum();
	next;
}

/^KRS42,/ {
	datum();
	next;
}

/^PL42,/ {
	datum();
	next;
}

/LL Grid Setup/ {
	getline;
	gridsetup();
	next;
}

/Other Grid Setup/ {
	getline;
	othergridsetup();
	next;
}

/^MMPXY/ { # Poprawienie narożników
	pt=$2+0;
	printf("MMPXY,%d,%d,%d\n", pt, pttabX[pt]+marX[pt], pttabY[pt]+marY[pt]);
	next;
}

/^MMPLL/ { # Oraz współrzędnych związanych z narożnikami
	pt=$2+0;

	# najpierw wyliczamy ile wynosi poprawka na margines w skali mapy:
	# larmar na przeciwny znak niż powinien:
	lonmar=0.0+pttabX[2]-pttabX[1]+pttabX[3]-pttabX[4]; # długość ramek X
	latmar=0.0+pttabY[4]-pttabY[1]+pttabY[3]-pttabY[2]; # długość ramek Y
	# printf("DEBUG: %d/%f %d/%f (%d)", marX[pt],lonmar, marY[pt],latmar, pt);
	latmar=marY[pt]*.33333/latmar;	# margin*(10/60)/(latmar/2)
	lonmar=marX[pt]*.25/lonmar;		# margin*(15/60)/(lonmar/2)

	# po czym wyliczamy współrzędne punktów kalibracyjnych + poprawka
	lon=0.0+pttabLonM[pt];
	lon=lon/60+pttabLonD[pt]+lonmar;
	lat=0.0+pttabLatM[pt];
	lat=lat/60+pttabLatD[pt]-latmar;
	printf("MMPLL,%d,  %2.6f,  %2.6f\n", pt, lon, lat);
	next;
}

/^MOP,/ {
	if (GridSetup<1) {
		gridsetup();
	}
	if (OtherGridSetup<1) {
		othergridsetup();
	}
}

END {
	if (GridSetup<1) {
		gridsetup();
	}
}

{
	print $0;
}
' | unix2dos > $name
touch -r "$sname".bak "$name"
ls -l "$sname".bak "$name"
