#!/bin/sh

W="$1"		# width  = number of columns
H="$2"		# height = number of rows

if [ -z "$W" ] || [ -z "$H" ] ; then
  echo 'USAGE: pto2points 8 6 < file.pto > file-points.json' 1>&2
  exit 1
fi

sed -ne 's/^c .* x\([0-9.]*\) y\([0-9.]*\) .*$/\1 \2/p' |
(
  X=0
  Y=0

  printf '      {\n'
  printf '        "#": "pto2points %s %s",\n' "$W" "$H"
  printf '        "points":\n'
  printf '        [\n'

  while read PX PY ; do
    #echo "gridpix  $X  $Y  $PX  $PY"
    printf '          {"realh": %2d, "realv": %2d, "pixx": %10.5f, "pixy": %10.5f},\n' \
	   "$X" "$Y" "$PX" "$PY"

    X="$(( $X + 1 ))"
    if [ "$X" -ge "$W" ] ; then
      Y="$(( $Y + 1 ))"
      X=0
    fi
  done

  printf '          "# (additional item to allow comma above)"\n'
  printf '        ]\n'
  printf '      },\n'

  if [ "$X" != 0 ] || [ "$Y" != "$H" ] ; then
    echo "WARNING: Not exactly $W x $H = $(( $W * $H )) points!" 1>&2
  fi
)