cleaned up encoding of types (reducing duplication and using encode_typ_term uniformly)