%mathpiper,def="CompilePatterns"

LocalSymbols(LocResult) [

  Bind(LocResult,True);
  10 # LocPredicate(exp_IsAtom) <--
  [
    Local(tr,result);
    tr:=patterns;
    result:=False;
    While (tr != {})
    [
      If (First(First(tr)) = exp,
      [
        Bind(LocResult,Eval(First(Rest(First(tr)))));
        result := True;
        tr:={};
      ],
      [
        tr := Rest(tr);
      ]);
    ];
    result;
  ];

  10 # LocPredicate(exp_IsFunction) <--
  [
    Local(tr,result,head);
    tr:=patterns;
    result:=False;
    While (tr != {})
    [
      Bind(head, First(First(tr)));
      If (Not(IsAtom(head)) And exp[0]=head[1] And PatternMatches(head[2], exp),
      [
        Bind(LocResult,Eval(First(Rest(First(tr)))));
        Bind(result, True);
        Bind(tr,{});
      ],
      [
        Bind(tr, Rest(tr));
      ]);
    ];
    result;
  ];
  20 # LocPredicate(_exp) <-- False;

  LocChange(_exp) <-- LocResult;
]; // LocalSymbols(LocResult)

UnFence("LocPredicate",1);
UnFence("LocChange",1);

10 # LocProcessSingle({_pat,_post,_exp}) <-- { {pat[0],PatternCreate(pat,post)},exp };

20 # LocProcessSingle({pat_IsFunction,_exp}) <-- { {pat[0],PatternCreate(pat,True)},exp };

30 # LocProcessSingle({pat_IsAtom,_exp}) <-- { pat,exp };

/*
    40 # LocProcessSingle(pat_IsFunction <- _exp) <-- { {pat[0],PatternCreate(pat,True)},exp };
    todo:tk:this rule was not handling post predicates so I replaced it with a new version that does.
    I suspect that the other rules for this Rulebase have problems too. 
*/
40 # LocProcessSingle(pat_IsFunction <- _exp) <-- 
[
    Local(justPattern, postPredicate);
    
    If(Type(pat) = "_",
        [
            //A post predicate was submitted.
            justPattern := pat[1];
            postPredicate := pat[2];
        ],
        [
            //No post predicate was submitted.
            justPattern := pat;
            postPredicate := True;
        ]
    );
    
    { {justPattern[0],PatternCreate(justPattern,postPredicate)},exp };
];

50 # LocProcessSingle(pat_IsAtom <- _exp) <-- { pat,exp };

LocProcess(patterns) :=
[
  MapSingle("LocProcessSingle",patterns);
];

CompilePatterns(patterns) := LocPatterns(LocProcess(patterns));

%/mathpiper