Fixed race condition.
Added checks for NaN to avoid infinite loops