Refactor code

to reduce redundancy (in determining whether file exists, whether to overwrite, how to query and save data)