Some refactoring and style enhancements
Major code refactoring