#!/bin/sh
# Default
Eyes=""
Tongue=""
Thougts=""
Opts="e:t:T:s:cax?h"
Sign='\$the_cow'

while getopts "$Opts" opt
do
  case $opt in
    x)	set -x;;
    e)	Eyes="$OPTARG" ;;
    t)  Thougts="$OPTARG" ;;
    T)  Tongue="$OPTARG" ;;
    s)  Sign="$OPTARG" ;;
    c)	Src="Cow";;
    a)  Src="Ascii";;
    \?|h) echo "$0 [$Opts] <file>" >&2
	  echo "Convert COW file to and from Ascii format" >&2
    	  echo "-e <str>	Use <str> as eye_string [$Eyes]" >&2
    	  echo "-T <str>	Use <str> as tongue_string [$Tongue]" >&2
    	  echo "-t <str>	Use <str> as thougts_string [$Thougts]" >&2
    	  echo "-s <str>	Use <str> as COW file signature [$Sign]" >&2
	  echo "-c		Source is COW file" >&2
	  echo "-a		Source is ASCII file" >&2
	  exit 0
	  ;;
    *)  echo "ERROR: unknown flag $opt"; exit 1;;
  esac
done
shift `expr $OPTIND - 1`

SignRE="$Sign"'[    ]*=[ 	"<]*\([^" 	;]*\)'

if [ "$1" = "-" -o "$1" = "" ]; then File="/dev/stdin"; else File="$1"; shift; fi
test -n "$Src" || grep -q "$Sign" "$File" && Src="Cow" || Src="Ascii"
case "$Src" in
  Cow)	EOC="`sed -n "/$Sign/s/$SignRE.*/\1/p" "$File"`"
  	sed "	s/\$eyes/$Eyes/g
  		s/\$thoughts/$Thougts/g
		s/\$tongue/$Tongue/g
		s/[\\]\([@\\]\)/\1/g
	    " < "$File" |
	sed "	/$SignRE/d
		/^$EOC/d"
	;;
  Ascii) EOC="EOC"; St="`sed -n "/^#/!{=;q}" "$File"`"
  	sed "	s/$Eyes/\$eyes/g
		s/$Thougts/\$thoughts/g
		s/$Tongue/\$tongue/g
		s/\([@\\]\)/\\\\\1/g
	    " < "$File" |
	sed "${St}i\\
$Sign = <<$EOC
\$a\\
$EOC
"	;;
esac
