Refactorized and added comments