 #!/usr/local/bin/scsh \
 -o srfi-2 -e main -s

 Usage
 substirename.scm FROM-REGEXP TO-TEMPLATE
 FROM-REGEXP : Posix regexp
 TO-TEMPLATE : regexp substitution items -- submatch numbers, strings,
     'pre, 'post
 Rename files in the cwd with (relative) names partially matching the
 FROM-REGEXP to the respective name derived from the TO-TEMPLATE and
 the match.  Query in case of name collisions.

 Example
 substirename.scm "^([0-9]+)([A-Za-z]+)" '(2 "-" 1 post)'
 would rename "./12arch.bmp" to "./arch-12.bmp" and leave files alone
 whose names don't match the regexp.

 Works in scsh 0.6.6 (RC2).
 !#

 ;; Call procedure with source and dest string, the latter derived by
 ;; regexp substitution.
 ;;
 ;; proc : String String --> T0
 ;; source : String
 ;; pattern : Regular-Expression
 ;; template : Proper-List -- items for rx substitution, i.e.
 ;;     submatch numbers, strings, 'pre, 'post
 ;; ret val : T0 | False
 ;;
 ;; (call-substituting list "1/3" (rx (submatch (+ digit)) "/"
 ;;                                   (submatch (+ digit)))
 ;;                    '(1 "oOo" 2))
 ;; ==> ("1/3" "1oOo3")
 (define (call-substituting proc source pattern template)
   (and-let* ((match (regexp-search pattern source)))
             (proc source (apply regexp-substitute #f match template))))


 ;; Call (PROC OLD-NAME NEW-NAME) for each file in the cwd whose name OLD-NAME
 ;; partially matches the PATTERN, with NEW-NAME determined by TEMPLATE (and
 ;; the match).
 ;;
 ;; (for-each-matching-file/substitutions
 ;;  (lambda (x y) (format #t "~a ~a~%" x y))
 ;;  (rx ".")
 ;;  '(post "." pre))
 (define (for-each-matching-file/substitutions proc pattern template)
   (for-each (lambda (filename)
               (call-substituting proc filename pattern template))
             (directory-files (cwd) #t)))


 ;; no input validation, no usage message -- it's the weekend!
 (define (main args)
   (let ((re (posix-string->regexp (second args)))
         (template (read (make-string-input-port (third args)))))
     (for-each-matching-file/substitutions
      (lambda (oldname newname)
        (rename-file oldname newname 'query))
      re template)))