fix bugs and improve the code