#!/bin/bash

# Copyright (c) 2010 Jim Peters (http://uazu.net)

die() { echo "ABORT: $@"; exit 1; }

rm -rf out >/dev/null 2>&1
mkdir out || die "mkdir failed"
mkdir out/lilypond || die "mkdir failed"
mkdir out/img || die "mkdir failed"

./draw-scales C out/lilypond || die "draw-scales failed"
./draw-scales G out/lilypond || die "draw-scales failed"
./hash-names out/lilypond out/img >tmp-hash-list

cd out/img || die "cd failed"
for xx in *.ly
do 
    echo ==== $xx
    base=${xx%.ly}
    lilypond --ps $xx || die "lilypond failed"
    #lilypond -danti-alias-factor=3 --png *.ly || die "lilypond failed"

    gs -dEPSCrop -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -dNOPAUSE -sDEVICE=png16m -sOutputFile="$base.png" -r303 $base.ps -c quit || die "gs failed"
    mv $base.png $base.png.old || die mv failed

    PAD=12
    pngtopnm $base.png.old | pnmscale -reduce 3 2>/dev/null | pnmcrop | pnmpad -left $PAD -right $PAD -top $PAD -bottom $PAD -white | pnmtopng -compression 9 2>/dev/null > $base.png
    [ ! -f $base.png ] && die "PNM sequence failed"
    rm $base.png.old $base.ps
done

for xx in 0 1 2 3 4 5 6 7 8 9 A B C D E F; do
  echo "Crushing PNGs $xx????? ..."
  pngnq -e .png2 -n 10 $xx*.png || die pngnq failed
  pngcrush -e .png3 -q $xx*.png2 || die pngcrush failed
done
for xx in *.png
do 
    [ ! -f ${xx}3 ] && die "Can't find ${xx}3"
    mv ${xx}3 $xx
    rm ${xx}2
done

cd ../.. || die "cd failed"

./gen-html
