#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH

(setq args (getopts 
"USAGE: gnews [options] pattern files-or-dirs
does a grep in newsgroup.
if no pattern given, list from result of grep in stdin"
))

(setq pattern (getn args 0))
(setq files (subseq args 1))

(defun main ()
  (if pattern
    (do-gnews-on-files)
    (do-gnews-on-stdin)
))

(defun do-gnews-on-stdin (&aux
    (re (regcomp "^([^: ]+):(.*)$"))
    line
    (files (list))			;plist name count
    file
    s
    fd
  )
  (while (setq line (read-line *standard-input* ()))
    (if (regexec re line) (progn
	(setq file (regsub re 1))
	(put files file (+ 1 (get files file 0)))
  )))
  (dohash (file n files)
    (setq s (print-format String "%0 match%1 in %2:"
	n (if (> n 1) "es" "")  file
    ))
    (print-format "\n%0 %1\n" (make-string (- 78 (length s)) #\*) s)
    (if (setq fd (open file :error ()))
      (print-news fd *standard-output*)
      (print-format "##### file \"%0\" not found !!! #####\n" file)
    )
  )
)

(defun print-news (fd out &aux
    line
    (re-header (regcomp "^([^:]+):"))
    (in-header t)
    s
    (allowed-headers '("Newsgroups" "From" "Subject" "Organization" "Date"))
  )
  (while (and in-header (setq line (read-line fd ())))
    (if (and (regexec re-header line)
	(seek allowed-headers (regsub re-header 1))
      )
      (write-line line out)
      (= "" line)
      (progn   (write-line "" out) (setq in-header ()))
  ))
  (print-format out "%0" (setq s (String fd)))
  (flush out)
)

(defun do-gnews-on-files (&aux
  )
  (error "gnews on files not yet implemented!")
)


(main)


;;; EMACS MODES
;;; Local Variables: ***
;;; mode:lisp ***
;;; End: ***

	
