#!/bin/sh
# -*- scheme -*-
exec guile $0 $*
!#
;; Copyright (C) 2018,2020 Matthew R. Wette
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public License
;; along with this library; if not, see <http://www.gnu.org/licenses/>

(use-modules (nyacc lang mlang mltoc))
(use-modules (srfi srfi-37))

(define (fail fmt . args)
  (apply simple-format (current-error-port)
	 (string-append "mltoc: " fmt "\n")
	 args)
  (exit 1))

(define (show-usage)
  (simple-format #t "Usage: mltoc [OPTION] FILE ...
Convert a mlang dot-m file to c.
  -h, --help           print this help message

Report bugs to https://savannah.nongnu.org/projects/nyacc.\n"))

(define options
  (list
   (option '(#\h "help") #f #f
	   (lambda (opt name arg opts files)
	     (values (acons 'help #t opts) files)))
   (option '(#\g "gen") #t #f
	   (lambda (opt name arg opts files)
	     (values (acons 'gen arg opts) files)))
   ))

(define (parse-args args)
  (args-fold args options
	     (lambda (opt name arg files opts)
	       (fail "unrecognized option: ~S" name)
	       (exit 1))
	     (lambda (file opts files)
	       (if (string-suffix? file ".m")
		   (fail "expecting .m file"))
	       (values opts (cons file files)))
	     '() '()))

(define (do-this . args)
  (call-with-values
      (lambda () (parse-args args))
    (lambda (opts files)
      (when (or (assq-ref options 'help) (null? files)) (show-usage) (exit 0))
      (for-each (lambda (file) (mlang-to-c99 file opts)) files)))
  0)

(apply do-this (cdr (program-arguments)))

;; --- last line ---
