Fixed loop and correct bugs