;;; -*- Mode: Lisp; Package: Macsyma -*-                                 ;;;
;;;    (c) Copyright 1984 the Regents of the University of California.   ;;;
;;;        All Rights Reserved.                                          ;;;
;;;        This work was produced under the sponsorship of the           ;;;
;;;        U.S. Department of Energy.  The Government retains            ;;;
;;;        certain rights therein.                                       ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(macsyma-module seqopt)

(defmvar $sequence_optim_prefix '$opt
         "String used to prefix all optimized temporaries arising from a
   call to SEQUENCE_OPTIMIZE."
         modified-commands '$sequence_optimize)

(defmvar $sequence_optim_counter 1
         "Integer index used to uniquely identify all optimized temporaries
   arising from a call to SEQUENCE_OPTIMIZE."
         fixnum
         modified-commands '$sequence_optimize)

(defmvar $sequence_optim_suffix 's
         "String used to suffix all optimized temporaries arising from a
   call to SEQUENCE_OPTIMIZE, as well as names generated by CRAY_FORTRAN for
   subexpressions which have been broken out of an expression which is too
   large for the CFT compiler."
         modified-commands '($sequence_optimize $cray_fortran))

(defmvar $save_optim_info nil
         "Flag which, if TRUE, causes the common subexpressions which
  SEQUENCE_OPTIMIZE finds to be saved as equations on the MACSYMA list
  OPTIM_EQUIVS."
         boolean
         modified-commands '$sequence_optimize)

(defmvar $optim_equivs (list '(mlist simp))
         "Macsyma list of equations for the common subexpressions which
  SEQUENCE_OPTIMIZE finds when SAVE_OPTIM_INFO is TRUE."
         modified-commands '$sequence_optimize)

(defmvar $optim_additions (list '(mlist simp))
         "Macsyma list of equations for the subexpressions which it is known
  a priori will occur more than once in a sequence of code to be optimized."
         modified-commands '$pre_optimize)

(defmvar $merge_ops (list '(mlist simp) '$cvmgp '$cvmgt)
         "A MACSYMA list of currently known CRAY-1 vector merge operations."
         modified-commands '($sequence_optimize $expense))

(defmvar $cost_float_power (+ $cost_exp $cost_sin_cos_log)
         "The expense of computing a floating point power in terms of scalar
  floating point additions on the CRAY-1(For further discussion do:
  DESCRIBE(COST_RECIPROCAL) )."
         fixnum
         modified-commands '($expense $gather_exponents))

(defvar optim-vars nil
  "MACSYMA list of generated names for common subexpressions(Not used if
   a list equations is passed to SEQUENCE_OPTIMIZE).")

(array subexp t 64.)

(defmacro make-expt (base exponent) ``((mexpt simp) ,,base ,,exponent))

(defmacro base (x) `(cadr ,x))

(defmacro exponent (x) `(caddr ,x))

(defmacro mquotientp (x) `(and (not (atom ,x)) (eq (caar ,x) 'mquotient)))

;; $SEQUENCE_OPTIMIZE takes a Macsyma expression or list of simple equations
;; and returns a LIST which contains a series of equivalences for the common
;; subexpressions and the reduced equations or expression.
;; These subexpressions are found by hashing them.

(defun alike1-hash (exp)
  (\ (if (atom exp)
         (sxhash exp)
         (do ((n (alike1-hash (caar exp))
                 (+ n (alike1-hash (car arg_list))))
              (arg_list (cdr exp) (cdr arg_list)))
             ((null arg_list) n)))
     27449.))  ; a prime number < 2^15 = PRIME(3000)

(defun $sequence_optimize (x)
  (prog (setqs)
    (fillarray 'subexp (list nil))
    (if ($listp x)
        (do ((chk (cdr x) (cdr chk)))
            ((null chk))
          (or (and (not (atom (car chk)))
                   (eq (caaar chk) 'mequal)
                   ($mapatom (cadar chk)))
              (merror "List passed to SEQUENCE_OPTIMIZE of incorrect form.  Bad element is ~%~M" (car chk))))
        (setq optim-vars (append (list '(mlist)) nil)))
    (setq x (collapse (fix-unary-minus (optim-format ($gather_exponents (copy-tree x))))))
    (if (atom x) (return x))
    (comexp x)
    (setq x (optim x))
    (and $save_optim_info 
         (setq $optim_equivs (append $optim_equivs (copy-tree setqs))))
    (return (prog1 (cond ((null setqs) x)
                         (($listp x)
                          (let ((scan x))
                            (do ((opt-con setqs (cdr opt-con)))
                                ((null opt-con) x)
                              (let ((rhs-eqn (caddar opt-con)))
                                (do ((equivs scan (cdr equivs)))
                                    ((null (cdr equivs))
                                     (rplacd scan (append (ncons (car opt-con)) (cdr scan)))
                                     (setq scan (cdr scan)))
                                  (or (freeof (cadadr equivs) rhs-eqn)
                                      (setq scan (cdr equivs))))))))
                         ((or (not (eq 'mprog (caar x)))
                              (and ($listp (cadr x)) (cdadr x)))
                          `((mprog) ,optim-vars ,.setqs ,x))
                         (t `((mprog) ,optim-vars ,.(nconc setqs (cddr x)))))
                   (setq optim-vars nil)
                   (fillarray 'subexp (list nil))))))

(defun copy-to-pntr (x y)
  (do ((redo x (cdr redo))
       (new nil `(,.new ,(car redo))))
      ((eq redo y) new)))

(defun recip-1 (expon)
  (or (and (numberp expon) (minusp expon))
      (and (not (atom expon))
           (let ((op (caar expon)))
             (or (and (eq op 'mtimes) (equal (cadr expon) -1))
                 (and (eq op 'rat) (minusp (cadr expon)))
                 (eq op 'mminus))))))

(defun reciprocalp (x)
  (and (mexptp x)
       (let ((expon (exponent x)))
         (cond ((mquotientp expon) (recip-1 (cadr expon)))
               (t (recip-1 expon))))))

(defun gen-negative (x)
   (cond ((mmminusp x) (cadr x))
         ((mquotientp x) `((mquotient) ,(mul -1 (cadr x)) ,(caddr x)))
         (t (mul -1 x))))

(defun mul-list (x)
   (cond ((cdr x) `((mtimes) ,@x))
         (t (car x))))

(defun optim-format (x)
  (cond ((atom x) x)
        ((and (eq 'rat (caar x)) (minusp (cadr x)))
         `((mminus) ((rat) ,(- (cadr x)) ,(caddr x))))
        ((and (eq 'mquotient (caar x)) (not (equal 1 (cadr x))))
         (let ((nmr (cadr x)))
           (optim-format `((mtimes simp) ,@(cond ((mtimesp nmr) (cdr nmr))
                                                 (t (list nmr)))
                                         ((mquotient) 1 ,(caddr x))))))
        ((eq 'mexpt (caar x)) (opt-expt x))
        ((eq 'mtimes (caar x))
         (do ((next (cdr x) (cdr next))
              (denominator)
              (numerator))
             ((null next)
              (cond (denominator
                     (let ((recip `((mquotient) 1 ,(mul-list denominator))))
                       (cond (numerator
                              (let ((prod? (mul-list numerator)))
                                (cond ((mtimesp prod?)
                                       (nconc prod? (ncons recip)))
                                      (t `((mtimes) ,prod? ,recip)))))
                             (t recip))))
                    (numerator (mul-list numerator))
                    (t x)))
           (let ((obj (car next)))
             (cond ((reciprocalp obj)
                    (let* ((expon (exponent obj))
                           (optim-expt (let ((mbase (base obj)))
                                         (cond ((equal expon -1)
                                                (optim-format mbase))
                                               (t
                                                (opt-expt (make-expt mbase (gen-negative expon))))))))
                      (setq denominator
                            (nconc denominator
                                   (cond ((mtimesp optim-expt) (cdr optim-expt))
                                         (t (ncons optim-expt)))))
                      (or numerator
                          (do ((seplist (cdr x) (cdr seplist)))
                              ((eq seplist next))
                            (let ((element (car seplist)))
                              (or (reciprocalp element)
                                  (setq numerator `(,.numerator ,element))))))))
                   (t
                    (let ((result (optim-format obj)))
                      (or (eq obj result)
                          numerator
                          (do ((seplist (cdr x) (cdr seplist)))
                              ((eq seplist next))
                            (let ((element (car seplist)))
                              (or (reciprocalp element)
                                  (setq numerator `(,.numerator ,element))))))
                      (and (or numerator denominator (not (eq obj result)))
                           (setq numerator (nconc numerator
                                                  (cond ((and (mexptp obj) (mtimesp result))
                                                         (copy-tree (cdr result)))
                                                        (t (ncons result))))))))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (optim-format obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defun opt-expt (x)
  (let ((osym-base (base x)) (oexp (exponent x)))
    (let ((sym-base (optim-format osym-base)) (exp (optim-format oexp)))
      (cond ((reciprocalp x)
             `((mquotient) 1 ,(cond ((equal -1 exp) sym-base)
                                    (t (opt-expt (make-expt sym-base (gen-negative exp)))))))
            ((and (ratnump exp) (equal 2 (caddr exp))) 
             (setq exp (cadr exp))
             (cond ((equal 1 exp) `((%sqrt) ,sym-base))
                   (t (let ((int-exp (quotient exp 2)))
                        `((mtimes) ((%sqrt) ,sym-base)
                                   ,(cond ((equal int-exp 1) sym-base)
                                          (t (make-expt sym-base int-exp))))))))
            (t
             (cond ((and (eq osym-base sym-base) (eq oexp exp)) x)
                   (t (make-expt sym-base exp))))))))

;; the following two functions were motivated by an inability of the
;; cray merge functions to cope with a unary minus.

(defun disp-negate (x)
       (cond ((mtimesp x)
              (let ((coeff (cadr x)))
                (cond ((and (fixnump coeff) (minusp coeff))
                       (append `((mtimes) ,(- coeff)) (cddr x)))
                      (t `((mminus) ,x)))))
             ((mnump x) (mul -1 x))
             ((or (atom x) (not (eq (caar x) 'mminus))) `((mminus) ,x))
             (t (cadr x))))

(defun fix-unary-minus (x)
   (cond (($mapatom x) x)
         ((eq (caar x) 'mtimes)
          (mapc 'fix-unary-minus (cdr x))
          (let ((sign (cadr x)))
            (cond ((and (fixnump sign) (minusp sign))
                   (cond ((equal sign -1)
                          (let ((chk-merge (caddr x)))
                            (cond ((and (not (atom chk-merge))
                                        (member (caar chk-merge) $merge_ops :test #'eq))
                                   (rplacd (cdr x) (append `(((,(caar chk-merge)) ,(disp-negate (cadr chk-merge))
                                                                                  ,(disp-negate (caddr chk-merge))
                                                                                  ,(cadddr chk-merge)))
                                                           (cdddr x)))
                                   (cond ((cdddr x) (rplacd x (cddr x)) x)
                                         (t (caddr x))))
                                  (t `((mminus) ,(cond ((cdddr x)
                                                        (rplacd x (cddr x)) x)
                                                       (t (caddr x))))))))
                         (t `((mminus) ,(append `((mtimes) ,(- sign)) (cddr x))))))
                  (t x))))
         (t (do ((search (cdr x) (cdr search)))
                ((null search) x)
              (let* ((obj (car search)) (new (fix-unary-minus obj)))
                (or (eq new obj) (rplaca search new)))))))

(defun collapse (x)
  (if (atom x)
      x
      (let ((n (logand 63. (alike1-hash x))))
             (do ((l (cdr x) (cdr l)))
                 ((null l))
               (let* ((carl (car l)) (res (collapse carl)))
                 (or (eq carl res) (rplaca l res))))
             (do ((l (subexp n) (cdr l)))
                 ((null l) (setf (subexp n) (cons (list x) (subexp n))) x)
               (if (alike1 x (caar l)) (return (caar l)))))))

(defun comexp (x)
  (cond ((atom x))
        ((eq 'rat (caar x)))
        (t
         (setq x (assoc x (subexp (logand 63. (alike1-hash x))) :test #'eq))
         (cond ((null (cdr x))
                (rplacd x 1)
                (mapc 'comexp (cdar x)))
               (t (rplacd x (1+ (cdr x))))))))

(defun optim (x)
  (cond ((atom x) x)
        ((and (member 'array (cdar x) :test #'eq) (not (mget (caar x) 'arrayfun-mode))) x)
        ((eq 'rat (caar x)) x)
        (t 
         (let ((xpair (assoc x (subexp (logand 63. (alike1-hash x))) :test #'eq))
               (nx (do ((l (cdr x) (cdr l))
                        (c (list (car x)) (cons (optim (car l)) c)))
                       ((null l) (nreverse c)))))
           (let ((tmp (cdr xpair))
                 (sym (do ((lk (cdr $optim_equivs) (cdr lk)))
                          ((null lk))
                        (and (alike1 nx (caddar lk))
                             (return (cadar lk))))))
             (cond ((fixnump tmp)
                    (cond (sym
                           (rplacd xpair sym)
                           (mformat nil "c - earlier opt-vect, ~M, occurs ~M time(s)" sym tmp)
                           sym)
                          ((= tmp 1) nx)
                          (t 
                           (let ((sym (getvar)))
                             (rplacd xpair sym)
                             (setq setqs `(,.setqs ,(list (cond (optim-vars (list 'msetq))
                                                                (t (list 'mequal)))
                                                          sym nx)))
                             (mformat nil "c - there are ~M occurrences of ~M" tmp sym)
                             sym))))
                   (t tmp))))))) ;;; Should this be an error?

(defun getvar ()
   (let ((newvar (implode (nconc (exploden $sequence_optim_prefix)
                                 (exploden $sequence_optim_counter)
                                 (exploden $sequence_optim_suffix)))))
     (incf $sequence_optim_counter)
     (if optim-vars (setq optim-vars `(,.optim-vars ,newvar)))
     newvar))

;;; The following will not PRE_OPTIMIZE top-level forms.

(defun $pre_optimize (x)
  (cond ((atom x))
        ((eq (caar x) '$cvmgp)
         (let ((term3 (cadddr x))
               (opt-list (append $optim_equivs (cdr $optim_additions))))
           (or ($mapatom term3)
               (and (eq (caar term3) 'mtimes)
                    (equal (cadr term3) -1)
                    (let ((obj (caddr term3))
                          (two-term (= (length term3) 3)))
                      (or (and two-term ($mapatom obj))
                          (do ((l (cdr opt-list) (cdr l)))
                              ((null l))
                            (let ((rhs (caddar l)))
                              (cond ((and two-term (alike1 rhs obj))
                                     (rplaca (cdddr x) (mul -1 (cadar l)))
                                     (return t))
                                    ((alike1 rhs term3)
                                     (rplaca (cdddr x) (cadar l))
                                     (return t))))))))
               (do ((l (cdr opt-list) (cdr l)))
                   ((null l))
                 (let ((rhs (caddar l)))
                   (cond ((alike1 rhs term3)
                          (rplaca (cdddr x) (cadar l))
                          (return t))
                         ((and (eq (caar rhs) 'mtimes)
                               (equal (cadr rhs) -1)
                               (null (cdddr rhs))
                               (alike1 (caddr rhs) term3))
                          (rplaca (cdddr x) (mul (cadar l) -1))
                          (return t)))))
               (let ((name (getvar)))
                 (setq $optim_additions
                       `(,@$optim_additions ((mequal simp) ,name ,term3)))
                 (rplaca (cdddr x) name)))))
        (t (do ((terms (cdr x) (cdr terms)))
               ((null terms))
             (let ((obj (car terms)))
               ($pre_optimize obj)
               (do ((lk (cdr $optim_equivs) (cdr lk)))
                   ((null lk))
                 (and (alike1 obj (caddar lk))
                      (rplaca terms (cadar lk))
                      (return t))))))))

(defun $collapse_pre_optims (x)
  (cond ((atom x) x)
        ((do ((lk (cdr $optim_equivs) (cdr lk)))
             ((null lk))
           (and (alike1 x (caddar lk))
                (return (cadar lk)))))
        (t (do ((terms (cdr x) (cdr terms))
                (success))
               ((null terms)
                (cond ((or success (not (eq (caar x) 'mtimes))) x)
                      (t (do ((l (cdr x) (cdr l))
                              (follow x l))
                             ((null l) x)
                           (let ((saved (car l)))
                             (cond ((atom saved))
                                   ((eq (caar saved) '$cvmgp)
                                    (rplacd follow (cdr l))
                                    (let* ((pminus (equal (cadr x) -1))
                                           (new (do ((lk (cdr $optim_equivs) (cdr lk)))
                                                    ((null lk) x)
                                                  (let ((rhs (caddar lk)))
                                                    (cond ((alike1 x rhs)
                                                           (return (cadar lk)))
                                                          (t (and (eq (caar rhs) 'mtimes)
                                                                  (cond (pminus
                                                                         (alike1 (cddr x) (cdr rhs)))
                                                                        ((equal (cadr rhs) -1)
                                                                         (alike1 (cdr x) (cddr rhs))))
                                                                  (return (mul -1 (cadar lk))))))))))
                                      (return (cond ((eq new x)
                                                     (rplacd follow `(,saved ,@(cdr follow)))
                                                     x)
                                                    (t (mul new saved))))))))))))
             (let* ((obj (car terms)) (new-obj ($collapse_pre_optims obj)))
               (or (eq obj new-obj)
                   (and (setq success t)
                        (rplaca terms new-obj))))))))

(defun product-base (x y)
  (muln (append (cond ((mtimesp x) (cdr x))
                      (t (ncons x)))
                (cond ((mtimesp y) (cdr y))
                      (t (ncons y))))
        nil))

(defun floating-exponent-gather (x)
  (cond ((atom x) x)
        ((mtimesp x)
         (do ((next (cdr x) (cdr next))
              (xfol (cdr x) (cdr xfol))
              (modified)
              (new))
             ((null next)
              (cond ((null new) x)
                    (t (muln new nil))))
           (let* ((obj (car next)) (result obj))
             (and (mexptp result)
                  (let ((expon (exponent result)))
                    (and (not (fixnump expon))
                         (do ((remain (cdr next) (cdr remain)))
                             ((null remain))
                           (let ((powered? (car remain)))
                             (and (mexptp powered?)
                                  (let ((expon-2 (exponent powered?)))
                                    (and (not (fixnump expon-2))
                                         (let ((intdif (sub expon expon-2)))
                                           (and (fixnump intdif)
                                                (let ((pf (> intdif 0))
                                                      (ab intdif))
                                                  (declare (fixnum ab))
                                                  (cond ((or (zerop ab)
                                                             (> (+ $cost_float_power
                                                                   $cost_float_power
                                                                   (cond (pf ($expense expon-2))
                                                                         (t ($expense expon))))
                                                                (+ (cond (pf
                                                                          (let ((mbase (base result)))
                                                                            (cond ((mtimesp mbase) ($expense mbase))
                                                                                  (t 0))))
                                                                         (t
                                                                          (let ((mbase (base powered?)))
                                                                            (cond ((mtimesp mbase) ($expense mbase))
                                                                                  (t 0)))))
                                                                   (multiplies-in-nth-power (abs ab)))))
                                                         (cond ((not modified)
                                                                (setq modified t
                                                                      next (append next nil))
                                                                (setq remain (member powered? next :test #'eq))
                                                                (setq powered? (car remain))))
                                                         (cond (pf
                                                                (let ((mbase (base result)))
                                                                  (setq result
                                                                        (cond ((equal ab 1) mbase)
                                                                              (t (make-expt mbase ab))))
                                                                  (rplaca remain (make-expt (product-base mbase (base powered?)) (exponent powered?))))
                                                                (return t))
                                                               (t
                                                                (setq result (make-expt (product-base (base result) (base powered?)) (exponent result)))
                                                                (cond ((zerop ab)
                                                                       (setq next (delete powered? next :test #'eq)))
                                                                      (t
                                                                       (let ((pabs (- ab))
                                                                             (mbase (base powered?)))
                                                                         (cond ((equal pabs 1)
                                                                                (cond ((mtimesp mbase)
                                                                                       (setq next (nconc next (cdr mbase)))
                                                                                       (setq remain (member powered? next :test #'eq))
                                                                                       (setq next (delete powered? next :test #'eq)))
                                                                                      (t (rplaca remain mbase))))
                                                                               (t (rplaca remain (make-expt mbase pabs))))))))))))))))))))))
             (setq result (floating-exponent-gather result))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr (cdr x) xfol)))
             (and (or new (not (eq obj result)))
                  (setq new (nconc new
                                   (cond ((mtimesp result)
                                          (copy-tree (cdr result)))
                                         (t (ncons result)))))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (floating-exponent-gather obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defmacro div-q (x y) `(div (simplify ,x) (simplify ,y)))

(defun fgcd-exponent-gather (x)
  (cond ((atom x) x)
        ((mtimesp x)
         (do ((next (cdr x) (cdr next))
              (xfol (cdr x) (cdr xfol))
              (modified)
              (new))
             ((null next)
              (cond ((null new) x)
                    (t (muln new nil))))
           (let* ((obj (car next))
                  (result (fgcd-exponent-gather obj)))
             (and (mexptp result)
                  (let ((expon (exponent result)))
                    (and (not (fixnump expon))
                         (do ((allow-fix t nil)
                              (repeat t))
                             ((null repeat))
                           (do ((remain (cdr next) (cdr remain))
                                (current-gcd expon)
                                (pntrs))
                               ((null remain)
                                (or allow-fix (setq repeat nil))
                                (and pntrs
                                     (if (fixnump current-gcd)
                                         (<= (multiplies-in-nth-power current-gcd)
                                             (1+ (length pntrs)))
                                         t)
                                     (let* ((leadiv (gen-quotients (div-q expon current-gcd)))
                                            (a-single (equal leadiv 1))
                                            (ints (and (not a-single) (fixnump leadiv))))
                                       (do ((scan pntrs (cdr scan))
                                            (save (cond (ints
                                                         (- $cost_float_power
                                                            (multiplies-in-nth-power leadiv)))
                                                        (t 0)))
                                            (interms (cond (ints (ncons (make-expt (base result) leadiv)))
                                                           (t ())))
                                            (others (cond (ints ())
                                                          (t
                                                           (let ((mbase (base result)))
                                                             (cond (a-single
                                                                    (cond ((mtimesp mbase) (cdr mbase))
                                                                          (t (ncons mbase))))
                                                                   (t (ncons (make-expt mbase leadiv)))))))))
                                           ((null scan)
                                            (cond (interms
                                                   (let* ((prod-ints (muln interms nil))
                                                          (try-ints-gather (integer-gathering prod-ints))
                                                          (savings (- (+ (1+ (length pntrs))
                                                                         (- ($expense prod-ints)
                                                                            ($expense try-ints-gather))
                                                                         save)
                                                                      $cost_float_power)))
                                                     (declare (fixnum savings))
                                                     (if (< savings 0) (return nil))
                                                     (setq result (make-expt (muln (nconc others
                                                                                          (cond ((mtimesp try-ints-gather)
                                                                                                  (cdr try-ints-gather))
                                                                                                (t (ncons try-ints-gather))))
                                                                                   nil)
                                                                             current-gcd))))
                                                  (t
                                                   (if (not a-single) (return (setq repeat nil)))
                                                   (setq result (make-expt (muln others nil) current-gcd))))
                                            (do ((rescan pntrs (cdr rescan)))
                                                ((null rescan) (setq repeat nil))
                                              (setq next (delete (car rescan) next :test #'eq))))
                                         (declare (fixnum save))
                                         (let* ((expt (car scan))
                                                (expon-2 (exponent expt))
                                                (nxdiv (gen-quotients (div-q expon-2 current-gcd))))
                                           (cond ((equal nxdiv 1)
                                                  (setq a-single t
                                                        save (+ save $cost_float_power)
                                                        others (nconc others (let ((mbase (base expt)))
                                                                               (cond ((mtimesp mbase) (cdr mbase))
                                                                                     (t (ncons mbase)))))))
                                                 ((fixnump nxdiv)
                                                  (setq save (+ save (- $cost_float_power
                                                                        (multiplies-in-nth-power nxdiv)))
                                                        interms `(,.interms ,(make-expt (base expt) nxdiv))))
                                                 (t
                                                  (setq others `(,.others ,(make-expt (base expt) nxdiv))))))))))
                             (let ((powered? (car remain)))
                               (and (mexptp powered?)
                                    (let ((expon-2 (exponent powered?)))
                                      (and (not (fixnump expon-2))
                                           (let ((fgcd (gen-quotients ($gcd current-gcd expon-2))))
                                             (cond ((equal fgcd 1))
                                                   ((or pntrs
                                                        (alike1 fgcd expon)
                                                        (alike1 fgcd expon-2)
                                                        (and allow-fix
                                                             (or (fixnump (div-q expon fgcd))
                                                                 (fixnump (div-q expon-2 fgcd)))))
                                                    (cond ((not modified)
                                                           (setq modified t
                                                                 next (append next nil))
                                                           (setq remain (member powered? next :test #'eq))
                                                           (setq powered? (car remain))))
                                                    (setq current-gcd fgcd
                                                          pntrs `(,.pntrs ,powered?))))))))))))))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr (cdr x) xfol)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (fgcd-exponent-gather obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defun integer-exponent-gather (x)
  (cond ((atom x) x)
        ((mtimesp x)
         (do ((top x (or new top))
              (new 0 new))
             ((null new) top)
           (setq new nil)
           (do ((next (cdr top) (cdr next))
                (xfol (cdr top) (cdr xfol))
                (modified))
               ((null next)
                (and new (setq new (muln new nil))))
             (let* ((obj (car next)) (result obj))
               (and (mexptp result)
                    (let ((expon (exponent result)))
                      (and (fixnump expon)
                           (do ((remain (cdr next) (cdr remain)))
                               ((null remain))
                             (let ((powered? (car remain)))
                               (and (mexptp powered?)
                                    (let ((expon-2 (exponent powered?)))
                                      (and (fixnump expon-2)
                                           (let* ((intdif (- expon expon-2))
                                                  (pf (plusp intdif)))
                                             (declare (fixnum intdif))
                                             (cond ((or (zerop intdif)
                                                        (< (+ (cond (pf
                                                                     (let ((mbase (base result)))
                                                                       (cond ((mtimesp mbase) ($expense mbase))
                                                                             (t 0))))
                                                                    (t
                                                                     (let ((mbase (base powered?)))
                                                                       (cond ((mtimesp mbase) ($expense mbase))
                                                                             (t 0)))))
                                                              1
                                                              (multiplies-in-nth-power (abs intdif)))
                                                           (multiplies-in-nth-power (max expon expon-2))))
                                                    (cond ((not modified)
                                                           (setq modified t
                                                                 next (append next nil))
                                                           (setq remain (member powered? next :test #'eq))
                                                           (setq powered? (car remain))))
                                                    (cond (pf
                                                           (let ((mbase (base result)))
                                                             (setq result
                                                                   (cond ((equal intdif 1) mbase)
                                                                         (t (make-expt mbase intdif))))
                                                             (rplaca remain (make-expt (product-base mbase (base powered?)) (exponent powered?))))
                                                           (return t))
                                                          (t
                                                           (setq result (make-expt (product-base (base result) (base powered?)) (exponent result)))
                                                           (cond ((zerop intdif)
                                                                  (setq next (delete powered? next :test #'eq)))
                                                                 (t
                                                                  (let ((pabs (- intdif))
                                                                        (mbase (base powered?)))
                                                                    (cond ((equal pabs 1)
                                                                           (cond ((mtimesp mbase)
                                                                                  (setq next (nconc next (cdr mbase)))
                                                                                  (setq remain (member powered? next :test #'eq))
                                                                                  (setq next (delete powered? next :test #'eq)))
                                                                                 (t (rplaca remain mbase))))
                                                                          (t (rplaca remain (make-expt mbase pabs))))))))))))))))))))
               (setq result (integer-exponent-gather result))
               (or (eq obj result)
                   new
                   (setq new (copy-to-pntr (cdr top) xfol)))
               (and (or new (not (eq obj result)))
                    (setq new (nconc new
                                     (cond ((mtimesp result)
                                            (copy-tree (cdr result)))
                                           (t (ncons result))))))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (integer-exponent-gather obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defun igcd-exponent-gather (x)
  (cond ((atom x) x)
        ((mtimesp x)
         (do ((next (cdr x) (cdr next))
              (xfol (cdr x) (cdr xfol))
              (modified)
              (new))
             ((null next)
              (cond ((null new) x)
                    (t (muln new nil))))
           (let* ((obj (car next))
                  (result (igcd-exponent-gather obj)))
             (and (mexptp result)
                  (let ((expon (exponent result)))
                    (and (fixnump expon)
                         (do ((remain (cdr next) (cdr remain))
                              (current-gcd expon)
                              (pntrs))
                             ((null remain)
                              (and pntrs
                                   (do ((scan pntrs (cdr scan))
                                        (newbase (let ((mbase (base result)))
                                                   (cond ((equal expon current-gcd)
                                                          (cond ((mtimesp mbase) (cdr mbase))
                                                                (t (ncons mbase))))
                                                         (t (ncons (make-expt mbase (quotient expon current-gcd))))))))
                                       ((null scan)
                                        (setq result (make-expt (muln newbase nil) current-gcd)))
                                     (let* ((expt (car scan))
                                            (expon-2 (exponent expt)))
                                       (setq newbase (nconc newbase (let ((mbase (base expt)))
                                                                      (cond ((equal expon-2 current-gcd)
                                                                             (cond ((mtimesp mbase) (cdr mbase))
                                                                                   (t (ncons mbase))))
                                                                            (t (ncons (make-expt mbase (quotient expon-2 current-gcd)))))))
                                             next (delete expt next :test #'eq))))))
                           (declare (fixnum current-gcd))
                           (let ((powered? (car remain)))
                             (and (mexptp powered?)
                                  (let ((expon-2 (exponent powered?)))
                                    (and (fixnump expon-2)
                                         (let ((intgcd (gcd current-gcd expon-2)))
                                           (cond ((not (equal intgcd 1))
                                                  (cond ((not modified)
                                                         (setq modified t
                                                               next (append next nil))
                                                         (setq remain (member powered? next :test#'eq))
                                                         (setq powered? (car remain))))
                                                  (setq current-gcd intgcd
                                                        pntrs `(,.pntrs ,powered?)))))))))))))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr (cdr x) xfol)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (igcd-exponent-gather obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defun gen-quotients (x)
  (cond (($mapatom x) x)
        ((specrepp x) (gen-quotients (specdisrep x)))
        ((eq 'mtimes (caar x))
         (do ((next (cdr x) (cdr next))
              (denominator)
              (numerator))
             ((null next)
              (cond (denominator
                     (let ((den (mul-list denominator)))
                       (cond (numerator
                              `((mquotient) ,(mul-list numerator) ,den))
                             (t `((mquotient) 1 ,den)))))
                    (numerator (mul-list numerator))
                    (t x)))
           (let ((obj (car next)))
             (cond ((reciprocalp obj)
                    (let ((expon (gen-quotients (exponent obj)))
                          (mbase (gen-quotients (base obj))))
                      (setq denominator
                            (nconc denominator
                                   (cond ((equal expon -1)
                                          (cond ((mtimesp mbase) (cdr mbase))
                                                (t (ncons mbase))))
                                         (t (ncons (make-expt mbase (gen-negative expon)))))))
                      (or numerator
                          (do ((seplist (cdr x) (cdr seplist)))
                              ((eq seplist next))
                            (let ((element (car seplist)))
                              (or (reciprocalp element)
                                  (setq numerator `(,.numerator ,element))))))))
                   (t
                    (let ((result (gen-quotients obj)))
                      (or (eq obj result)
                          numerator
                          (do ((seplist (cdr x) (cdr seplist)))
                              ((eq seplist next))
                            (let ((element (car seplist)))
                              (or (reciprocalp element)
                                  (setq numerator `(,.numerator ,element))))))
                      (and (or numerator denominator (not (eq obj result)))
                           (setq numerator `(,.numerator ,result)))))))))
        ((reciprocalp x)
         `((mquotient) 1 ,(gen-quotients (let ((exp (exponent x))
                                               (mbase (base x)))
                                           (cond ((equal -1 exp) mbase)
                                                 (t (make-expt mbase (gen-negative exp))))))))
        (t
         (do ((next (cdr x) (cdr next))
              (new))
             ((null next)
              (cond (new new)
                    (t x)))
           (let* ((obj (car next))
                  (result (gen-quotients obj)))
             (or (eq obj result)
                 new
                 (setq new (copy-to-pntr x next)))
             (and (or new (not (eq obj result)))
                  (setq new `(,.new ,result))))))))

(defun integer-gathering (x)
   (do ((new x (igcd-exponent-gather (integer-exponent-gather new)))
        (onew 0 new))
       ((eq new onew) new)))

(defun $gather_exponents (x)
   (do ((new (gen-quotients x)
             (fgcd-exponent-gather (floating-exponent-gather new)))
        (onew 0 new))
       ((eq new onew) (integer-gathering new))))
