#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH

(setqn FF () F ()L ()S() F() D() B "")

;; Mon, 8 Aug 94 09:51:18 +0200  ==> Mon Aug 08 09:51:18 1994

(setq td-re (regcomp 
    "^Date:[ \t]*([a-zA-Z]*),? *([0-9]+) *([a-zA-Z]+) *([0-9]+) *([0-9:]+)"))
(setq re-time (regcomp "^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$"))
(setq td-last "Date: Mon, 01 Jan 00:00:00 1970")

(defun transforms-date (d &aux 
    res
  )
  (if (not d) (setq d td-last))
  (if 
    (regexec td-re d) (with (
	time (regsub td-re 5)
      )
      (setq res (+ (regsub td-re "\\1 \\3 \\2 \\5 ") 
	  (if (< (length (regsub td-re 4)) 4) "19" "") (regsub td-re 4)
      ))
      (if (not (regexec re-time time)) 
	(setq res (+ (regsub td-re "\\1 \\3 \\2 00:00:00 ") 
	    (if (< (length (regsub td-re 4)) 4) "19" "") (regsub td-re 4)
      )))
      ;; if daynum <10, add a 0
      (if (and (/= #\ (getn res 0)) (= #\  (getn res 9)))
	(insert res 8 #\0)
	(and (= #\ (getn res 0)) (= #\  (getn res 6)))
	(insert res 5 #\0)
      )
      
      (if (match "^[A-Z][a-z][a-z] [A-Z][a-z][a-z] [0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]$" res)
	(setq td-last res)

	(match "^ [A-Z][a-z][a-z] [0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]$" res)
	(setq td-last (setq res
	    (+ "Mon" res)
	))

	(progn (PF *standard-error* "ERROR! bad date format: %r0\n    (giving: %r1)\n" d res)
	  (setq res td-last)
	)
      )
    )
    (setq res td-last)
  )
  res
)

(while (setq line (read-line *standard-input* ()))
  (if
    (= "******************************************************************************" line)
    (when FF
      (PF "From %0 %5\n%1\n%2\n%3\n%4\n" FF S F 
	(if D D "")
	B (transforms-date D))
      (setqn FF () F ()L ()S() F() D() B "")
    )
    
    (regexec {regcomp "^Subject:"} line)
    (if (/= B "") (setq B (+ B "\n" line)) (setq S line))
    
    (regexec {regcomp "^Date:"} line)
    (if (/= B "") (setq B (+ B "\n" line)) (setq D line))
    
    (regexec {regcomp "^From:"} line) 
    (if (/= B "")  (setq B (+ B "\n" line)) (progn
	(setq F line)
	(setq FF (match "^From: *(.*)$" line 1))
    ))
    
    (= line "")
    (if (and FF (/= B "\n"))
      (setq B (+ B "\n" line))
    )
    
    (if FF (setq B (+ B "\n" line)))
  )
)

(PF "From %0 %5\n%1\n%2\n%3\n%4\n" FF S F D B (transforms-date D))


    

;;; EMACS MODES
;;; Local Variables: ***
;;; mode:lisp ***
;;; End: ***
