#! /bin/csh -f
# Last edited on 2004-02-04 08:01:11 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 \
     ' BEGIN { obook = ""; nbook = 0; } \
       /^[\#][ ]+[=][=][=]+[ ]/ { next; } \
       /^ *([\#]|$)/ { print; next; } \
       /[@]fix / { \
         gsub(/[@]fix +/, "#     "); \
         print; next; \
       } \
       /[@]chapter/ { \
         gsub(/[ ]/, "_"); \
         gsub(/[{}]/, " "); \
         chnum = $2; book = $3; chtit = $4; entit = $5;  \
         gsub(/[_]/, " ", chtit); gsub(/[_]/, " ", entit); \
         if (book != obook) { \
           nbook++; obook = book; \
           printf "@part %s {%s:%s}\n", substr("abcdefgh", nbook, 1), book, entit; \
         } \
         printf "@chapter %s {%s:%s}\n", chnum, book, chnum; \
         printf "@unit T 0 chaptertitle\n  %s:%s\n    %s %s\n@=\n", book, chnum, chtit, chnum; \
         next; \
       } \
       /[@]verse/ { \
         $0 = gensub(/^ *[@]verse{([A-Z]+)}{([0-9]+)}{([0-9]+)} *(.*)$/, \\
           "@unit V \\3 verse\n  \\1:\\2:\\3\n    \\4\n@=", \\
           "g", $0); \
         print; next; \
       } \
       /^ *[@]/ { print; next; } \
       /./ { print; next; } \
     ' \
  | egrep -v '^ *$'