+(* LOOPING : COL057-1.ma *)
+
 let debug s =
-  () (* prerr_endline s *)
+  prerr_endline s
 ;;
 
 let nparamod rdb metasenv subst context t table =
-  let nb_iter = ref 200 in
-  let amount_of_time = 20.0 in
+  let max_nb_iter = 999999999 in
+  let amount_of_time = 10.0 in
   let module C = struct
     let metasenv = metasenv
     let subst = subst
     let context = context
   end
   in
+  let nb_iter = ref 0 in
   let module B = NCicBlob.NCicBlob(C) in
   let module Pp = Pp.Pp (B) in
   let module FU = FoUnif.Founif(B) in
   let rec given_clause bag maxvar actives      
       passives g_actives g_passives =
     
-    decr nb_iter; if !nb_iter = 0 then 
+    incr nb_iter; if !nb_iter = max_nb_iter then 
       (*(prerr_endline "Bag :"; prerr_endline (Pp.pp_bag bag);
       prerr_endline "Active table :"; 
        (List.iter (fun x -> prerr_endline (Pp.pp_unit_clause x))
           let bag, g_current = 
             Sup.simplify_goal maxvar (snd actives) bag g_current
           in
+           debug "Simplified goal";
           let bag, maxvar, new_goals = 
             Sup.infer_left bag maxvar g_current actives 
           in
+           debug "Performed infer_left step";
          let new_goals = List.fold_left add_passive_clause
            PassiveSet.empty new_goals
          in
          | None -> assert false
          | Some (current, passives) -> 
              debug ("Selected fact : " ^ Pp.pp_unit_clause current);
-(*               match Sup.keep_simplified current actives bag maxvar with *)
-               match Sup.one_pass_simplification current actives bag maxvar with 
+                match Sup.keep_simplified current actives bag maxvar with
+(*  match Sup.one_pass_simplification current actives bag maxvar with*)
                | None -> aux_simplify passives
                | Some x -> x,passives
       in
   with 
   | Sup.Success (bag, _, (i,_,_,_)) ->
       let l =
-        let module S  = 
-          HTopoSort.Make(struct type t=int let compare=Pervasives.compare end)
-        in
-        let module C : Set.S with type elt = int = 
-          Set.Make(struct type t=int let compare=Pervasives.compare end)
-        in
-        let all id = 
-          let rec traverse ongoal (accg,acce) i =
-            match Terms.M.find i bag with
-            | (_,_,_,Terms.Exact _) -> accg, acce
-            | (_,_,_,Terms.Step (_,i1,i2,_,_,_)) -> 
-               let accg, acce = 
-                 if ongoal then C.add i1 accg, acce
-                 else accg, C.add i1 acce
-               in
-               let acce = C.add i2 acce in
-                 traverse false (traverse ongoal (accg,acce) i1) i2    
-          in
-            traverse true (C.empty,C.empty) id
-        in
-        let esteps = 
-          S.topological_sort (C.elements (snd (all i))) 
-           (fun i -> C.elements (C.union (snd (all i)) (fst (all i)) ))
-        in
-        let gsteps = 
-          S.topological_sort (C.elements (fst (all i))) 
-           (fun i -> C.elements (fst (all i)))
+       let rec traverse ongoal (accg,acce) i =
+         match Terms.M.find i bag with
+           | (id,_,_,Terms.Exact _) ->
+               if ongoal then [i],acce else
+                 if (List.mem i acce) then accg,acce else accg,acce@[i]
+           | (_,_,_,Terms.Step (_,i1,i2,_,_,_)) ->
+               if (not ongoal) && (List.mem i acce) then accg,acce
+               else
+                  let accg,acce = 
+                   traverse false (traverse ongoal (accg,acce) i1) i2
+                 in
+                   if ongoal then i::accg,acce else accg,i::acce
         in
-        let gsteps = List.rev gsteps in
-        esteps@(i::gsteps)
+       let gsteps,esteps = traverse true ([],[]) i in
+         (List.rev esteps)@gsteps
       in
-(*
-      prerr_endline "Proof:"; 
+       prerr_endline (Printf.sprintf "Found proof in %d iterations" !nb_iter);
+      (* prerr_endline "Proof:"; 
       List.iter (fun x -> prerr_endline (string_of_int x);
-              prerr_endline (Pp.pp_unit_clause (Terms.M.find x bag))) l;
-*)
+              prerr_endline (Pp.pp_unit_clause (Terms.M.find x bag))) l;*)
       let proofterm = B.mk_proof bag i l in
+       prerr_endline "Got proof term";
       let metasenv, proofterm = 
         let rec aux k metasenv = function
           | NCic.Meta _ as t -> metasenv, t
           metasenv subst context proofterm None
       in
       proofterm, metasenv, subst
-  | Failure _ -> prerr_endline "FAILURE"; assert false
+  | Failure _ -> prerr_endline
+      (Printf.sprintf "FAILURE in %d iterations" !nb_iter); assert false
 ;;
 
     exception Success of B.t Terms.bag * int * B.t Terms.unit_clause
 
     let debug s =
-      () (* prerr_endline s *)
+       () (* prerr_endline s *)
     ;;
 
     let rec list_first f = function
       let rec aux pos ctx = function
       | Terms.Leaf _ as t -> f t pos ctx 
       | Terms.Var _ -> None
-      | Terms.Node l as t-> 
+      | Terms.Node l as t->
           match f t pos ctx with
           | Some _ as x -> x
           | None ->
      * in normal form we should not traverse it again *)
     let demodulate_once bag (id, literal, vl, pr) table =
       (* debug ("Demodulating : " ^ (Pp.pp_unit_clause (id, literal, vl, pr)));*)
-      let t = 
-        match literal with
-        | Terms.Predicate t -> t
-        | Terms.Equation (l,r,ty,_) -> Terms.Node [ Terms.Leaf B.eqP; ty; l; r ]
-      in
-      match first_position [] (fun x -> x) t (demod table vl) with
-      | None -> None
-      | Some (newt, subst, varlist, id2, pos, dir) ->
-          build_clause bag (fun _ -> true) Terms.Demodulation 
-            newt subst varlist id id2 pos dir
+      match literal with
+      | Terms.Predicate t -> assert false
+      | Terms.Equation (l,r,ty,_) ->
+        match first_position [2]
+         (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; x; r ]) l
+         (demod table vl)
+       with
+         | Some (newt, subst, varlist, id2, pos, dir) ->
+             build_clause bag (fun _ -> true) Terms.Demodulation 
+               newt subst varlist id id2 pos dir
+         | None ->
+             match first_position
+               [3] (fun x -> Terms.Node [ Terms.Leaf B.eqP; ty; l; x ]) r
+               (demod table vl)
+             with
+               | None -> None
+               | Some (newt, subst, varlist, id2, pos, dir) ->
+                   build_clause bag (fun _ -> true) Terms.Demodulation 
+                     newt subst varlist id id2 pos dir
     ;;
 
     let rec demodulate bag clause table =
 
     let infer_left bag maxvar goal (_alist, atable) =
        (* We superpose the goal with active clauses *)
-      let bag, maxvar, new_goals =
+      let bag, maxvar, new_goals =     
         superposition_with_table bag maxvar goal atable 
       in
+       prerr_endline "Superposed goal with active clauses";
        (* We demodulate the goal with active clauses *)
       let bag, new_goals = 
         List.fold_left
             bag, g :: acc) 
          (bag, []) new_goals
       in
+       prerr_endline "Demodulated goal with active clauses";
       bag, maxvar, List.rev new_goals
     ;;