#!/bin/bash

# c2016-17 by Paul Sherman <psherman2001@gmail.com>
# uses imagemagick (smaller grayscale than GIMP, posterized), then pngcrush,
# and fnally exiftool to put in ps, wpclipart stuff.

if [ "$1" == "" ]; then
  $dialog --title "No PNG to convert" --msgbox "\nThis utility needs to be passed the filename of a PNG image, including the path.\n" 0 0
  exit 0
fi

ret=`which pngcrush`
if [ ! "$ret" == "/usr/bin/pngcrush" ]; then
	$dialog --title "PNG Crush not found..." \
        	--msgbox "PNG Crush needs to be installed for this conversion.\n" 0 0
	exit 0
fi

pth=`dirname "$1"`
cd $pth


ret=`identify -verbose "$1" | grep Colorspace`

if [[ $ret == *"Gray"* ]]
then

	selection=$(zenity --list "256" "64" "32" "24" "16" --column="number of grays" --text="Please Choose the" --title="PNG Gray Reduce")
	case "$selection" in
	"256")num=256;;
	"64")num=64;;
	"32")num=32;;
	"24")num=24;;
	"16")num=16;;
	*)exit;;
	esac



	Xdialog --title "It begins" --infobox "hang on a second.\n" 12 50 1000
	tmpfile="/tmp/1.png"
	#convert "$1" -colorspace gray +dither -posterize 64 "$tmpfile"
	convert "$1" -define png:big-depth=8 -colors $num -define png:color-type=0 "$tmpfile"
	pngcrush -reduce -brute -q "$tmpfile" "$1"  2>/dev/null
	exiftool -Comment="Edited by Paul Sherman for WPClipart, Public Domain" -overwrite_original_in_place "$1"
	Xdialog --title "DONE" --infobox "$1 \nhas been reduced to $num shades of gray\n" 16 90 4000
	paplay /usr/share/sounds/opcomp.wav
	exit 0
fi

	Xdialog --title "HEY" --infobox "image was not grayscale to begin with...\n" 0 0 2000
	