Refactored code and added file exists check