clean up code and make it more robust