[IMP] Clean up and improve the code in several places