#!/bin/sh

# PNGenie 1.01 (2009-07-14)
# process files
# by Matt Sephton http://www.gingerbeardman.com

RES="$1"/Contents/Resources
CDIALOG="$RES/CocoaDialog.app/Contents/MacOS/CocoaDialog"

#download pngout if we need it
"$RES/pngout-downloader.php"

if [ -n "$2" ]
then
	total=$#
	let "total = $total - 1"

	# drag and drop
	count=0
	until [ "$*" = "" ]
	do
		let "count = $count + 1"
		let "percent = ($count*100 / $total*100)/100"
		
		echo "$percent Optimising files: $count of $total"
		
		"$RES/advpng" -z4q "$2"
		"$RES/optipng" -q "$2"
		if [ -f "$RES/pngout-darwin" ]
		then
			"$RES/pngout-darwin" -q "$2"
		fi

		shift
	done | $CDIALOG progressbar --title "PNGenie"

else
	# file selector
	rv=`$CDIALOG fileselect --select-multiple --text "Select one or more PNG files to be optimised" --with-extensions .png`

	if [ -n "$rv" ]; then
		total=`echo $rv | wc -l`
		let "total = $total + 1"

		count=0
		echo -e "$rv" | while read file; do
			let "count = $count + 1"
			let "percent = ($count*100 / $total*100)/100"
		
			echo "$percent Optimising files: $count of $total"
		
			"$RES/advpng" -z4q "$file"
			"$RES/optipng" -q "$file"
			if [ -f "$RES/pngout-darwin" ]
			then
				"$RES/pngout-darwin" -q "$file"
			fi
		
			shift
		done | $CDIALOG progressbar --title "PNGenie"
	else
		$CDIALOG ok-msgbox --no-cancel --title "PNGenie" --text "How to use PNGenie" --informative-text "No files selected or dropped onto the application." --icon-file "$RES/appIcon.icns"
	fi
fi
