%mathpiper,def="ExpandBrackets"

LocalSymbols(AssembleTerms, AssembleTermsRecursive)
[

    AssembleTerms(list) :=
    [
        Check(IsList(list), "Argument", "The argument must be a list.");

        If(Length(list) = 1, 
            First(list),
            AssembleTermsRecursive(Reverse(list)) 
        );
    ];


    AssembleTermsRecursive(list) :=
    [
        If(Type(list[1]) = "-" Or IsNegativeNumber(list[1]) Or Type(list[1]) = "/" And (Type(Numerator(list[1])) = "-" Or IsNegativeNumber(Numerator(list[1]))),
            If(Length(list) = 2,
                ListToFunction({ToAtom("-"), list[2], -list[1]} ),
                ListToFunction({ToAtom("-"), AssembleTermsRecursive(Rest(list)), -First(list)} )
            ),
            If(Length(list) = 2,
                ListToFunction({ToAtom("+"), list[2], list[1]} ),
                ListToFunction({ToAtom("+"), AssembleTermsRecursive(Rest(list)), First(list)} )
            )
        );
    ];


10 # ExpandBrackets(xx_IsZero) <-- 0;

20 # ExpandBrackets(_xx)_(Type(xx)="/" Or Type(-xx)="/") <-- 
[
    Local(N,D,t);
    N := ReassembleListTerms(DisassembleExpression(Numerator(xx)));
    D := ExpandBrackets(Denominator(xx));
    AssembleTerms(MapSingle({{t}, t / D}, N));
];


30 # ExpandBrackets(_xx) <-- AssembleTerms(ReassembleListTerms(DisassembleExpression(xx)));

];



//ExpandBrackets(_xx) <-- SimpExpand(SimpImplode(SimpFlatten(xx)));
//ExpandBrackets(x) := NormalForm(MM(x));

%/mathpiper


    



%mathpiper_docs,name="ExpandBrackets",categories="User Functions;Polynomials (Operations)"
*CMD ExpandBrackets --- expand all brackets
*STD
*CALL
	ExpandBrackets(expr)

*PARMS

{expr} -- an expression

*DESC

This command tries to expand all the brackets by repeatedly using the
distributive laws $a * (b+c) = a*b + a*c$ and $(a+b) * c = a*c + b*c$.
It goes further than {Expand}, in that it expands all brackets.

*E.G.

In> Expand((a-x)*(b-x),x)
Result: x^2-(b+a)*x+a*b;
In> Expand((a-x)*(b-x),{x,a,b})
Result: x^2-(b+a)*x+b*a;
In> ExpandBrackets((a-x)*(b-x))
Result: a*b-x*b+x^2-a*x;

*SEE Expand
%/mathpiper_docs
