#! /bin/csh -f
# Last edited on 2004-02-02 05:41:03 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{(.*)}{(.*)} *$/, \\
           "  \\1 {\\2}", \\
           "g", $0); \
         print; next; \
       } \
       /^ *[@]/ { print; next; } \
       /./ { print; next; } \
     ' \
  | gawk \
     ' /./ { gsub(/[_ ]+$/, ""); } \
       /^ *([\#@]|$)/ { print; next; } \
       /./ { gsub(/^[ ]*[_ ]*/, "_"); gsub(/[_ ]+/, "_"); } \
       /^[_]/ { gsub(/^[_]/, "  "); } \
       /./ { gsub(/[_]/, " "); print; next; } \
     ' \
  | egrep -v '^ *$'