#!/bin/bash
BALLS_LIB=$(readlink -f $(dirname $0)/../lib)

shopt -s extglob

. $BALLS_LIB/balls.sh

dash_trim_r() {
  local str="${!1}"
  str="${str%%*( )}"
  export "$1"="$str"
}

compile() {
  local code
  local chunk
  local trim_next=0
  while read_until '<%' chunk; do
    if [ "$FOUND" = 1 ]; then
      read_until '%>' code
      trim code

      case "${code:0:1}" in
        =)
          code="${code:1}"
          trim code
          code="echo -n $code"
        ;;
        -)
          code="${code:1}"
          dash_trim_r chunk
          trim code
        ;;
      esac

      case "${code:${#code}-1}" in
        -)
          # read off the next line
          read
          code="${code:0:${#code}-1}"
          trim code
        ;;
      esac

    fi # if [ "$FOUND" = 1 ]

    # echo "echo -n $(bash_safe <<< "$chunk")"
    bash_safe chunk
    echo "echo -n $chunk"

    [ "$FOUND" = 1 ] && echo "$code"

  done # while read_until '<%' chunk
  true
}

fname=$1; shift

export eof="$(echo -e '\004')"

if [ -n "$fname" ]; then
  cat $fname || exit 1
else
  cat -
fi | compile