propagating Deyan's fixes
more refactoring and beautification