Added logging logic.

Also provided some code refactoring