#!/bin/sh
# View an image with ImageMagick.

view() {
    # Extract header (ignores intermediate bytes, can be any byte including '\0')
    sig=$(dd bs=1 count=7 2>/dev/null) # Extract sig
    dd bs=1 count=1 >/dev/null 2>&1    # Any byte
    w=$(  dd bs=1 count=7 2>/dev/null) # Extract width
    dd bs=1 count=1 >/dev/null 2>&1    # Any byte
    h=$(  dd bs=1 count=7 2>/dev/null) # Extract width

    # remove leading spaces (0x20) for width and height
    # (removes everything up to an including last space, doesn't error check)
    w=${w##* }
    h=${h##* }

    # Check signature
    if [ "$sig" = imgRGBA ]; then
        display -size "$w"x"$h" -depth 8 rgba:-
    else
        echo "bad image signature" >&2
        exit 1
    fi
}

if [ $# -gt 0 ]; then
    # run on all arguments (skip empty arguments)
    for file do
        [ "$file" ] || continue
        view < "$file"
    done
else
    view
fi
