Refactored and added final code.