General code refactoring and cleanup

This pull request is mainly to get synced with master.