(defun ess-find-rterm (&optional ess-root-dir)
  "Find the full path of all occurences of Rterm.exe under the ESS-ROOT-DIR.
If ESS-ROOT-DIR is nil, construct it by looking for an occurence of Rterm.exe
in the exec-path."
  (if (not ess-root-dir)
      (setq ess-root-dir
	    (expand-file-name (concat
			       (file-name-directory (executable-find "Rterm"))
			       "../../"))))
  (ess-uniq-list (ess-find-exec  "Rterm" ess-root-dir)))


(defun ess-rterm-versions-create ()
  "Generate the `M-x R-X.Y' functions for starting other versions of R.
See `ess-rterm-versions' for strings that determine which functions
are created."

  ;; This works by creating a temp buffer where the template function is
  ;; edited so that X.Y is replaced by the version name
  (let ((template "")
	(beg)
	(versions)
	(version)
	(eval-buf (get-buffer-create "*ess-temp-r-evals*"))
	)
    ;; 
    ;; This is the template function used for creating M-x R-X.Y.
    (setq template "(defun R-X.Y (&optional start-args)
  \"Call R-X.Y, i.e., the R version 'R-X.Y' using ESS.
This function was generated by `ess-rterm-versions-create'.\"
  (interactive \"P\")
  (let ((inferior-R-program-name \"Rterm-X.Y\"))
    (R start-args)))

")
    (save-excursion
      (set-buffer eval-buf)
      ;; clear the buffer.
      (delete-region (point-min) (point-max))

      ;; Find which versions of R we want.  Remove the pathname, leaving just
      ;; the name of the executable.
      (setq versions ess-rterm-versions)
      (ess-write-to-dribble-buffer
       (format "(R): ess-rterm-versions-create making M-x defuns for %s"
	       (mapconcat 'identity versions " ")))

      ;; Iterate over each string in VERSIONS, creating a new defun each time.
      (while versions
	(setq version (car versions)
	      versions (cdr versions)
	      version-root (file-name-nondirectory
			    (substring (file-name-directory
					(substring
					 (file-name-directory version)
					 0 -1)) 
				       0 -1)))
	(setq beg (point))
	(insert template)
	(goto-char beg)
	(while (search-forward "R-X.Y" nil t)
	  (replace-match version-root t t))
	(goto-char beg)
	(while (search-forward "Rterm-X.Y" nil t)
	  (replace-match version t t))
	(goto-char (point-max))
	)
      ;; buffer has now been created with defuns, so eval them!
      (eval-buffer)
      (kill-buffer eval-buf)
      )))


(setq ess-rterm-versions (ess-find-rterm))
(ess-rterm-versions-create)
