Added sanity check; refactored a bit