Fixed logic errors and poorly written loop