
(defun igc-parse-one (x) 
  (if (string-match "^.\\(..\\).\\(..\\)   \\(..\\) \\([^ ]+\\) +\\([^ ]+\\) +\\([^ ]+\\)" x)
      (list (substring x (match-beginning 1) (match-end 1))
	    (substring x (match-beginning 2) (match-end 2))
	    (substring x (match-beginning 3) (match-end 3))
	    (substring x (match-beginning 4) (match-end 4))
	    (substring x (match-beginning 5) (match-end 5))
	    (substring x (match-beginning 6) (match-end 6))
	    x)))

(defun igc-parse-text (text)
  (let ((result nil))
    (while (string-match "\\(.+\\) | \\([^\C-m\C-j]+\\)\C-m?\C-j" text)
      (let ((first (substring text (match-beginning 1) (match-end 1)))
	    (second (substring text (match-beginning 2) (match-end 2)))
	    (rest (substring text (match-end 0))))
	(setq text rest)
	(setq result (cons (igc-parse-one first) (cons (igc-parse-one second) result)))))
    result))

(defun igc-rate (opponent)
  (if opponent
      (let ((flags (nth 0 opponent))
	    (observing (nth 1 opponent))
	    (playing (nth 2 opponent))
	    (username (nth 3 opponent))
	    (idle (nth 4 opponent))
	    (rank (nth 5 opponent)))
	(if (or
	     (string-match "X" flags)
	     (string-match "[0-9]" playing)
	     (string-match "h" idle)
	     (string-match "d" rank))
	    0
	  (let ((r 100))
	    (if (string-match "!" flags) (setq r (+ r 100)))
	    r)))
    0))

(defun igc-unparse (opponent)
  (nth 6 opponent))

(defun igc-hunt (start end)
  (interactive "r")
  (let ((b (get-buffer-create "*igc*"))
	(l (igc-parse-text (buffer-substring start end))))
    (set-buffer b)
    (erase-buffer)
    (while l
      (let ((r (igc-rate (car l))))
	(if (> r 0)
	    (insert (format "%03d    %s\n"
			    (igc-rate (car l))
			    (igc-unparse (car l)))))
	)
      (setq l (cdr l)))
    (sort-lines t (point-min) (point-max))
    (display-buffer b)))

