improved parse function

error handling, file cleanup