Exception handling on NaN

Also heavy refactoring.