added KASSERTS and fixed some bugs