#!/bin/bash
#
# make a white-on-black PNG from fig, pdf, or png
#   for use on hackaday.io
#

usage()
{
cat <<EOF
create a white-on-black PNG image from a pdf, fig, or png files

make_hadio_figure [-r <dpi>] <input_file>

Options:

-r <dpi> ; set the output resolution (dots per inch) for pdf or fig

EOF
}

if [ "$#" -lt 1 ]; then
    usage
    exit
fi

resolution=72
while getopts "r:" option
do
    case $option in
        r)
            resolution=$OPTARG
            ;;
        ?)
            usage
            exit
            ;;
    esac
done
shift $((OPTIND-1))   

# first argument is input file
input_file=$1

# check for fig or pdf extension
if [ ${input_file: -4} == ".fig" ]
then
    # the input is actually a fig file; convert it to pdf first
    pdf_file=${input_file%.fig}.pdf
    fig2dev -L pdf $input_file $pdf_file
    png_file=${pdf_file%.pdf}.png
    # convert to ppm at given resolution and invert to white-on-black
    pdftoppm -r $resolution ${pdf_file} | pnminvert > schematic_temp.ppm
else
    if [ ${input_file: -4} == ".pdf" ]
    then
        png_file=${input_file%.pdf}.png
        # convert to ppm at given resolution and invert to white-on-black
        pdftoppm -r $resolution ${input_file} | pnminvert > schematic_temp.ppm
    else
        png_file=${input_file%.png}_hadio.png
        pngtopnm -mix -background white -gamma 0.45 ${input_file} | pnminvert > schematic_temp.ppm
    fi
fi


# determine dimensions of resulting image file
pamfile_output=`pamfile schematic_temp.ppm`
regexp="([[:digit:]]+)[[:space:]]+by[[:space:]]+([[:digit:]]+)"
if [[ $pamfile_output =~ $regexp ]]; then
    width=${BASH_REMATCH[1]}
    height=${BASH_REMATCH[2]}
else
    echo "can't find image dimensions"
    exit -1
fi

# create a 21/255 black background to match hackaday.io theme
ppmmake rgb:15/15/15 $width $height > background_temp.ppm

# compose the schematic on the background image
pnmarith -maximum background_temp.ppm schematic_temp.ppm | pnmtopng > $png_file

# clean up
rm -f background_temp.ppm schematic_temp.ppm

