Add assert and various preconditions. Fix some bugs and code smells.