port from http://jsfiddle.net/psiborg/PVNAx/4/