(defun merge-me-toc ()
"Merge the auto-gen'd toc.me into the locale of the .toc command, if it is
present.  If .toc was found, save the buffer, otherwise do nothing.  To allow
postscript an html tocs to be in different locations, e.g., in a book before
and after the preface, resp., there may be separate troff vs html toc lcations,
designatied toc_html and toc_ps, resp.  In this case, the toc goes where the
.toc_me command appears."
    (interactive)
    (if (search-forward "\n.toc_me\n" nil t)
      (progn
	(merge-me-toc-1)
      )
      (progn
	(beginning-of-buffer)
	(if (search-forward "\n.toc\n" nil t)
	  (progn
	    (merge-me-toc-1)
	  )
        )
      )
    )
)

(defun merge-me-toc-1 ()
"Work doer for merge-me-toc."
    (previous-line 1)
    (beginning-of-line)
    (kill-line 1)

    ; There's some trickery here for books to do the right thing page
    ; numberingwise and front-and-back pagewise.  First, the code guarded by
    ; ".ie '\\nB'1' puts odd/even headers in for second and subsequent toc
    ; pages.  Second, the value of the last page of the toc is saved in the reg
    ; last_toc_page.  For an e.g. of how this is used, see ~/se-book/hdr.me.
    ;
    ; As of the latest hacking on this, I'm not sure that the last page number
    ; reg is necessary, but let's leave it and get on with life.
    ;
    (insert-string
      (concat
	".ie '\\nB'1' \\{\\\n"
	".    of ''%''\n"
	".    fo ''''\n"
	".    he ''''\n"
	".    oh '''Contents \\ \\ %'\n"
	".    eh '% \\ \\ Contents'''\n"
	".\\}\n"
	".ep\n"
	".af % 1\n"
	".nr last_toc_page \\n%-1\n"
	".nr % 1\n"
	".fo ''''\n"
	".he '''Page %'\n"
	".fi\n"
	".ad\n"
      )
    )

    ; The next line is the sweet little hack that moves back to just before the
    ; .ep, but after the odd/even header settings.  This means that the toc is
    ; stuck in just the right place.  How nice.
    ;
    (previous-line 8)

    ; OK, now we finally do the sticking.  The kill-line call gets rid of
    ; top-level troff commands that stdhdr.me puts in the toc file to make it
    ; a stand-alone document if we want to look at it that way.
    ;
    (insert-file "toc.me")
    (kill-line 3)
    (save-buffer)

    ; Stick in the list of figures and list of tables files, if they exist.
    (if (file-exists-p "lof-raw.me")
	(insert ".bp\n")
        (insert-file "lof-raw.me")
        (kill-line 3)
    )
    (if (file-exists-p "lot-raw.me")
	(insert ".bp\n")
        (insert-file "lot-raw.me")
        (kill-line 3)
    )

)