refactored whole code