#!/usr/local/bin/gosh

(use gauche.parseopt)

(define-constant ANSI_ESCAPE_BG_COLOR_BASE 40)

(define (ansi-escape str color-num)
  (apply string-append
         (map (apply$ string)
              (list `(#\escape #\[ ,@(string->list (x->string color-num)) #\m)
                    (string->list str)
                    `(#\escape #\[ ,@'(#\0) #\m)))))

(define (draw ls)
  (for-each
   (^l (for-each
        (^x (if-let1 n (string->number x)
                     (display (ansi-escape " " (+ n ANSI_ESCAPE_BG_COLOR_BASE)))
                     (display " ")))
        l)
       (print))
   ls))

(define (usage cmd)
  (print "usage: " cmd " file1.dat file2.dat ... filen.dat")
  (print "exapmle: % echo \'0123 4567\' | " cmd)
  (print (draw '(("0" "1" "2" "3" " " "4" "5" "6" "7"))))
  (exit))

(define (input->list)
  (define (line->list val)
    (map string (string->list val)))
  (let rec ((acc '()))
    (let1 val (read-line)
      (if (eof-object? val)
          (reverse acc)
          (rec (cons (line->list val) acc))))))

(define (list->double ls)
  (fold-right (^ (x acc)
                 (cons x (cons x acc)))
              '()
              ls))

(define (main args)
  (let-args (cdr args)
      ((help "h|help" => (cut usage (car args)))
       (else (opt . _)
             (print "Unknown option : " opt)
             (usage (car args)))
       . rest)
    (let1 data (if (null? rest)
                   (input->list)
                   (apply map (^ rows (apply append rows))
                          (map (cut with-input-from-file <> input->list)
                               rest)))
      (print (draw (map list->double data))))))