(defun dot () (point))

(defun mh-folder-to-apple-mbox ()
"Given a file named ``all'', consisting of the ordered concatenation of all the
files in an mh folder, convert it to a format suitable for reading with MacOS
Mail.  The conversion, luckily, is straightforward, entailing the change of two
lines at the top of each message.  See the code for details.

This emacs script is run from the companion csh script
./mh-folder-to-apple-mbox.csh, which creates the ``all'' file and then runs
this script via emacs -batch."

    (interactive)
    
    ; Open the "all" file.
    (find-file "all")

    ; Confirm that it's the expected format by checking the first line starts
    ; with "Return-Path:"
    (setq d (dot))
    (forward-word 2)
    (forward-char 1)
    (setq s (buffer-substring d (dot)))
    (if (not (string= s "Return-Path:"))
	(error "You're not in the right kind of file.")
    )

    ; For the first line, replace "Return-Path:" with "From", delete
    ; "Delivery-Date:" from the beginning of the second line, and merge the
    ; first and second lines into one line.  The reason for the non-uniform
    ; treatment of the first vs the rest of the lines is that at the top of the
    ; file, there is no blank line, whereas there is a blank line in front of
    ; all the remaining message headers.
    (beginning-of-buffer)
    (kill-word 2)
    (delete-char 1)
    (insert "From")
    (end-of-line)
    (kill-word 2)
    (delete-char 1)

    ; Cruise the rest of the file looking for "Return-Path:" at the beginning
    ; of the line, followed by "Delivery-Date:" at the beginning of the next
    ; line.  The reason for the double-line search is to be more certain not to
    ; find message-body content rather than the beginning-of-message delimiter.
    ; Once found, do the same change as to the first two lines, but leave a
    ; blank line in front of the resulting merged line.
    (while (search-forward-regexp "^Return-Path:.*\nDelivery-Date:" nil t)
        (previous-line 1)
	(beginning-of-line)
	(kill-word 2)
	(delete-char 1)
	(insert "From")
	(end-of-line)
	(kill-word 2)
	(delete-char 1)
	(beginning-of-line)
	(open-line 1)
    )

    ; Stick a blank line at the end of the file and save the puppy.
    (end-of-buffer)
    (newline 1)
    (save-buffer)

)