#!/bin/bash

src="$1"
pg="$2"

dst="${src%.*}"
mkdir -pv "$dst"

let j=10000+$pg
tname="$dst/page-${j:1}"

#echo $src, $pg, $dst, $tname

fginfo=""
bginfo=""
ddjvu -format=tiff -page=$pg "$src" "$tname.tiff"
#djvused "$src" -e "select $pg; dump"
fginfo=`djvused $src -e "select $pg; dump" | grep -m 1 "FG44" | awk '{ print $10 }' | tr "x" " "`
bginfo=`djvused $src -e "select $pg; dump" | grep -m 1 "BG44" | awk '{ print $10 }' | tr "x" " "`

if [ ! -z "$fginfo$bginfo" ]
then
	convert "$tname.tiff" "$tname.png"
	rm "$tname.tiff"
	ddjvu -format=pbm -mode=mask -page=$pg $src "$tname.pbm"
	convert -compress Group4 "$tname.pbm" "$tname.black.tiff"
	rm "$tname.pbm"
	echo "Page $pg: Image"
else
	convert -compress Group4 "$tname.tiff" "$tname.tif"
	rm "$tname.tiff"
	echo "Page $pg: Mask"
fi

if [ ! -z "$fginfo" ]
then
	fgw=`echo "$fginfo" | awk '{ print $1 }'`
	fgh=`echo "$fginfo" | awk '{ print $2 }'`
	djvuextract $src -page=$pg FG44="$tname.fg44"
	djvumake "$tname.fg.djvu" INFO=$fgw,$fgh,300 BG44="$tname.fg44"
	rm "$tname.fg44"
	ddjvu -format=ppm "$tname.fg.djvu" "$tname.fg.ppm"
	rm "$tname.fg.djvu"
	echo "Extracted fg"
fi

if [ ! -z "$bginfo" ]
then
	bgw=`echo "$bginfo" | awk '{ print $1 }'`
	bgh=`echo "$bginfo" | awk '{ print $2 }'`
	djvuextract $src -page=$pg BG44="$tname.bg44"
	djvumake "$tname.bg.djvu" INFO=$bgw,$bgh,300 BG44="$tname.bg44"
	rm "$tname.bg44"
	ddjvu -format=ppm "$tname.bg.djvu" "$tname.bg.ppm"
	rm "$tname.bg.djvu"
	echo "Extracted bg"
fi


