#!/bin/bash

# This file is part of NIT ( http://www.nitlanguage.org ).
#
# Copyright 2012-2013 Alexis Laferrière <alexis.laf@xymus.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script extracts pngs from a single svg for all objects with ids
# beginning by 0. Requires Inkscape.

# there are some trick used do to inconsistency in inkscape input and output values
# the document must be resized to fit all objects

dir=`dirname $0`
log=$dir/`basename $0 .sh`.log

echo $0 executed at `date` > $log

if [ $# -ne 2 ]
then
	echo "Usage: $0 source.svg destination/folder/"
	exit
fi

sourceFile="$1"
destinationFolder="$2"
if [ ! -f $sourceFile ]
then
	echo "Source file \"$sourceFile\" not found."
	exit
fi

if [ ! -d $destinationFolder ]
then
	echo "Destination folder \"$destinationFolder\" not found, creating it."
	mkdir -p $destinationFolder
fi


query=`inkscape --query-all $sourceFile`
min_x=10000
min_y=10000
for line in $query; do
	ld=(${line//,/ })

	x=${ld[1]}
	y=${ld[2]}
	w=${ld[3]}
	h=${ld[4]}
	# remove e notation
	if echo $y | grep e &> /dev/null; then
		y=0
	fi
	if echo $x | grep e &> /dev/null; then
		x=0
	fi

	echo "$x < $min_x" | bc &> /dev/null
	if [ $? ]; then
		min_x=$x
	fi

	y=`echo $y-$h|bc`
	echo "$y < $min_y" | bc &> /dev/null
	if [ $? ]; then
		min_y=$y
	fi
done

full_h=`inkscape "-f$sourceFile" -C -H 2>> $log`

for line in $query; do #`inkscape --query-all $sourceFile | grep ^0`; do
	if echo $line | grep ^0 &> /dev/null; then
		ld=(${line//,/ })
		id=${ld[0]} #${line:0: $[`expr index "$line" ,` - 1] }
		name=${line:1: $[`expr index "$line" ,` - 2] }

		x=${ld[1]}
		y=${ld[2]}
		w=${ld[3]}
		h=${ld[4]}

		# remove e notation
		if echo $y | grep e &> /dev/null; then
			y=0
		fi
		if echo $x | grep e &> /dev/null; then
			x=0
		fi

		# corrected dim for pow(2)
		i=`bc <<!
			i=1
			while (i<$w || i<$h){
				i=i*2
			}
			print i
!`
		echo "found $i for $w $h" &>> $log
		cw=$i
		ch=$i
		dw=`echo \($cw-$w\)/2|bc`
		dh=`echo \($ch-$h\)/2|bc`
		cx=`echo $x + \($cw-$w\)/2|bc`
		cy=`echo $y + \($ch-$h\)/2|bc`

		# corrects value of y.
		y=`echo $full_h - $y | bc`

		echo "x=$x y=$y w=$w h=$h" &>> $log
		echo "cx=$cx cy=$cy cw=$cw ch=$ch" &>> $log
		i=`echo "$i * 2" | bc`
		inkscape -z -C "-f$sourceFile" "-i$id" -j "-a`echo $x-$dw|bc`:`echo $y-$h-$dh|bc`:`echo $x+$w+$dw|bc`:`echo $y+$dh|bc`" "-e$destinationFolder/$name.png" -b#000000 -y0.0 -d180 -w$i -h$i &>> $log
	fi
done
