Refactoring and clean up

Refactoring and cleaning up the code. You can noticed that there are
more deletions than additions...