Fixed some bugs ant latest minor optimization