added asserts and other defensive stuff