#!/bin/bash
# Find the actual location of the script and the directory it is in
SCRIPT_LOCATION="$( readlink -f "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}" )"
PROG_DIR="$( dirname "$SCRIPT_LOCATION")"
PROG_NAME="$(basename "$SCRIPT_LOCATION")"
VERSION="0.3"

# The usage instructions, these will be output if the user gets anything wrong
USAGE=`cat << EOF
=== ${PROG_NAME} v$VERSION ===
usage: ${PROG_NAME} options [infile]

[infile] optional input file to view, can also use STDIN

Display formatted contents of a file. This is a wrapper around mdtable and
pipes it into less -S. The options are the options to mdtable, although peep
has the -u and --all-left options flagged already:
EOF
`

if [[ "$1" == "--help" ]]; then
    echo "$USAGE"
    mdtable --help
    exit 0
fi

# If input is from STDIN then INFILE will end up being ""
INFILE=""
ARGS=("")

# If there are some arguments assess them, if there are none then we just move
# on
if [[ $# -gt 0 ]];
then
    # The infile should be the last argument if present or course it could be
    # absent and we could have arguments that we need to pass through to
    # mdtable
    INFILE="${@: -1}"

    # If the infile exists or is from STDIN "-" then any other arguments are
    # things to mdtable
    if [[ -e "$INFILE" ]] || [[ "$INFILE" == "-" ]];
    then
        ARGS="${@:1:$#-1}"
    else
        # infile does not exist so all args passed through to mdtable
        INFILE=""
        ARGS=${@}
    fi
fi

# For some reason when no other command line args are specified ARGS has a
# single element which is "", so I have to check for this and adjust accordingly
if [[ ${ARGS[0]} == "" ]]; then
    ARGS=(-u --all-left)
else
    ARGS+=(-u --all-left)
fi

# Is the input file compressed
if [[ "$INFILE" =~ \.b?gz$ ]];
then
    zcat "$INFILE" | mdtable "${ARGS[@]}" | less -S
elif [[ "$INFILE" == "" ]] || [[ "$INFILE" == '-' ]];
then
    # No input so assume stdin and pass are args through
    mdtable "${ARGS[@]}" | less -S
else
    # With uncompressed input file
    cat "$INFILE" | mdtable "${ARGS[@]}" | less -S
fi

exit 0
