refactor clean and add error checking