Added assertions and exceptions, minor refactoring