;;; -*-  Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;     The data in this file contains enhancments.                    ;;;;;
;;;                                                                    ;;;;;
;;;  Copyright (c) 1984,1987 by William Schelter,University of Texas   ;;;;;
;;;     All rights reserved                                            ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;     (c) Copyright 1980 Massachusetts Institute of Technology         ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(in-package "MAXIMA")
(macsyma-module scs)

(DECLARE-TOP (*EXPR $RATSUBST CONSSIZE))

(DEFMFUN $SCSIMP N 
  (DO ((I N (f1- I)) (ZRS)) ((= 1 I) (SCS (ARG 1) ZRS))
      (SETQ ZRS (CONS (IFN (EQ 'MEQUAL (CAAR (ARG I))) (ARG I)
			   (SUB (CADR (ARG I)) (CADDR (ARG I)))) ZRS))))

(DEFUN SCS (X ZRS)
  (DO ((FLAG T) (SZ (CONSSIZE X)) (NX) (NSZ)) ((NOT FLAG) X)
      (DO ((L ZRS (CDR L))) ((NULL L) (SETQ FLAG NIL))
	  (SETQ NX (SUBSCS 0 (CAR L) X) NSZ (CONSSIZE NX))
	  (IF (< NSZ SZ) (RETURN (SETQ X NX SZ NSZ))))))

(DEFUN SUBSCS (A B C)
  (COND ((ATOM B) (SUBSC A B C))
	((EQ 'MPLUS (CAAR B))
	 (DO ((L (CDR B) (CDR L)) (SZ (CONSSIZE C)) (NL) (NC) (NSZ)) ((NULL L) C)
	     (SETQ NC (SUBSCS (SUB A (ADDN (RECONC NL (CDR L)) T)) (CAR L) C)
		   NSZ (CONSSIZE NC) NL (CONS (CAR L) NL))
	     (IF (< NSZ SZ) (SETQ C NC SZ NSZ))))
	(T (SUBSC A B C))))

(DEFUN SUBSC (A B C) ($EXPAND ($RATSUBST A B C)))

(DEFMFUN $DISTRIB (EXP)
  (COND ((OR (MNUMP EXP) (SYMBOLP EXP)) EXP)
	((EQ 'MTIMES (CAAR EXP))
	 (SETQ EXP (MAPCAR '$DISTRIB (CDR EXP)))
	 (DO ((L (CDR EXP) (CDR L))
	      (NL (IF (MPLUSP (CAR EXP)) (CDAR EXP) (LIST (CAR EXP)))))
	     ((NULL L) (ADDN NL T))
	     (IF (MPLUSP (CAR L))
		 (DO ((M (CDAR L) (CDR M)) (ML)) ((NULL M) (SETQ NL ML))
		     (SETQ ML (DSTRB (CAR M) NL ML)))
		 (SETQ NL (DSTRB (CAR L) NL NIL)))))
	((EQ 'MEQUAL (CAAR EXP))
	 (LIST '(MEQUAL) ($DISTRIB (CADR EXP)) ($DISTRIB (CADDR EXP))))
	((EQ 'MRAT (CAAR EXP)) ($DISTRIB (RATDISREP EXP)))
	(T EXP)))

(DEFUN DSTRB (X L NL)
  (DO () ((NULL L) NL)
      (SETQ NL (CONS (MUL X (CAR L)) NL) L (CDR L))))

(DEFMFUN $FACOUT (X Y)
  (IFN (EQ 'MPLUS (CAAR Y)) Y
       (MUL X (ADDN (MAPCAR #'(LAMBDA (L) (DIV L X)) (CDR Y)) T))))
