fixed loop bug, code cleaning