Fixed some bug and improve the code.