(define-library (picrin main)
  (import (scheme base)
          (scheme read)
          (scheme write)
          (scheme process-context)
          (scheme load)
          (scheme eval)
          (picrin repl))

  (define (print-help)
    (display "picrin scheme\n")
    (display "\n")
    (display "Usage: picrin [options] [file]\n")
    (display "\n")
    (display "Options:\n")
    (display "  -e [program]		run one liner script\n")
    (display "  -l [file]		load the file then enter repl\n")
    (display "  -h or --help		show this help\n"))

  (define (getopt)
    (let ((args (cdr (command-line))))
      (if (null? args)
          (values 'repl #f)
          (case (string->symbol (car args))
            ((-h --help)
             (print-help)
             (exit 1))
            ((-e)
             (values 'line (cadr args)))
            ((-l)
             (values 'load (cadr args)))
            (else
             (values 'file (car args)))))))

  (define (exec-file filename)
    (load filename))

  (define (exec-line str)
    (call-with-port (open-input-string str)
      (lambda (in)
        (let loop ((expr (read in)))
          (unless (eof-object? expr)
            (eval expr '(picrin user))
            (loop (read in)))))))

  (define (main)
    (call-with-values getopt
      (lambda (type dat)
        (case type
          ((repl) (repl))
          ((load) (load dat) (repl))
          ((line) (exec-line dat))
          ((file) (exec-file dat))))))

  (export main))