Fixes #29
propagating Deyan's fixes
more refactoring and beautification