;; (c--delete-current-line-as-string)
(defun c--delete-current-line-as-string ()
  (let* ((min (save-excursion (beginning-of-line) (point)))
         (max (save-excursion (end-of-line) (point)))
         (result (buffer-substring-no-properties min max)))
    (delete-region min (1+ max))
    result))

;; (setq list (c--get-lines))
(defun c--get-lines ()
  (let ((list nil) (i 0))
    (goto-char (point-min))
    ;;(re-search-forward "^#include .*\\.hh" nil t)
    ;;(beginning-of-line)
    ;;(setq list (cons (c--delete-current-line-as-string) list))
    (while (re-search-forward "^#include \".*\\.hh\"" nil t)
      (setq list (cons (c--delete-current-line-as-string) list)))
    (reverse list)))

;; (setq list '(1 2 3))
;; (add-to-list 'list 4 'END)
;; (c--get-ancestors)
(defun c--get-ancestors ()
  (let (ptr ptr2 parent pparent-list)
    (setq ptr direct-parent-class)
    (setq ptr2 (cdar ptr))
    (while ptr2
      (setq parent (car ptr2))
      (setq pparent-list (cdr (assq parent direct-parent-class)))
      (while pparent-list
        (setcdr (last ptr2) (cons (car pparent-list) nil))
        (setq pparent-list (cdr pparent-list)))
      (setq ptr2 (cdr ptr2)))
    )
  )

;;(stable-sort list 'c-pred)
;; (setq x "#include \"Banana.hh\"")
;; (setq x "#include <iostream>")
(defun c--pred (x y)
  (let (class-x class-y)
    (assert (string-match "\"\\(.*\\)\\.hh\"" x))
    (setq class-x (read (substring x (match-beginning 1) (match-end 1))))
    (assert (string-match "\"\\(.*\\)\\.hh\"" y))
    (setq class-y (read (substring y (match-beginning 1) (match-end 1))))
    ;;(debug)
    (cond 
     ((memq class-y (cdr (assq class-x direct-parent-class)))
      t)
     ((memq class-x (cdr (assq class-y direct-parent-class)))
      nil)
     (t nil))))

;; (c--put-lines list)
(defun c--put-lines (list)
  (let ((ptr list))
    (while ptr
      (insert (car ptr) "\n")
      (setq ptr (cdr ptr))))
  )

      ;;      (c--get-ancestors)
      ;;      (let (lines)
      ;;        (save-excursion
      ;;          (find-file global-cc)
      ;;          (setq lines (c--get-lines))
      ;;          ;;(setq lines '("#include \"Apple.hh\" "#include \"Base.hh\"" "#include \"Zippy.hh\"" "#include \"../2006/libd/global.hh"))
      ;;          (setq lines (sort lines 'string<))
      ;;          (setq lines (stable-sort lines 'c--pred))
      ;;          (setq lines (reverse lines))
      ;;          (c--put-lines lines)
      ;;          (save-buffer))
      ;;        (checkpoint 1.6)
