;; #!/bin/bash

(module extract
	*

(import  scheme
	 chicken)

(use	 srfi-1
	 srfi-69
	 extras
	 posix
	 regex
	 matchable
	 data-structures
	 )

(define (get-norefs)
  (let* ((indat (with-input-from-pipe
		 "grep 'Warning: refer' typescript"
		 read-lines)))
    (filter string?
	    (map (lambda (instr)
		   (match (string-search "`(\\S+)'" instr)
			  ((full thematch) thematch)
			  (else #f)))
		 indat))))

(define (get-parent-files noref)
  (let ((scmfiles (with-input-from-pipe
		   "ls *scm|grep -v import"
		   read-lines))
	(resultht (make-hash-table)))
    (for-each
     (lambda (scmfile)
       (let ((lines (with-input-from-pipe
		     (conc "grep '"noref"' "scmfile"|egrep '^.define'")
		     read-lines)))
	 (if (not (null? lines))
	     (hash-table-set! resultht scmfile #t))))
     scmfiles)
    (hash-table-keys resultht)))

(define (main)
  (let ((data (make-hash-table))
	(fns  (get-norefs)))
    (for-each
     (lambda (fn)
       (let ((parents (get-parent-files fn)))
	 ;; (print fn": "parents)
	 (for-each
	  (lambda (parent)
	    (hash-table-set! data parent (cons fn (hash-table-ref/default data parent '()))))
	  parents)))
     fns)
    (for-each
     (lambda (f)
       (let ((fns (hash-table-ref data f)))
	 (print "\n"f)
	 (map print fns)))
     (hash-table-keys data))))

(main)
)

;; 
;; LAST_PARENT=foobar
;; 
;; for fn in $(grep 'Warning: refer' typescript |tr '`' ' '|tr "'" " "|awk '{print $7}');do
;;     PARENT=$(grep $fn *mod.scm|grep define|cut -d: -f1)
;;     if [[ $PARENT != $LAST_PARENT ]];then
;; 	echo
;; 	echo $PARENT
;; 	LAST_PARENT=$PARENT
;;     fi
;;     echo $fn
;; done
;; 
