#!/bin/bash

item="${1}"
group="false"
if ( echo "${item}"|grep -q '@' ); then
  group="true"
  item="$(echo ${item}|sed 's/@.*//')@*.txt"
fi

if [[ ${group} == "true" && -z "${3}" ]]; then
  echo "when passing in a group you must specify the column width"
  echo "$0 ${1} ${2} x"
  exit 1
fi

direction="${2}"
if [[ -z "${item}" || -z "${direction}" ]]; then
  echo "Must pass in object to move"
  echo "item direction (u,r,d)"
  echo "wooden_paxel.txt u"
  exit 1
fi
distance=34

parents=$(thedir=$(pwd|awk -F'/' '{print $NF}'); grep Parent ${item}|grep -v Parents|cut -f2 -d'"'|sed -e 's/triumph:'"${thedir}"'\///' -e 's/$/.txt/')

x=$(grep setPos ${parents}|cut -f2 -d'('|cut -f1 -d','|awk '{if (i < $0 || i == "" ){i=$0}}END{print i}')
ymax=$(grep setPos ${parents}|cut -f2 -d','|cut -f1 -d')'|awk '{if (i < $0 || i == "" ){i=$0}}END{print i}')
ymin=$(grep setPos ${parents}|cut -f2 -d','|cut -f1 -d')'|awk '{if (i >= $0 || i == ""){i=$0}}END{print i}')

y=$(echo ${ymax} ${ymin}|awk '{print ((($1-$2)/2)+$2)}'|cut -f1 -d'.')

if [[ "${direction}" == "u" ]]; then
  x="$((x+${distance}))"
  y="$((y-${distance}-13))"
elif [[ "${direction}" == "r" ]]; then
  x="$((x+${distance}))"
elif [[ "${direction}" == "d" ]]; then
  x="$((x+${distance}))"
  y="$((y+${distance}))"
fi
if [[ ${group} == "true" ]]; then
  count=$(ls ${item}|wc -l)
  if [[ ${3} -gt 1 ]]; then
    count=$(echo "${count}" "${3}"|awk '{print ($1/$2)}'|cut -f1 -d'.')
  fi
  if [[ $((count%2)) == 0 ]]; then
    y=$((y+12))
  fi
  half=$((count/2))
  temp=$((half*23))
  y=$(echo "${y}" "${temp}"|awk '{print ($1-$2)}'|cut -f1 -d'.')
  ../autolayoutgroup "${item}" ${x} ${y} ${3}
else
  sed -i '/setPos/d' "${item}"
  echo "setPos(${x},${y})" >> "${item}"
fi

../organize "${item}"
