#!/bin/bash
# usage:
#   geotiffgcp2kal map.tif > map.kal
#
# convert GeoTIFF Calibration to Glopus KAL
# using GCP calibration points of the GeoTIFF

if [ $# -ne 1 ]; then
  echo 'Syntax: geotiffgcp2kal map.tif > map.kal'
  exit
fi

image=$1
imageinfo=$1.info
gdalinfo "$image" > "$imageinfo"

sizex=`cat "$imageinfo" | grep "^Size is " | sed "s/^Size is \(.*\), \(.*\)/\1/"`
sizey=`cat "$imageinfo" | grep "^Size is " | sed "s/^Size is \(.*\), \(.*\)/\2/"`

cat "$imageinfo" | \
sed "N;s/^GCP\[.*\]: Id=\(.*\), Info=.*\n.*(\(.*\),\(.*\)) -> (\(.*\),\(.*\),.*)/calGCP \4 \5 \2 \3 /g" | \
sed "/^calGCP/!d ; s/^calGCP //g" | \
asc2kal "$image" $sizex $sizey

rm "$imageinfo"
