fixed a couple of bugs and clean a little bit code