; Finish up the troff pass 1 file by making each line into a troff string def
; of the form
;
;     .ds <full section title> <section number>
;
; where the full section title is the full section title with underscores
; instead of spaces so as to be a legal troff string name.
;
; It is worth noting that this file has been the site of a couple nastly little
; bugs, as described in the comments below.  What can I say?  "F--- me" might
; do nicely.
;

(defun dot () (point))

(defun finish-up-troff-pass1-file ()
"Finish up the troff pass 1 file by making each line into a troff string def
of the form

     .ds <full section title> <section number>

where the full section title is the full section title with underscores
instead of spaces so as to be a legal troff string name."
    (finish-up-troff-pass1-file-1)
    (save-buffer)
)

(defun finish-up-troff-pass1-file-1 ()
"Work doer for finish-up-troff-pass1-file."
  (interactive)
  (replace-string "\\&" "")
  (beginning-of-buffer)
  (while (not (eobp))
    (insert-string ".ds ")
    (setq d (dot))
    (search-forward "'" nil t)
    (backward-delete-char 1)
    (narrow-to-region d (dot))
    (beginning-of-line)
    (replace-string " " "_")

    ; Nasty little bug #1 was having the next line be forward-word 1 instead of
    ; end-of-line, which caused some kind of mess up that I can't fully
    ; remember the details of, but it was something about having some
    ; "abnormal" chars in a section name or caption that caused the .ds to have
    ; the wrong def.
    (end-of-line)
    (widen)
    (setq string-name (buffer-substring d (dot)))
    (forward-char 1)

    ; Nasty little bug #2 was fixed by adding the cond logic to check for
    ; "Appendix", since without it the fact that the appendix number follows
    ; the string "Appendix" caused the def of the string to be wrong, due to
    ; the search for the end of section number being based on the space char.  
    ; Hence, the section number for "Appendix A" would end up being "Appendix" 
    ; instead of "A".  What a sick hack this all is.
    ;
    ; And later, we added "Chapter ", but of course.  Hack, hack, hack, hack.
    (setq d (dot))
    (search-forward " ")
    (if (or (string= (buffer-substring d (dot)) "Appendix ")
	    (string= (buffer-substring d (dot)) "Chapter "))
      (progn
	(backward-kill-word 1)
	(search-forward " ")
      )
    )
    (backward-char 1)
    (newline)
    (insert-string (concat ".ds " string-name "_page"))
    (forward-line 1)
    (beginning-of-line)
  )
)