Refactored  functions. Added comments