## GolfScript (<strike>41</strike> 39 bytes)

    [][1,]@~:^;({{.-1=(+.)))+}%}*{{+}*^=}?`

[Online demo](http://golfscript.apphb.com/?c=Oyc4IDQnCgpbXVsxLF1AfjpeOyh7ey4tMT0oKy4pKSkrfSV9Knt7K30qXj19P2A%3D)

Thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 41->39.