#! /bin/csh -f
# Last edited on 2004-01-30 04:52:21 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 \
     ' /[@](chapter|fix)/ { gsub(/@/, "<ATSIGN>"); print; next; } \
       /[@]verse/ { \
         $0 = gensub(/{([0-9]+)}{([0-9]+)} */, "{\\1}{\\2}\n    ", "g", $0); \
         print; next; \
       } \
       // { print; next; } \
     ' \
  | utf-8-to-hexbytes \
  | hexbytes-to-jsar \
  | gawk \
     ' /^ *<ATSIGN>/ { gsub(/<ATSIGN>/, "@"); } \
       /^ *([\#]|$)/ { print; next; } \
       /[@]fix / { gsub(/[@]fix +/, "#     "); print; next; } \
       /[@]chapter/ { \
         $0 = gensub(/^ *[@]chapter{([0-9]+)}{.*}{(.*)} */, \\
           "@chapter \\1 {\\2}\n@unit T 0 chaptertitle\n  \\1.\n    \\2\n@=", \\
           "g", $0); \
         print; next; \
       } \
       /[@]verse/ { \
         $0 = gensub(/^ *@verse{([0-9]+)}{([0-9]+)} */, \\
           "@unit V \\2 verse\n  \\1.\\2.", \\
           "g", $0); \
         print; next; \
       } \
       /^ *[@]/ { print; next; } \
       /./ {print; next; } \
     ' \
  | gawk \
     ' /^ *([\#@]|$)/ { print; next; } \
       /./ { \
         gsub(/^[ ]*[_]*/, "    "); gsub(/[_ ]+$/, ""); gsub(/[_]+/, " "); \
       } \
       /./ { gsub(/[ _]/, "\n    "); print; next; } \
     ' \
  | egrep -v '^ *$'