Fixed bug in loop logic, which caused EIO error and other logic issues