#!/bin/bash

svgfile=$1		#input-file
pngwidth=$2		#output-file width in pixels
twidthf=3500		#increase this value, if you have enough RAM
tpngwidth=1024		#tilewidth in pixels

echo -n "Detecting image width ... "
iwidth=$(inkscape -W $svgfile 2> /dev/null)
echo $iwidth
echo -n "Detecting image height ... "
iheight=$(inkscape -H $svgfile 2> /dev/null)
echo $iheight
nsplit=$(echo "$iwidth/3500" | bc)
let "ntiles=$nsplit**2"
twidth=$(echo "$iwidth/$nsplit" | bc)
theight=$(echo "$iheight/$nsplit" | bc)

for((i=0;i<=$(($nsplit-1));i++))
do
	for((j=0;j<=$(($nsplit-1));j++))
	do
		let "m+=1"
		echo -n "Rendering tile "$m"/"$ntiles" ..."
		let "x0=$i*$twidth"
		let "y0=$j*$theight"
		let "x1=($i+1)*$twidth"
		let "y1=($j+1)*$theight"
		echo " "$x0:$y0:$x1:$y1" "
		if [[ -e tiles/tile-$i-$j.png ]]
		then
			echo "already rendered"
		else
			inkscape -a $x0:$y0:$x1:$y1 -w $tpngwidth -e tiles/tile-$i-$j.png $svgfile &> /dev/null
		fi
	done
done

for((i=0;i<=$(($nsplit-1));i++))
do
	echo "Merging row "$(($i+1))"/$nsplit ..."
	montage -geometry +0+0 -tile x1 tiles/tile-*-$i.png tiles/row-$(($nsplit-1-$i)).png
done

echo "Merging and resizing image ..."
montage -geometry $(echo $pngwidth)x+0+0 -tile 1x tiles/row-*.png tiles/image.png
echo "Crushing image ..."
pngcrush tiles/image.png $(basename "$svgfile" .svg).png &> /dev/null
#rm -f tiles/*
