#!/usr/local/bin/gosh

(use gauche.charconv)
(use gauche.process)
(use util.let-args)
(use srfi-13)

(define (main args)
  (let-args (cdr args)
      ((from "from=s" "UTF-8")
       (to "to=s" (gauche-character-encoding))
       (command "command=s")
       (in-file "in=s" "-")
       (out-file "out=s" "-"))
    (let ((in ;;(open-input-conversion-port
               (cond ((equal? in-file "-")
                      (current-input-port))
                     (else
                      (open-input-file in-file)))
              ;; from
              ;; :to-code to
              ;; :owner #t)
               )
          (out (open-output-conversion-port
                (cond ;;(command
                     ;; (open-output-process-port command))
                     ((equal? out-file "-")
                      (current-output-port))
                     (else
                      (open-ouput-file out-file)))
                from
                :to-code to
                :owner #t
                ))
          (fp #f))
      (when command
        (let* ((p (apply run-process
                        (append (string-tokenize command)
                                '(:input :pipe :output :pipe))))
               (p-out (process-output p)))
          (set! (port-buffering p-out) :none)
          (set! out (process-input p))
          (set! (port-buffering out) :none)
          (set! fp (open-input-conversion-port
                    p-out
                    from
                    :to-code to
                    ;;:owner #t
                    ))))
      (let loop ((line (and (char-ready? in) (read-char in))))
        (unless (eof-object? line)
          (when line
            (display line out)
            (flush out))
          (when fp
            (while (char-ready? fp)
              (let ((line (read-char fp)))
                (display line)
                (flush))))
          (sys-nanosleep 50000000)
          (loop (and (char-ready? in) (read-char in)))))))
  (newline))
