#!/usr/pkg/bin/emacs --script
;;
;; break thai string into words separated by spaces, using only
;; 'thai-break-words from 'thai-word library with merged wordlist
;;
;; - if no args, process stdin
;; - if one arg and file exists with arg name, process file
;; - else join remainder of args and process
;;

;;(toggle-debug-on-error) ;; debug

;; turn off loading messages
(setq pthai-verbose-wordloads nil)

;; load pthai library
(load "/usr/pkg/share/split-thai/pthai" nil t)

;; split a thai line by spaces, return new line
(defun process-thai-line(line)
  (with-temp-buffer
    (insert line)
    (goto-char (point-min))
    (thai-break-words " " (line-end-position))
    (buffer-string)))

;; hack to process stdin
(defun process-stdin()
  (condition-case nil
      (let (aline)
	(while (setq aline (read-from-minibuffer ""))
	  (princ (process-thai-line aline))
	  (princ "\n")))
    (error nil)))

;; process arguments, remove "emacs -scriptload scriptname" from args,
;; join the rest by spaces
(setq args (cdddr command-line-args))
(setq argc (length args))

;; no args => process stdin
(when (= 0 argc)
  (process-stdin)
  (kill-emacs 0))

;; if one arg and arg is a file, process that file
;; else process all input args joined by spaces with an added newline
(with-temp-buffer
  (if (and (= 1 argc) (file-exists-p (car args)))
      (insert-file-contents (car args))
    (insert (mapconcat 'identity (cdddr command-line-args) " "))
    (insert "\n"))
  (goto-char (point-min))
  (thai-break-words " " (point-max))
  (write-region nil nil "/dev/stdout"))
(kill-emacs 0)
