Code cleanup and small bug fix
Refactoring