#!/bin/bash

# display a file (url) as ascii art

# 0.1" character pitch horizontally
# 0.16" vertically
# geometry => 40:25
width=72

tmps=$(mktemp)
tmpj=$(mktemp -t XXXXXX.jpg)
function cleanup() {
    rm "$tmps"
    rm "$tmpj"
}
trap cleanup EXIT

# ASR33 typewheel characters approximately sorted by print density
chars=" .-,/)+>^_=?7I][*J5C#V96$P&%4OZSDAH@GX2U8EBQWKRM"

if [[ -f "$1" ]]; then
    cp "$1" "$tmps"
else
    wget -q -O "$tmps" "$1"
fi

if [[ $? == 0 ]]; then
    # convert to a JPG
    convert "$tmps" -background none -colorspace Gray -gamma 2 -resize $((width * 10))x -auto-level - | convert - -geometry 40%x25% jpg:"$tmpj"

    # convert to ascii (and trim blanks from line endings, to save printing time)
    jp2a --invert --chars="$chars" --width=$width "$tmpj" | sed 's/[[:blank:]]*$//'
fi
