#! /bin/bash
# Last edited on 2011-05-06 05:14:21 by stolfi

src="$1"; shift   # Source image
tsz="$1"; shift   # Text pointsize
trgb="$1"; shift  # Text color
crgb="$1"; shift  # Line/disk color

bwid=`echo "${tsz}*0.04" | bc -lq`
echo "basic line width = ${bwid}" 1>&2

cwid="${bwid}"

rtag=`echo "${tsz}*0.7+0.5" | bc -lq | sed -e 's:[.][0-9]*::g'`
echo "tag radius = ${rtag}" 1>&2

rdot="${bwid}"
echo "dot radius = ${rdot}" 1>&2

tmp="/tmp/$$"

cmd=()
while [[ $# -gt 0 ]]; do
  if [[ "/$1" == "/-color" ]]; then
    # Change color for subsequent ops 
    shift;
    if [[ $# -lt 1 ]]; then
      echo "** bad args '$*'" 1>&2; exit 1
    fi
    crgb="$1"; shift

  elif [[ "/$1" == "/-strokewidth" ]]; then
    # Change stroke width 
    shift;
    if [[ $# -lt 1 ]]; then
      echo "** bad args '$*'" 1>&2; exit 1
    fi
    mwid="$1"; shift
    cwid=`echo "${bwid}*${mwid}" | bc -lq`
    rdot="${cwid}"
    cmd+=( "-strokewidth" "${cwid}" )
  elif [[ "/$1" == "/-S" ]]; then
    # Line segment 
    shift;
    if [[ $# -lt 4 ]]; then
      echo "** bad args '$*'" 1>&2; exit 1
    fi
    ax="$1"; shift
    ay="$1"; shift
    bx="$1"; shift
    by="$1"; shift
    
    cmd+=( "-stroke" "${crgb}" "-fill" "none" )
    cmd+=( "-draw" "line ${ax},${ay} ${bx},${by}" )

  elif [[ "/$1" == "/-Q" ]]; then
    # Quadrilateral 
    shift;
    if [[ $# -lt 8 ]]; then
      echo "** bad args '$*'" 1>&2; exit 1
    fi
    ax="$1"; shift
    ay="$1"; shift
    bx="$1"; shift
    by="$1"; shift
    cx="$1"; shift
    cy="$1"; shift
    dx="$1"; shift
    dy="$1"; shift
    
    cmd+=( "-stroke" "${crgb}" "-fill" "none" )
    cmd+=( "-draw" "polygon ${ax},${ay} ${bx},${by} ${cx},${cy} ${dx},${dy}" )

  elif [[ "/$1" == "/-L" ]]; then
    # Label
    shift;
    if [[ $# -lt 5 ]]; then
      echo "** bad args '$*'" 1>&2; exit 1
    fi
    ox="$1"; shift
    oy="$1"; shift
    dx="$1"; shift
    dy="$1"; shift
    tag="$1"; shift

    # Courier bold with pointsize 100 has height 120 and width 60
    # So we must shift the text by tsz*(-30,-30)/100
    tx=`echo "${dx}-${tsz}*0.30" | bc -lq`
    ty=`echo "${dy}+${tsz}*0.30" | bc -lq`

    rx=`echo "${dx} + ${rtag}" | bc -lq`
    sx=`echo "${ox} + ${rdot}" | bc -lq`

    cmd+=( "-stroke" "${crgb}" "-fill" "${crgb}" )
    cmd+=( "-draw" "line ${ox},${oy} ${dx},${dy}" )
    cmd+=( "-draw" "circle  ${ox},${oy} ${sx},${oy}" )
    cmd+=( "-draw" "circle  ${dx},${dy} ${rx},${dy}" )
    cmd+=( "-stroke" "none" "-fill" "${trgb}" )
    cmd+=( "-draw" "text ${tx},${ty} '${tag}'" )

  else
    echo "** unknown option '$1'" 1>&2; exit 1
  fi
done

convert ${src} \
  -font 'Courier-Bold' -pointsize ${tsz} \
  -strokewidth ${cwid} \
  "${cmd[@]}" \
  ${tmp}.png

display ${tmp}.png

cat ${tmp}.png

rm ${tmp}.png

  
#   -fill Red -draw "circle 100,100 150,100" \
#   -fill Blue -draw "text 100,100 'FOO'" \
#   -stroke Green -strokewidth 4 -draw 'line 200,100 250,350' \
