;
; bible.el - print a random bible verse
;

; keep quiet about "mark set" and other stupid stuff
(defun message (&rest x)
  nil
)

(defun abs (x) (if (> x 0) x (- 0 x)))

(defun sizes-and-names ()
  (save-excursion
    (set-buffer (get-buffer-create "foo"))
    (delete-region (point-min) (point-max))
    (insert "(")
    (let ((standard-output nil))
     (shell-command "ls -l [0-9][0-9].* | awk '{print \"(\" $4 \" \\\"\" $8 \"\\\")\"}'" t)
    )
    (goto-char (point-max))
    (insert ")\n")
    (goto-char (point-min))
    (read (current-buffer))
    )
  )


;; Find the file in containing OFFSET in FILES; return a list
;; (OFFSET FILENAME) where OFFSET is the position from the beginning of
;; the file
(defun offset-to-file (offset files)
  (if (< offset (car (car files)))
      (cons offset (cdr (car files)))
      (offset-to-file (- offset (car (car files))) (cdr files))
  )
)


(defun random-verse ()
  (let* 
      ((files (sizes-and-names))
       ;; get the total length in bytes of all files
       (total (apply '+ (mapcar '(lambda (x) (car x)) files)))
       (offset (mod (abs (random t)) total))
       (location (offset-to-file offset files))
       )
    (save-excursion
      (find-file (car (cdr location)))
      (goto-char (car location))
      (princ 
        (buffer-substring
	  (progn
	    (if (search-backward "\n\n")
	       (forward-char 2)		; to beginning of current verse
	       (goto-char (point-min))	; to beginning of first verse
	    )
	    (point)
	  )
	  (save-excursion
	    (if (search-forward "\n\n")
	       (backward-char 2)		; to end of current verse
	       (goto-char (point-max))	; to end of last verse
	    )
	    (point)
	 )
       )
     )
   )
  )
)

(random-verse)
