clean up the code and fix some mem unsafety