#!/bin/bash
###################################################################### 
#Copyright (C) 2020  Kris Occhipinti
#https://filmsbykris.com

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
###################################################################### 

original="$1"
name="$(echo "$original"|cut -d\. -f1)"
tmp="$PWD/${name}_tmp"

function error(){
  echo "==ERROR=="
  echo "$*"
  exit 1
}

echo "Creating tmp directories..."
mkdir -p $tmp/{0,1} || error "Unable to create $tmp"

echo "Splitting Sprite $name Vertically..."
./divide_vert "$original" $tmp/0/output-$(date +%s).png 

echo "Rotating and Splitting Sprite Horizontally"
for i in $tmp/0/*.png;
do 
  echo "$i"
  convert $i -rotate 90 $i
  ./divide_vert "$i" $tmp/1/output-$(date +%s).png 
done 

#This is suppose to remove blank images, but didn't work very well
for i in $tmp/1/*.png
do
   #check if image is blank
   blank="$(identify -format "%[opaque] %[fx:mean] %[fx:standard_deviation]" $i|awk '{print $2}')"
   if [ "$blank" = "0" ]
   then
     echo "$i is blank and will be removed"
     rm "$i"
#   else
#     echo "Rotating $i"
#     convert $i -rotate -90 $i
   fi 
done

echo "Removing small images..."
find pun_tmp/1/ -name "*.png" -type 'f' -size -2k -delete

#echo "Rotating $i"
#convert $i -rotate -90 $i

echo "Calculating Largest Side..."
size="$(identify $tmp/1/*.png|awk '{print $3}'|grep 'x'|tr 'x' '\n'|sort -ug|tail -n1)"

echo "Creating frames at ${size}x${size}"
for i in $tmp/1/*.png;
do 
  echo $i;
  convert $i -background none -gravity center -extent ${size}x${size} $i;
done

echo "Combining final sprite sheet ${name}_sheet.png..."
montage $tmp/1/*.png -rotate -90 -geometry ${size}x${size} -background none ${name}_sheet.png
