;;AUTOLOAD: concat-paths
;;AUTODOC: concat-paths "concatenate file paths (directory and file name)"
;; (concat-paths directory-name file-name)
;;
;; returns the concatenation of directory and file path, taking into account
;; pending "/"s, empty dirs, ../ in file names...
;;
;; (concat-paths "" "foo")         ==> "foo"
;; (concat-paths "foo" "bar")      ==> "foo/bar"
;; (concat-paths "foo/" "bar")      ==> "foo/bar"
;; (concat-paths "foo" "/bar")      ==> "/bar"
;; (concat-paths "/foo/bar/" "../gee") ==> "foo/gee"

(setq concat-paths:re-dotdot (regcomp "^[.][.][/](.*)$"))
(setq concat-paths:re-last (regcomp "^((.*)[/])?([^/]+)[/]?$"))

(defun concat-paths (dir file &aux path)
  (if 
    (= "" dir) file			;no dir
    (= #\/ (0 file)) file		;absolute pathname
    (regexec concat-paths:re-dotdot file) (progn ;file begin with ../
      (if (regexec concat-paths:re-last dir)
	(concat-paths (regsub concat-paths:re-last 2)
	  (regsub concat-paths:re-dotdot 1)
	)
	file
    ))
    (if (= #\/ ((- (length dir) 1) dir))
      (+ dir file)
      (+ dir "/" file)
    )
))
