move code from assert statements so it is run when NDEBUG is active
improve error checking