/* COLLECTION ROUTINE TO INVOKE POWERFUL MATCHER */


collect(X,Old,New1) :-
/*  least_dom(X,Old),   */
    flag(try_hard,true,true),
    trace('\ntrying to use powerful matcher to collect %p in %c\n',
      [X,Old],3),
    features(Old,X,FExpr),
    /* select a collection axiom */
    trace('features of expression are %p\n',[FExpr],4),
    trace('looking for a collection rule with matching features\n\n',4),
    collax(Us,LHS,RHS),
    /* bind all rule variables to random atoms */
    instantiate(LHS,PatternVars),
    /* chose a collection variable in rule and work out features wrt it */
    wordsin(Us,Ul), member(U,Ul),
    features(LHS,U,FRule),
    /* make sure the features of the expression and the rule match */
    match_cut(FExpr,FRule,X,U,Subst,NewPVars), !,
    append(NewPVars,PatternVars,PatternVars1),
    /* apply resulting substitution to rule and put in pnf */
    subst(Subst,LHS,LHS1), subst(Subst,RHS,RHS1),
    poly_form([X],LHS1,LHS2),
    /* prepare for and apply rule */
    make_description(Old,X,[],Old_D),
    make_description(LHS2,X,PatternVars1,LHS_D),
    make_description(RHS1,X,PatternVars1,RHS_D),
    apply_rule( Old_D , rule(LHS_D,RHS_D) , New_D),
    expr(New_D,New),
    tidy(New,New1),
    trace('%p collected in %p gives  %c\n',[X,Old,New1],2).



try_hard_to_solve(Eqn,Unknown,Ans) :-
   /* solve the equation using powerful matcher */
   flag(try_hard,Old,true),
   solve(Eqn,Unknown,Ans),
   flag(try_hard,_,Old).

:- flag(try_hard,_,false).


/* Match features of expr and rule and return substitution */

/* FExpr are identical except for the difference in variable */
match_cut(FExpr, FRule, X, U, U=X, []) :-
	subst(U=X, FRule, FExpr).

/* Special hack for cubic */
match_cut(FExpr, FRule, X, U, cos(U)=X*Q^(-1) & U=arccos(X*Q^(-1)), [Q] ) :-
	gensym(q,Q),
	subst(cos(U)=X, FRule, FExpr).
