#!/bin/bash

DEBUG=1
debug()
{
  [ "$DEBUG" = 1 ] && echo -e $@
}

desktop=`wmctrl -d | grep "*" | tr x " " | tr -s " "`
DNUM=`echo "$desktop" | cut -f 1 -d " "`
DXSIZE=`echo "$desktop" | cut -f 4 -d " "`
DYSIZE=`echo "$desktop" | cut -f 5 -d " "`
DYSIZE=$(($DYSIZE - 48))

windows=`wmctrl -l | grep -E ^0x[0-9a-f]*\ \+$DNUM | cut -f 1 -d " "`
nwindows=`echo $windows | wc -w`

NROWS=`wcalc "round(sqrt($nwindows))" | cut -f 3 -d " "`
NCOLS=$(($nwindows / $NROWS))
if [ $(($NROWS * $NCOLS)) -lt $nwindows ]; then
  NCOLS=$(($NCOLS + 1))
fi

XSIZE=$(($DXSIZE / $NCOLS))
YSIZE=$(($DYSIZE / $NROWS))

col=0
row=0

debug "Windows: $windows"
debug "\t window\t\txpos\typos\txsize\tysize"
for win in $windows; do
  xpos=$(($XSIZE * $col))
  ypos=$(($YSIZE * $row))
  ypos=$(($ypos + 24))
  debug "Resizing $win: 0\t$xpos\t$ypos\t$XSIZE\t$YSIZE"
  debug "wmctrl -i -r $win -e 0,$xpos,$ypos,$XSIZE,$YSIZE"
  wmctrl -i -r $win -e 0,$xpos,$ypos,$XSIZE,$YSIZE
  col=$(($col + 1))
  if [ $col -eq $NCOLS ]; then
    col=0
    row=$(($row + 1))
  fi
done

