+exception Nothing_to_do;;
+
+let fix_outty curi tyno t context outty =
+ let leftno,rightno =
+ match fst (CicEnvironment.get_obj CicUniv.oblivion_ugraph curi) with
+ Cic.InductiveDefinition (tyl,_,leftno,_) ->
+ let _,_,arity,_ = List.nth tyl tyno in
+ let rec count_prods leftno context arity =
+ match leftno, CicReduction.whd context arity with
+ 0, Cic.Sort _ -> 0
+ | 0, Cic.Prod (name,so,ty) ->
+ 1 + count_prods 0 (Some (name, Cic.Decl so)::context) ty
+ | n, Cic.Prod (name,so,ty) ->
+ count_prods (leftno - 1) (Some (name, Cic.Decl so)::context) ty
+ | _,_ -> assert false
+ in
+(*prerr_endline (UriManager.string_of_uri curi);
+prerr_endline ("LEFTNO: " ^ string_of_int leftno ^ " " ^ CicPp.ppterm arity);*)
+ leftno, count_prods leftno [] arity
+ | _ -> assert false in
+ let ens,args =
+ let tty,_= CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph in
+ match CicReduction.whd context tty with
+ Cic.MutInd (_,_,ens) -> ens,[]
+ | Cic.Appl (Cic.MutInd (_,_,ens)::args) ->
+ ens,fst (HExtlib.split_nth leftno args)
+ | _ -> assert false
+ in
+ let rec aux n irl context outsort =
+ match n, CicReduction.whd context outsort with
+ 0, Cic.Prod _ -> raise Nothing_to_do
+ | 0, _ ->
+ let irl = List.rev irl in
+ let ty = CicSubstitution.lift rightno (Cic.MutInd (curi,tyno,ens)) in
+ let ty =
+ if args = [] && irl = [] then ty
+ else
+ Cic.Appl (ty::(List.map (CicSubstitution.lift rightno) args)@irl) in
+ let he = CicSubstitution.lift (rightno + 1) outty in
+ let t =
+ if irl = [] then he
+ else Cic.Appl (he::List.map (CicSubstitution.lift 1) irl)
+ in
+ Cic.Lambda (Cic.Anonymous, ty, t)
+ | n, Cic.Prod (name,so,ty) ->
+ let ty' =
+ aux (n - 1) (Cic.Rel n::irl) (Some (name, Cic.Decl so)::context) ty
+ in
+ Cic.Lambda (name,so,ty')
+ | _,_ -> assert false
+ in
+(*prerr_endline ("RIGHTNO = " ^ string_of_int rightno ^ " OUTTY = " ^ CicPp.ppterm outty);*)
+ let outsort =
+ fst (CicTypeChecker.type_of_aux' [] context outty CicUniv.oblivion_ugraph)
+ in
+ try aux rightno [] context outsort
+ with Nothing_to_do -> outty
+(*prerr_endline (CicPp.ppterm outty ^ " <==> " ^ CicPp.ppterm outty');*)
+;;
+