Refactored whole code