remove_debugging_calls(Layout,Term,Layout,Term) :- var(Term),!.
 remove_debugging_calls(LayoutIn,when(Cond,Body),LayoutOut,ResTerm) :- !,
       ResTerm = when(Cond,NewBody), % do not expand inside condition
       (LayoutIn = []
        -> LayoutBody = [],
           LayoutOut = []
        ;  LayoutIn = [LayoutWhen,LayoutCond,LayoutBody],
           LayoutOut = [LayoutWhen,LayoutCond,LayoutBodyOut]),
       remove_debugging_calls(LayoutBody,Body,LayoutBodyOut,NewBody).
 remove_debugging_calls(LayoutIn,Term,Layout2,Term2) :-
      functor(Term, ~~, 1),
      arg(1,Term,Term1),
      nonvar(Term1),!,functor(Term1,Functor,Arity),
      ( LayoutIn = [] -> Layout1 = []
      ; LayoutIn = [_,Layout1]),
      ( is_debug_call(Functor,Arity,CallPos) ->
          ( remove_debug_calls ->
        safe_arg(CallPos,Term1,TermI),
        ( Layout1 = [] -> LayoutI = []
        ; Layout1 = [_|ArgLayout] ->
            nth1(CallPos,ArgLayout,LayoutI)),
        remove_debugging_calls(LayoutI,TermI,Layout2,Term2)
          ;
        remove_debugging_calls(Layout1,Term1,Layout2,Term2))
      ;
          write_to_codes(Functor/Arity,M1),
          append(["encountered unregistered ",M1,
            " tagged for debugging removal"],M3),
          safe_atom_codes(Msg1,M3),
          print_message(error,Msg1),
          Term2 = Term1
   ).
 remove_debugging_calls(LayoutIn,Term1,LayoutOut,Term2) :-
      !,functor(Term1,Functor,Arity),
      functor(Term2,Functor,Arity),
      ( LayoutIn = [] ->
          LayoutOut = [],
          remove_debugging_calls_args_nl(1,Arity,Term1,Term2)
      ; LayoutIn = [Pos|Layout1] ->
          LayoutOut = [Pos|Layout2],
          remove_debugging_calls_args(Layout1,Term1,Layout2,Term2,1)
      ;
          LayoutIn = LayoutOut,
          Term1 = Term2).