#!/n/mynah/home/dreeves/bin/mash
(* Simplifies expression with conditionals on stdin. *) 

protDiv[a_,b_] := If[b==0, 1, a/b]  (* for Evan *)

Off[FullSimplify::fas]; (* self-contradictory assumptions *)

simpIf[x_, y_, z_] := Module[{sx, sy, sz, yGx, yGNx, zGx, zGNx},
  sx = FullSimplify[x];
  sy = FullSimplify[y];
  sz = FullSimplify[z];
  yGx = FullSimplify[sy, sx];
  yGNx = FullSimplify[sy, Not[sx]];
  zGx = FullSimplify[sz, sx];
  zGNx = FullSimplify[sz, Not[sx]];
  Which[
    yGx === zGNx, yGx,
    yGx === zGx,  sz,
    yGNx === zGNx, sy,
    True, If[sx, yGx, zGNx]]]

simplifyAll[x_] := FullSimplify[Evaluate //@ x]

simplifyWithIfsSub[x_] := 
  FixedPoint[simplifyAll, FixedPoint[simplifyAll, x] /. If->simpIf, 10]

simplifyWithIfs[x_] := FixedPoint[simplifyWithIfsSub, x, 10]


str = StringJoin@@readList[];
sexp = ToExpression[str];
sexpSimp = simplifyWithIfs[sexp];
pout[InputForm[sexpSimp]];

