#!/bin/bash
INPUT="$1"
OUTPUT=$(basename "$1" .pdf).png
# These numbers are for portrait maps, they are flipped below for landscape.
PAGE_SIZE=(2479 3508)
# Extract the coordinates for the map corners and compute the width in metres.
COORDS=($(ps2ascii "$INPUT" 2> /dev/null \
| grep '[N|E] [0-9]*' \
| sed 's/[^0-9 ]//g'))
LOWER_LEFT=(${COORDS[1]} ${COORDS[0]})
if [ ${LOWER_LEFT[0]} -gt ${LOWER_LEFT[1]} ] ; then
TMP=${LOWER_LEFT[0]}
LOWER_LEFT[0]=${LOWER_LEFT[1]}
LOWER_LEFT[1]=$TMP
fi
UPPER_RIGHT=(${COORDS[3]} ${COORDS[2]})
WIDTH=$((${UPPER_RIGHT[0]} - ${LOWER_LEFT[0]}))
HEIGHT=$((${UPPER_RIGHT[1]} - ${LOWER_LEFT[1]}))
DIM=$WIDTH
# Set parameters depending on whether the map is in portrait or landscape mode.
if [ $WIDTH -gt $HEIGHT ] ; then
TMP=${PAGE_SIZE[0]}
PAGE_SIZE[0]=${PAGE_SIZE[1]}
PAGE_SIZE[1]=$TMP
DIM=$HEIGHT
fi
LL_PIXEL=(83 $((${PAGE_SIZE[1]} - 163)))
UR_PIXEL=($((${PAGE_SIZE[0]} - 84)) 166)
W_PIXEL=$((${UR_PIXEL[0]} - ${LL_PIXEL[0]}))
H_PIXEL=$((${UR_PIXEL[0]} - ${LL_PIXEL[0]}))
PPM=$((($W_PIXEL * 1000000) / $WIDTH))
# Compute a nice grid size.
FACTOR=1
while [ -z "$GRIDSIZE" ] ; do
for DIGIT in 1 2 5; do
if [ $(($DIM / 10)) -lt $(($DIGIT * $FACTOR)) ] ; then
GRIDSIZE=$(($DIGIT * $FACTOR))
break
fi
done
FACTOR=$(($FACTOR * 10))
done
# Convert the PDF file to PNG and add the grid and coordinates.
gs -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=png16m -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r1200x1200 -dDownScaleFactor=4 -sOutputFile="$INPUT".tmp "$INPUT"
DRAW_CMD="convert ${INPUT}.tmp -stroke black -fill black -box '#FFFC' -font courier -pointsize 24"
X=$(((${LOWER_LEFT[0]} / $GRIDSIZE) * $GRIDSIZE))
while [ $X -lt ${UPPER_RIGHT[0]} ] ; do
if [ $X -gt ${LOWER_LEFT[0]} ] ; then
XP=$((${LL_PIXEL[0]} + (($X - ${LOWER_LEFT[0]}) * $PPM) / 1000000))
DRAW_CMD="$DRAW_CMD -draw 'line $XP,${UR_PIXEL[1]} $XP,${LL_PIXEL[1]}'"
DRAW_CMD="$DRAW_CMD -draw 'text $XP,$((${UR_PIXEL[1]} + 16)) \"$(($X/1000))\"' "
fi
X=$(($X + $GRIDSIZE))
done
Y=$(((${LOWER_LEFT[1]} / $GRIDSIZE) * $GRIDSIZE))
while [ $Y -lt ${UPPER_RIGHT[1]} ] ; do
if [ $Y -gt ${LOWER_LEFT[1]} ] ; then
YP=$((${LL_PIXEL[1]} - (($Y - ${LOWER_LEFT[1]}) * $PPM) / 1000000))
DRAW_CMD="$DRAW_CMD -draw 'line ${LL_PIXEL[0]},$YP ${UR_PIXEL[0]},$YP'"
DRAW_CMD="$DRAW_CMD -draw 'text ${LL_PIXEL[0]},$YP \"$(($Y/1000))\"' "
fi
Y=$(($Y + $GRIDSIZE))
done
DRAW_CMD="$DRAW_CMD '$OUTPUT'"
# Generate the PNG file with the map and the grid.
eval $DRAW_CMD || exit -1
rm -f "$INPUT".tmp
# Generate the world file.
MPP=$((($WIDTH * 1000) / $W_PIXEL))
MPP_REAL=$(echo "scale=3; $MPP/1000" | bc)
echo "$MPP_REAL
0
0
-$MPP_REAL
$(((${LOWER_LEFT[0]} * 1000 - $MPP * ${LL_PIXEL[0]}) / 1000))
$(((${UPPER_RIGHT[1]} * 1000 + $MPP * ${UR_PIXEL[1]}) / 1000))" > $(basename "$INPUT" .pdf).pgw