fix iterations when reach end and error/nil out