;;; Command to read buffer sentence by sentence

(defvar read-book-tts-program "/home/dima/bin/magic_tts_script"
  "*Program used by read-book for tts sakes.
These program should accept text on stdin and produce speech output.")


(defun read-book ()
  "Reads text sentence by sentence through the program
specified by read-book-tts-program variable."
  (interactive)
  (dtk-stop)
  (sleep-for 1)
  (ems-inhibit-point-motion-hooks)
  (push-mark nil t)
  (let* ((sentence-end-double-space nil)
	 (sentence-end "[.?!][]\"')}]*[ \t\n]+")
	 (BEG (progn
		(forward-sentence -1)
		(point)))
	 (END BEG))
    (while (< BEG
	      (setq END
		    (save-excursion
		      (forward-sentence 1)
		      (point))))
      (read-book-speak-region BEG END)
      (goto-char (setq BEG END))
      )))


(defun read-book-speak-region (begin end)
  (let ((buf (get-buffer-create " *book*"))
	(oldbuf (current-buffer)))
    (with-current-buffer buf
      (erase-buffer)
      (insert-buffer-substring oldbuf begin end)
      ;; Cleaning the text
      (goto-char (point-min))
      (while (re-search-forward "[ \t\n]+" nil t)
	(replace-match " "))
      (goto-char (point-max))
      (insert "\n")
      ;; Now speak it
      (call-process-region (point-min) (point-max)
			   read-book-tts-program
			   nil nil nil))))
