Refactored the whole code