minor refactoring and trivial bug fix
slighlty better, still not optimal