Clean up the code and do some minor fixes