#! /bin/csh -f
# Last edited on 2004-01-30 07:20:00 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; } \
     ' \
  | iso-8859-6-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", \\
           "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 \
     ' /./ { gsub(/[_ ]+$/, ""); } \
       /^ *([\#@]|$)/ { print; next; } \
       /./ { gsub(/^[ ]*[_ ]*/, "_"); gsub(/[_ ]+/, "_"); } \
       /^[_][0-9]/ { gsub(/^[_]/, "  "); } \
       /^[_]/ { gsub(/^[_]/, "    "); } \
       /./ { gsub(/[_]/, "\n    "); print; next; } \
     ' \
  | egrep -v '^ *$'