fix index 'i' is used before limits check