#!/usr/bin/bash
# Copyright (C) 1997-2015 Bob Hepple
#
# A simple script to convert a gjots file to emacs outline
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA

usage() {
    echo "Usage: $PROG [filename]
Converts a gjots file to emacs org-mode (on stdout).

    -F char: marker for headers in outline-regexp (default '*')
"
}

PROG=$( basename $0 )
MARKER="*"

ARGS=$( getopt -o F:h -n $PROG -- "$@" ) || {
    echo "use -h for usage" >&2
    exit 1
}

eval set -- "$ARGS"

while true; do
    case $1 in
    -h) usage; exit 0;;
    -F) MARKER="$2"; shift 2;;
    --) shift; break;;
    *)  echo "$PROG: internal error" >&2 ; exit 1;;
    esac
done

FILENAME=""
[ -r $1 ] && FILENAME=$1

writeBody() {
    [[ "$FILENAME" ]] && exec < $FILENAME
    awk -v marker="$MARKER" '
BEGIN {
    level = 1
    level_hdr = marker
    print_title = 0
}

{
    if ($0 ~ /^\\NewEntry/) {
        print_title = 1
    } else if ($0 ~ /^\\NewFolder/) {
        level++
        level_hdr = level_hdr marker
    } else if ($0 ~ /^\\EndFolder/) {
        if (level > 1) {
            level--
            level_hdr = substr(level_hdr, 1, length(level_hdr) - 1)
        }
    } else {
        if (print_title) {
            printf("%s %s\n",level_hdr, $0)
            print_title = 0
        } else {
            if (substr($0,0,1) == marker) {
                printf("\\")
            }
            print
        }
    }
}'
}

# main:
writeBody

# Local Variables:
# mode: shell-script
