#! /bin/csh -f
# Last edited on 2004-02-02 06:26:09 by stolfi

# A filter to be run on the main.raw to turn it into 
# the starting version of main.org

sed \
      -e '1,/# BEGIN TEXT/d' \
      -e '/# END TEXT/,$d' \
  | gawk \
      ' /^ *([\#]|$)/ { print; next; } \
        /[@]fix / { \
          gsub(/[@]fix +/, "#     "); \
          print; next; \
        } \
        /[@]item/ { \
          $0 = gensub(/^ *[@]item{([0-9]+)}{(.*)}{(.*)} *$/, \\
            "@chapter \\1 {\\2_\\3}\n@unit P 1 text", \\
            "g", $0); \
          print; next; \
        } \
        /[@]chinword{[*]}/ { \
          $0 = gensub(/^ *@chinword{(.*)}{(.*)} *$/, \\
            "  * {\\2}", \\
            "g", $0); \
          print; next; \
        } \
        /[@]chinword/ { \
          gb = gensub(/^[@]chinword{(.*)}{.*}.*$/, "\\1", "g", $0); \
          py = gensub(/^[@]chinword{.*}{(.*)}.*$/, "\\1", "g", $0); \
          printf "  %s {%s}\n", py, gb; next; \
        } \
        /^ *[@]/ { print; next; } \
        /./ { print; next; } \
      ' \
  | gawk \
      ' /./ { gsub(/[_ ]+$/, ""); } \
        /^ *([\#@]|$)/ { print; next; } \
        /./ { gsub(/^[ ]*[_ ]*/, "_"); gsub(/[_ ]+/, "_"); } \
        /^[_]/ { gsub(/^[_]/, "  "); } \
        /./ { gsub(/[_]/, " "); print; next; } \
      ' \
  | egrep -v '^ *$'