minor code refraction and some bugs fixed