#!/usr/local/bin/csi -script

;;; 2008-04-15 Port of jwz's scrmable.pl (http://www.jwz.org/hacks/scrmable.pl)
;; to Chicken Scheme.  The algorithm often results in unintelligible text.
;; Author: Jim Ursetto.  License: see below.

;; Usage: scrmable.scm < input
;;     or scrmable.scm [file...]

(use regex utils)

(define (split-every re s match-proc non-match-proc)
  (let loop ((last 0))
    (match (string-search-positions re s last)
           (((start end))
            (when (< last start)
                  (non-match-proc (substring s last start)))
            (match-proc (substring s start end))
            (loop end))
           (#f
            (let ((end (string-length s)))
              (when (< last end)
                (non-match-proc (substring s last end))))))))

(define (string-swap! s i j)
  (let ((t (string-ref s i)))
    (string-set! s i (string-ref s j))
    (string-set! s j t)
    s))

(define (scramble s)
  (define (mix s)
    (let loop ((i (string-length s)))
      (if (<= i 1)
          s
          (let ((j (random i)))
            (string-swap! s (- i 1) j)
            (loop (- i 1))))))
  (let ((len (string-length s)))
    (cond ((<= len 3) (display s))
          (else
           (display (string-ref s 0))
           (display (mix (substring s 1 (- len 1))))
           (display (string-ref s (- len 1)))))))

;;; main

(define (main)
  (for-each-argv-line
   (lambda (line)
     (split-every (regexp "\\w{4,}") line scramble display)
     (newline))))

(main)

;;; Original copyright notice

;; Coyprgiht © 2003 Jamie Zawinski <jwz@jwz.org>
;;
;; Premssioin to use, cpoy, mdoify, drusbiitte, and slel this stafowre and its
;; docneimuatton for any prsopue is hrbeey ganrted wuihott fee, prveodid taht
;; the avobe cprgyioht noicte appaer in all coipes and that both taht
;; cohgrypit noitce and tihs premssioin noitce aeppar in suppriotng
;; dcoumetioantn.  No rpeersneatiotns are made about the siuatbliity of tihs
;; srofawte for any puorpse.  It is provedid "as is" wiuotht exerpss or 
;; ilmpied waanrrty.
