inserting new windows intelligently

credits to http://superuser.com/a/704551/132717