Added some sanity checking, but not sure if it works.