;;; -*- 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 cfortr)


(declare (special lb rb         ;used for communication with mstring.
                  $loadprint    ;if nil, no load message gets printed.
                  1//2 -1//2
                  prefix-psize suffix-psize))

(defmvar pure-fortran nil "If T, separate FORTRAN output enabled." boolean)
(defmvar comment-fortran nil "T for comments only." boolean)
(defmvar fortran-wallpaper 't "SFA file stream")
(defmvar fort-line-width (- 72 6) "Max # of statement characters" fixnum)
(defmvar allowed-length-floor 28 "Min # of characters in a subexpression" fixnum)
(defmvar halfing-floor (* 2 allowed-length-floor) "See ALLOWED-LENGTH-FLOOR" fixnum)
(defmvar pure-col 0 "Internal column counter" fixnum)
(defmvar tab-encounter nil "Tab character encountered flag" boolean)

(defmvar $fortspaces nil
   "If TRUE, fortran card images are filled out to 80 columns using spaces."
   boolean
   modified-commands '$cray_fortran)

(defmvar $fortindent 0
   "The number of spaces (beyond 6) to indent fortran statements as they
   are printed."
   fixnum
   modified-commands '$cray_fortran)

(defmvar $fort_float t
   "Should be set to FALSE for code sequences containing only integer
 operations."
   boolean
   modified-commands '$cray_fortran)

(defmvar $fort_power_float nil
   "If TRUE, generate floating exponents in CRAY_FORTRAN output."
   boolean
   modified-commands '$cray_fortran)

(defmvar $allowed_length 1250.
   "Approximate number of characters in a FORTRAN statement with 19
  continuation lines.  This is the maximum allowed by CFT."
   fixnum
   modified-commands '$cray_fortran)

(defmvar $labelength 700.
   "Minimum number of FORTRAN characters a subexpression must generate
 before that subexpression can be broken out of an expression which
 exceeds ALLOWED_LENGTH FORTRAN characters.  This floor value is decreased
 by CRAY_FORTRAN as needed to permit the breaking apart of all oversized
 expressions."
   fixnum
   modified-commands '$cray_fortran)

(defmvar $break_prefix '$aa
   "Prefix string used to construct names for subexpressions which
 have been broken out of an expression which is too large for the CFT
 compiler."
   modified-commands '$cray_fortran)

(defmvar $fbreak_temp_counter 1
   "Integer index used to generate unique names for subexpressions which
 have been broken out of an expression which is too large for the CFT
 compiler."
   fixnum
   modified-commands '$cray_fortran)

(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 $fortran_subst_list (list '(mlist simp))
   "MACSYMA list of equations wherein each equation is interpreted as a
 LISP list of characters(RHS) to be substituted for another LISP list of
 characters(LHS) whenever the latter series of characters are encountered
 in the CRAY_FORTRAN output.  The CRAY_FORTRAN output is one long LISP list
 of characters at the point of comparison.
    The need for this variable and associated facility is an artifact of
 including subscript information in variable names in the interest of saving
 memory when the subscripts are strictly formal."
   modified-commands '$cray_fortran)

(defmvar $fort_string nil
   "If TRUE, causes CRAY_FORTRAN to return one long string of characters
 instead of generating textual output."
   boolean
   modified-commands '$cray_fortran)

(defmvar data-info nil
   "List to be used in setting up FORTRAN DATA statements.")

;; This function is called from Macsyma toplevel.  If the argument is a
;; symbol, and the symbol is bound to a matrix, then the matrix is printed
;; using an array assignment notation.

(defmspec $cray_fortran (l)
 (setq l (fexprcheck l))
 (let ((value (strmeval l)))
      (cond ((msetqp l) (setq value `((mequal) ,(cadr l) ,(meval l)))))
      (cond ((and (symbolp l) ($matrixp value))
             ($fortmx l value))
            ((and (not (atom value)) (eq (caar value) 'mequal)
                  (symbolp (cadr value)) ($matrixp (caddr value)))
             ($fortmx (cadr value) (caddr value)))
            (t (fortran-print value)))))

;; This function is called from Lisp programs.  It takes an expression and
;; a stream argument.  Default stream is NIL in MacLisp and STANDARD-OUTPUT
;; in LMLisp.  This should be canonicalized in Macsyma at some point.

;; TERPRI is a PDP10 MacLisp flag which, if set to T, will keep symbols and
;; bignums from being broken across page boundaries when printed.  $LOADPRINT
;; is NIL to keep a message from being printed when the file containing MSTRING
;; is loaded.  (MRG;GRIND)

(defprop mexpt (#\* #\*) dissym)

(defun fortran-print (x &optional bypass (stream standard-output)
                        ;; this is a poor way of saying that array references
                        ;; are to be printed with parens instead of brackets.
                        (lb #/( ) (rb #/) ))
  ;; restructure the expression for displaying.
  (or bypass (setq x ($fortranbreak (fortscan x))))
  ;; linearize the expression using mstring.  some global state must be
  ;; modified for mstring to generate using fortran syntax.  this must be
  ;; undone so as not to modifiy the toplevel behavior of mstring.
  (unwind-protect
   (progn
    (defprop mexpt msize-infix grind)
    (defprop mminus 100. lbp)
    (defprop msetq (#/=) strsym)
    (setq x (delete #/\ (mstring x))))
   ;; make sure this gets done before exiting this frame.
   (defprop mexpt msz-mexpt grind)
   (remprop 'mminus 'lbp)
   (defprop msetq (#/:) strsym))
  (do ((spot x (cdr spot))
       (trail x spot))
      ((null spot))
    (do ((pattern (cdr $fortran_subst_list) (cdr pattern)))
        ((null pattern))
      (and (do ((look (cdadar pattern) (cdr look))
                (follow spot (cdr follow)))
               ((null look)
                (rplacd trail (append (cdr (caddar pattern)) follow))
                (setq spot (nthcdr (1- (length (caddar pattern))) trail))
                t)
             (and (or (null follow)
                      (not (equal (car follow) (car look))))
                  (return nil)))
           (return t))))
  (if $fort_string (maknam x)
  ;; mstring returns a list of characters.   now print them.
      (prog1 '$done
             (do ((c #/0 (+ 1 (\ (- c #/0) 16) #/0))
                  (column (+ 6 $fortindent) (+ 9 $fortindent)))
                 ((null x))
      ;; print five spaces, a continuation character if needed, and then
      ;; more spaces.  column points to the last column printed in.  when
      ;; it equals 80, we should quit.
               (cond ((= c #/0)
                      (print-spaces column stream))
                     (t (print-spaces 5 stream)
                        (tyo c stream)
                        (and pure-fortran (tyo c fortran-wallpaper))
                        (print-spaces (- column 6) stream)))
      ;; print the expression.  remember, fortran ignores blanks and line
      ;; terminators, so we don't care where the expression is broken.
               (do ()
                   ((= column 72.))
                   (if (null x)
                       (cond ($fortspaces
                              (and pure-fortran (tyo #\SP fortran-wallpaper))
                              (tyo #\SP stream))
                             (t (return nil)))
                       (let ((char (pop x)))
                         (tyo char stream)
                         (and pure-fortran (tyo char fortran-wallpaper))))
                   (incf column))
      ;; columns 73 to 80 contain spaces
               (if $fortspaces (print-spaces 8 stream))
               (terpri stream)
               (and pure-fortran (terpri fortran-wallpaper))))))

(defun print-spaces (n stream)
       (dotimes (i n) 
                (tyo #\SP stream)
                (and pure-fortran (tyo #\SP fortran-wallpaper))))

(defun rem-value (x)
    (let ((numer (cadr x)))
      (declare (fixnum numer))
      (let* ((rep (append (list #/$ #/c)
                          (cond ((minusp numer)
                                 (append (list #/m) (exploden (abs numer))))
                                (t (exploden numer)))
                          (append (list #/d) (exploden (caddr x)))))
             (dlen (length rep))
             (dret (implode (cond ((< dlen 10) rep)
                                  (t (rplacd (nthcdr 8 rep) nil) rep)))))
        (cond ((do ((scan (cdr data-info) (cdr scan)))
                   ((null scan))
                 (cond ((alike1 (caar scan) x) (return t))
                       ((eq (cadar scan) dret)
                        (setq dret (implode (append (exploden dret) (list #/c)))
                              dlen (1+ dlen))
                        (return nil)))))
              (t
               (if (> dlen 9)
                   ($comment_fortran `((mequal) ,dret ,x)))
               (setq data-info `(,.data-info
                                 ,(list x (stripdollar dret) ($float x))))))
        dret)))

;; This function is similar to NFORMAT.  Prepare an expression
;; for printing by converting x^(1/2) to sqrt(x), etc.  A better
;; way of doing this would be to have a programmable printer and
;; not cons any new expressions at all.  Some of this formatting, such
;; as E^X --> EXP(X) is specific to Fortran, but why isn't the standard
;; function used for the rest?

(defun fortscan (e)
 (cond ((atom e)
        (cond ((and $fort_float (fixnump e)) (float e))
              ((eq e '$%i) (list '(mprogn) 0.0 1.0)) ;; %I is (0,1)
              (t e)))
       ((member 'array (cdar e) :test #'eq) e)
       (t (let ((op (caar e)))
            (cond ((eq op '%log) (list '(%alog simp) (fortscan (cadr e))))
                  ((eq op 'mexpt)
                   (let ((expon (caddr e)) (mybase (cadr e)))
                     (cond ((eq mybase '$%e) (list '(%exp simp) (fortscan expon)))
                           ((alike1 expon 1//2) (list '(%sqrt simp) (fortscan mybase)))
                           ((alike1 expon -1//2)
                            (list '(mquotient simp) 1 (list '(%sqrt simp) (fortscan mybase))))
                           (t (list (car e)
                                    (fortscan mybase)
                                    (cond ((fixnump expon)
                                           (cond ($fort_power_float (float expon))
                                                 (t expon)))
                                          (t (fortscan expon))))))))
                  ((eq op 'rat) (rem-value e))
                  ((eq op 'mrat) (fortscan (ratdisrep e)))
                  ;;  complex numbers to f77 syntax a+b%i ==> (a,b)
                  ((and (member op '(mtimes mplus) :test #'eq)
                        ((lambda (a) 
                           (and (numberp (cadr a))
                                (numberp (caddr a))
                                (not (zerop1 (cadr a)))
                                (list '(mprogn) (caddr a) (cadr a))))
                         (simplify ($bothcoef e '$%i)))))
                  ((and (eq op 'mtimes) (equal -1 (cadr e)))
                   `((mminus simp) ,(cond ((cdddr e)
                                           (do ((ele (cddr e) (cdr ele))
                                                (nl (list '(mtimes simp))
						    `(,@nl ,(fortscan (car ele)))))
                                               ((null ele) nl)))
                                          (t (fortscan (caddr e))))))
                  ((and (eq op 'mquotient) (member (cadr e) '(1 -1)))
                   `((mquotient simp) ,(cadr e) ,(fortscan (caddr e))))
                  (t (do ((ele (cdr e) (cdr ele))
                          (nl nil `(,@nl ,(fortscan (car ele)))))
                         ((null ele) (cons (car e) nl)))))))))

;; takes a name and a matrix and prints a sequence of Fortran assignment
;; statements of the form
;;  NAME(I,J) = <corresponding matrix element>

(defmfun $fortmx (name mat &optional (stream standard-output) &aux ($loadprint nil))
  (declare (fixnum i j))
  (cond ((not (eq (typep name) 'symbol))
         (merror "~%First argument to FORTMX must be a symbol."))
        ((not ($matrixp mat))
         (merror "Second argument to FORTMX must be a matrix: ~M" mat)))
  (do ((mat (cdr mat) (cdr mat)) (i 1 (1+ i))) ((null mat))
      (do ((m (cdar mat) (cdr m)) (j 1 (1+ j))) ((null m))
          (fortran-print `((mequal) ((,name) ,i ,j) ,(car m)) stream)))
  '$done)

(defun fort-len (x)
  (cond ((numberp x) (flatc x))
        ((atom x) (1- (flatc x)))
        (t (let ((op (caar x)))
             (let ((fpp (eq op 'mplus))
                   (prod (eq op 'mtimes)))
               (do ((mp (cdr x) (cdr mp))
                    (brackets (member op '(mtimes mexpt mquotient) :test #'eq))
                    (negexps 0)
                    (sm (cond ((or prod fpp (eq op 'mquotient)) -1)
                              ((member op '(mexpt mminus) :test #'eq) 0)
                              (t (flatc op)))))
                   ((null mp)
                    (and (> sm $labelength) 
                         (let ((len-q (last (car x)))) 
                           (cond ((fixnump (car len-q)) (rplaca len-q sm))
                                 (t (rplaca x `(,(caar x) simp ,sm))))))
                    sm)
                 (declare (fixnum sm negexps))
                 (let ((obj (car mp)))
                   (setq sm (+ sm (fort-len obj) 1))
                   (cond ((atom obj))
                         (brackets
                          (let ((inop (caar obj)))
                            (and (or (member inop '(mplus mminus) :test #'eq)
                                     (and prod
                                          (eq inop 'mexpt)
                                          (let ((exn (caddr obj)))
                                            (and (numberp exn)
                                                 (minusp exn)
                                                 (setq sm (cond ((equal exn -1)
                                                                 (- sm 4))
                                                                (t (1- sm)))
                                                       negexps (1+ negexps))))
                                          (= negexps 2)))
                                 (setq sm (+ 2 sm)))))
                         (fpp
                          (let ((led (cadr obj)))
                            (and (or (and (numberp led) (minusp led))
                                     (eq (caar obj) 'mminus))
                                 (cdr mp)
                                 (setq sm (1- sm)))))))))))))

(defun fort-temp (x)
  (let ((cp-sym (implode (nconc (exploden $break_prefix)
                                (exploden $fbreak_temp_counter)
                                (exploden $sequence_optim_suffix)))))
    (incf $fbreak_temp_counter)
    (fortran-print `((mequal) ,cp-sym ,x) t)
    cp-sym))

(defun break-p-t (x size)
   (cond (($mapatom x))
         (t
          (let ((opr (caar x)))
            (cond ((member opr '(mtimes mplus) :test #'eq)
                   (do ((newlen (+ 2 (+ prefix-psize suffix-psize
                                        (flatc $fbreak_temp_counter))))
                        (threshold (truncate size 2))
                        (newobj)
                        (big-ones)
                        (scan (cdr x) (cdr scan)))
                       ((null scan)
                        (cond ((> newlen threshold)
                               (rplaca (member (car newobj) x :test #'eq)
                                       (fort-temp (cond ((eq opr 'mplus)
                                                         (addn newobj nil))
                                                        (t (muln newobj nil)))))
                               (do ((iscan (cdr newobj) (cdr iscan)))
                                   ((null iscan))
                                 (setq x (delete (car iscan) x :test #'eq))))
                              (t
                               (do ((iscan big-ones (cdr iscan)))
                                   ((null iscan))
                                 (break-p-t (caar iscan) (cadar iscan))))))
                     (let* ((obj (car scan))
                            (plen (fort-len obj))
                            (trylen (+ newlen plen 1)))
                       (cond ((< trylen $allowed_length)
                              (setq newlen trylen
                                    newobj `(,.newobj ,obj)))
                             ((< newlen threshold)
                              (setq big-ones
                                    `(,.big-ones ,(list obj plen))))))))
                  (t
                   (do ((scan (cdr x) (cdr scan)))
                       ((null scan))
                     (let* ((obj (car scan))
                            (plen (fort-len obj)))
                       (and (>= plen allowed-length-floor)
                            (break-p-t obj plen))))))))))

(defun pre-compile (x)
   (cond ((atom x) 0)
         (t
          (let ((lenf (car (last (car x)))))
            (cond ((not (fixnump lenf)) 0)
                  (t
                   (do ((est lenf))
                       ((< est $allowed_length) est)
                     (declare (fixnum est))
                     (do ((next (cdr x) (cdr next))
                          (posit (cdr x) (cond ((> ntg rsize) next)
                                               (t posit)))
                          (rsize 0 (max rsize ntg))
                          (ntg 0))
                         ((null next)
                          (cond ((= rsize 0)
                                 (cond ((< $labelength halfing-floor)
                                        (break-p-t x est))
                                       (t
                                        (setq $labelength (truncate $labelength 2))))
                                 (setq est (fort-len x)))
                                (t
                                 (let ((prt (car posit)))
                                   (cond ((< rsize $allowed_length) 
                                          (let ((newsym (fort-temp prt)))
                                            (rplaca posit newsym)
                                            (setq est (+ (- est rsize) (flatc newsym)))))
                                         (t
                                          (let ((newlen (pre-compile prt)))
                                            (declare (fixnum newlen))
                                            (rplaca (last (car prt)) newlen)
                                            (setq est (- est (- rsize newlen))))))))))
                       (declare (fixnum rsize ntg))
                       (setq ntg (let ((potl-atom (car next)))
                                   (cond ((atom potl-atom) 0)
                                         (t
                                          (let ((pnum (car (last (car potl-atom)))))
                                            (cond ((fixnump pnum) pnum)
                                                  (t 0)))))))))))))))

(defun $fortranbreak (x)
   (setq $allowed_length (max allowed-length-floor $allowed_length))
   (cond ((> (fort-len x) (1- $allowed_length))
          (setq $labelength (max halfing-floor $labelength)
                prefix-psize (flatc $break_prefix)
                suffix-psize (flatc $sequence_optim_suffix))
          (pre-compile x)))
   x)

(defmacro tablen () 8)

(defvar eliminate-space nil)

(defun pure-fortran-handler (self op arg)
   (caseq op
     (:open (open arg '(out)))
     (:close (close arg))
     (:which-operations
      '(:tyo :print :princ :filemode :open :close :terpri))
     (t
      (let ((out-designate (sfa-get fortran-wallpaper 0)))
        (cond ((eq op :terpri)
               (tyo #\cr out-designate)
               (cond (comment-fortran
                      (tyo #/c out-designate)
                      (tyo #\sp out-designate)))
               (setq pure-col 0))
	      ((eq op :write-char) (sfa-call self :tyo (char-code arg)))
              ((eq op :tyo)
               (cond ((= arg #\tab)
                      (let* ((tabsz (tablen))
                             (left (\ pure-col tabsz)))
                        (if (or tab-encounter
                                (not (or (= left (- tabsz 2))
					 (= left (1- tabsz)))))
			    (progn
			      (tyo arg out-designate)
			      (setq eliminate-space nil))
			    (if (= left (1- tabsz)) (setq eliminate-space t)))
			(setq pure-col (+ tabsz (* tabsz (truncate pure-col tabsz)))
			      tab-encounter t)))
                     (t
                      (if (and comment-fortran tab-encounter)
			  (progn
			    (if eliminate-space (princ " " out-designate)
			        (princ "  " out-designate))
			    (setq tab-encounter nil eliminate-space nil)))
                      (setq pure-col (1+ pure-col))
                      (tyo arg out-designate))))
              ((member op '(:print :princ) :test #'eq)
               (if (eq op :print) (setq pure-col 0))
               (let ((str `(nil nil ,@(exploden arg))))
                 (do ((rst (cdr str) (cdr rst))
                      (follow str rst)
                      (tabsize (tablen)))
                     ((null (cdr rst))
                      (funcall op (maknam (cddr str)) out-designate)
                      (if (eq op :print) (setq pure-col (1+ pure-col))))
                   (let ((next (cadr rst)))
                     (declare (fixnum next))
                     (cond ((= next #\tab)
                            (let ((left (\ pure-col tabsize)))
			      (if (and (not tab-encounter)
				       (or (= left (- tabsize 2))
					   (= left (1- tabsize))))
				  (progn
				   (rplacd rst (cddr rst))
				   (if (= left (1- tabsize))
				       (setq eliminate-space t))
				   (setq rst follow)))
			      (if tab-encounter (setq eliminate-space nil))
			      (setq pure-col (+ tabsize (* tabsize (truncate pure-col tabsize)))
				    tab-encounter t)))
			   (t
			    (if (and comment-fortran tab-encounter)
				(progn
				 (if eliminate-space
				     (progn
				      (rplacd rst `(#\sp ,@(cdr rst)))
				      (setq rst (cdr rst)))
				     (progn
				      (rplacd rst `(#\sp #\sp ,@(cdr rst)))
				      (setq rst (cddr rst))))
				 (setq tab-encounter nil eliminate-space nil)))
                            (setq pure-col (1+ pure-col))))))))
              ((eq op :filemode) (status filemode out-designate))
              (t (sfa-unclaimed-message self op arg)))))))

(defun $open_fortran_file (file)
 (and (eq fortran-wallpaper 't)
      (status feature sfa)
      (setq fortran-wallpaper
            (sfa-create 'pure-fortran-handler 1 'fortran-wallpaper)))
 (sfa-store fortran-wallpaper 0 (sfa-call fortran-wallpaper :open ($filename_merge file)))
 (setq pure-fortran t))

(defun $close_fortran_file ()
  (cond (pure-fortran
         (terpri fortran-wallpaper)
         (sfa-call fortran-wallpaper :close (sfa-get fortran-wallpaper 0))
         (setq pure-fortran nil)))
  '$done)

(defun $comment_fortran (x)
  (cond (pure-fortran
         (let ((comment-fortran t))
           (tyo #/c fortran-wallpaper)
           (tyo #\sp fortran-wallpaper)
           (terpri fortran-wallpaper)
           (mformat fortran-wallpaper "~M" x))
         (terpri fortran-wallpaper))))

(defun zconcat (a b) (format NIL "~A~A" a b))

(defun $generate_data_section (&optional (stream standard-output))
   (if data-info
       (do ((step 15)
            (contin -1 -1)
            (header "      data " "      data "))
           ((null data-info) '$done)
         (do ((data data-info (nthcdr istep data))
              (indent 5 3)
              (istep step step))
             ((or (null data) (= contin 19))
              (setq data-info data))
           (let ((nam (cadar data)) (val (caddar data)))
             (setq header
                           (zconcat header nam)
                   contin (1+ contin))
             (do ((lst (cdr data) (cdr lst))
                  (cnt 1 (1+ cnt))
                  (chars-left (- fort-line-width indent 2 (flatc nam) (flatc val)))
                  (suffix
                           (zconcat '// val)))
                 ((or (null lst) (>= cnt istep))
                  (setq header 
                                (zconcat header (zconcat suffix '//)))
;;;               (and (nthcdr istep data) (< contin 19)
;;;                    (setq header
;;;                                  (zconcat header ",")))
                  (mformat stream "~A~%" header)
                  (and pure-fortran (mformat fortran-wallpaper "~A~%" header))
                  (setq header "     1   "))
               (let ((name (cadar lst)) (value (caddar lst)))
                 (cond ((< (setq chars-left
                                 (- chars-left 2 (flatc name) (flatc value)))
                           0)
                        (setq istep cnt))
                       (t
                        (setq header 
                                      (zconcat header (zconcat "," name))
                              suffix
                                     (zconcat suffix (zconcat "," value))))))))))))

(defun $exploden (x)
  `((mlist simp) ,@(exploden x)))

(defun $maknam (x)
  (maknam (cdr x)))
