refactor and check if file exists