Improved and tested in 8cf6f15