various code refactorings.
Added comments