simplified type signatures by adding calls to 'error' when internal invariants are violated; added many clarifying comments