Fixes for #71

Potential fix for #71, the cast now checks for `System.DBNull` everywhere now. Also the start of some refactoring to make the code testable. but now implementation changes so should not break anything.