#!/usr/bin/perl

# fix-outlook-quoting.pl

# Author:  Kevin D. Clark (alumni.unh.edu!kdc)


# This program will take a region of text that looks like this....:

# > Kevin ,
# >
# > Blah blah blah blah blah bla.
# >
# > Ralph
# > 
# > 		 -----Original Message-----
# > 		From: 	Clark, Kevin
# > 		Sent:	Thursday, January 03, 2002 8:18 AM
# > 		To:	A bunch of people
# > 		Cc:	A bunch of other people
# > 		Subject: life, the universe, and everything
# > 
# > 		Ralph,
# > 
# >     Mumble mumble mumble mumble.
# > 
# > 		Kevin

# (you'd end up with such a region of text if your mail program quoted 
#  email in the cannonical way, and you had to deal with brain-dead
#  email clients like Outlook)

# ....and transforms this into this:

# > Clark, Kevin writes:
# > > Ralph,
# > > 
# > > Mumble mumble mumble mumble.
# > > 
# > > Kevin
# 
# > Kevin ,
# >
# > Blah blah blah blah blah bla.
# >
# > Ralph
# > 
# `


# this program is also general enough to handle a whole thread of the 
# braindead outlook quoting style.  After this transmorgification is performed,
# it's simple enough to edit the resulting text to actually look decent.


# If you use emacs as your editor and you've yanked the mangled message into
# your reply buffer, some variant of:
#
#   C-u M-| fix-outlook-quoting.pl
#
# will suffice.

# If you use vi as your editor, some variant of:
#
# ma  (move to end of mangled text)
# :'a,.!fix-outlook-quoting.pl
#
# might work.



# Version history:
#
# 0.1 - initial version
# 0.2 - renamed original identifiers to be less offensive


undef $/;

$_ = <>;

($firstPart, $screwed) = /(.*?)(>\s*---*Original Message---*.*)/s;

# print ":$firstPart:\n";

$screwed =~ s/^[> \t]*//mg;

@screwedList = split(/---*Original Message---*/, $screwed);

# the first item in the list is screwed, er, I mean, blank...
shift @screwedList;


$i = 1;
for $f (@screwedList) {

  ($from) = $f =~ /From:\s+(.*?)\s*$/m;

  print "> " x $i++;
  print "$from writes:\n";
}

$i = scalar(@screwedList) + 1;
for $f (reverse(@screwedList)) {

  # delete first "paragraph" of screwed "headers"
  $f =~ s/.*?\n\s*\n//s;

  # quote properly
  $quotes = "> " x $i--;

  $f =~ s/^/${quotes}/mg;

  print "$f\n";
}

print "$firstPart\n";
