Code-rewrite, now works on 1.6.2