#!/usr/bin/perl
# read and parse unix mailboxes and write a temp file.

use File::Find;
use MIME::Base64;
use MIME::QuotedPrint;
use Encode;

$plPath = shift;
$logPath = shift;
$allmbState = shift;
$attachState = shift;
$htmlState = shift;
$trashState = shift;
$mboxState = shift;
$origState = shift;
$largeAttachState = shift;
$attachSize = shift;
$mailboxesState = shift;
$parseFolderState = shift;
$beginDate = shift;
$endDate = shift;
$attachSize = $attachSize * 1000000.0;
$beginDate =~ /(\d+)-(\d+)-(\d+)/;
$beginYr = $1; $beginMo = $2; $beginDa = $3;
$endDate =~ /(\d+)-(\d+)-(\d+)/;
$endYr = $1; $endMo = $2; $endDa = $3;
$stuffitCount = 0;
$numFolders = 0;
$saveFilePath = "";
undef @attachTypes;
undef @attachFilenames;
undef @attachBlobs;
undef @attachEncodings;
undef @attachCharsets;
undef @directories;
undef @accounts;
undef %options;
$attachCount = $chunkCount = 0;
%months = (
    "jan","01",
    "feb","02",
    "mar","03",
    "apr","04",
    "may","05",
    "jun","06",
    "jul","07",
    "aug","08",
    "sep","09",
    "oct","10",
    "nov","11",
    "dec","12"
    );

open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!\n";
$| = 1;
open ( LOGTMPFILE, ">>$logPath" ) || print STDERR "problem opening $logPath\n";
$temppath = $logPath;
$temppath =~ s/\.log$/\.tmp/;
$rawtemppath = $logPath;
$rawtemppath =~ s/\.log$/\.raw/;
if ( $mailboxesState ) {
    $mboxState = 0;
    $allmbState = 1;
    $trashState = 1;
}

if ( $mboxState ) {
    $allmbState = 1;
    $trashState = 1;
    while ( $filePath = shift ) {
        if ( (-d "$filePath") ) {
	    chomp($filePath);
	    push @accounts, $filePath;
	    $numFolders++;
	} else {
	    if ( $filePath =~ /\/\d+\.[\d\.]+$/ ) { next; }
	    $origBlob = "RAW:\n";

	    $mailbox = $filePath;
	    $mailbox =~ s/^.+\/([^\/]+)$/$1/;
	    $saveFilePath = $filePath;
	    if ( !(open ( INFILE, "<$filePath" )) ) {
		print STDERR "problem opening $filePath\n";
	    } else {
		if ( !(-T INFILE) ) {
		    close INFILE;
		    next;
		}
		read( INFILE,$buf,1000 );
		if ( $buf =~ /\r/ && $buf !~ /[^\r]+\n/ ) {
		    $/ = "\r";
		} else { $/ = "\n"; }
		close INFILE;
		if ( !(open ( INFILE, "<$filePath" )) ) { print STDERR "problem opening $filePath\n"; }
		if ( !(open ( INFILE2, "<$filePath" )) ) { print STDERR "problem opening 2 $filePath\n"; }
	    }
	    $file = $filePath;
	    $file =~ s/\/([^\/]+)$/$1/;
	    chomp($file);
	    &parseIt;
	    close INFILE;
	    close INFILE2;
	}
    }
    if ( $numFolders ) {
	$options{'wanted'} = \&wanted;
	$options{'no_chdir'} = 1;
	find(\%options, @accounts);
	foreach $dir (@directories) {
	    &doDirectory ($dir);
	}
    }
} else {
    while ( $account = shift ) {
	chomp($account);
        push @accounts, $account;
    }
    $options{'wanted'} = \&wanted;
    $options{'no_chdir'} = 1;
    find(\%options, @accounts);
    foreach $dir (@directories) {
        &doDirectory ($dir);
    }
}
syswrite(LOGTMPFILE,"PARSED:$stuffitCount\n",8+length($stuffitCount));
if ( $stuffitCount ) { &waitForSignal; }
close LOGTMPFILE;
close TMPFILE;
close RAWTMPFILE;
#close STDOUT;
close STDERR;
exit;

sub wanted {
    local($file) = $File::Find::name;
    if ( !$mailboxesState ) {
	if ( $file =~ /Delivered|Drafts|Outbox/i ) { return; }
	if ( !$trashState && $file =~ /Deleted|Junk|Trash|Spam/i ) { return; }
    }
#    $file = s/^.+\/([^\/]+)$/$1/;
    if ( $file =~ /^\./ ) { return; }
    if ( (-d $File::Find::name) ) {
        push @directories, $File::Find::name;
    }
}

sub doDirectory {
    local($targetdir) = @_;
    local(@files);
    opendir(NEXTDIR, "$targetdir") || print STDERR "doDirectory: problem opening $targetdir\n";
    @files = readdir(NEXTDIR);
    closedir NEXTDIR;
    foreach $file ( @files ) {
        if ( $file =~ /^\./ ) { next; }
        if ( (-d "$targetdir/$file") ) {
            next;
        }
        $filePath = "$targetdir/$file";
	if ( !$allmbState && $filePath =~ /Mailboxes/i && $filePath !~ /Sent/i ) { next; }
	if ( !$allmbState && $filePath !~ /INBOX/i && $filePath !~ /Sent/i && $filePath !~ /Deleted/i && $filePath !~ /Junk/i && $filePath !~ /Trash/i && $filePath !~ /Spam/i ) { next; }
	if ( $filePath =~ /Sent/i && !$allmbState ) {
	    $sentOK = 0;
	    foreach $myaccount (@accounts) {
		$myaccount =~ s/Mac-//;
		if ( $myaccount eq 'Mailboxes' ) { next; }
		$myaccount =~ s/\+/\./g;
		$myaccount =~ s/\$/\./g;
		if ( $filePath =~ /$myaccount/ ) {
		    $sentOK = 1;
		    last;
		}
	    }
	    if ( !$sentOK ) { next; }
	}
        if ( !$mboxState && $file ne 'mbox' && $file !~ /^\d+$/ && $file !~ /\.partial.*$/ && $file !~ /\.emlx$/ ) { next; }
	$saveFilePath = $filePath;
	if ( $mboxState ) {
	    $origBlob = "RAW:\n";
	    if ( !(open ( INFILE, "<$filePath" )) ) { print STDERR "problem opening $filePath\n"; } else {
		read( INFILE,$buf,1000 );
		if ( $buf =~ /\r/ && $buf !~ /\n/ ) {
		    $/ = "\r";
		} else { $/ = "\n"; }
		close INFILE;
		if ( !(open ( INFILE, "<$filePath" )) ) { print STDERR "problem opening $filePath\n"; }
		if ( !(open ( INFILE2, "<$filePath" )) ) { print STDERR "problem opening 2 $filePath\n"; }
	    }
	} else {
	    if ( !(open ( INFILE, "<$filePath" )) ) { print STDERR "problem opening $filePath\n"; }
	    if ( !(open ( INFILE2, "<$filePath" )) ) { print STDERR "problem opening 2 $filePath\n"; }
	    if ( $origState ) {
		if ( $file =~ /^\d+$/ || $file =~ /\.emlx$/ ) {
		    $origBlob = "RAW:\n";
		}
	    }
	}

	if ( $mboxState ) {
	    $mailbox = "$file";
	} else {
	    $mailbox = $targetdir;
	    $mailbox =~ s/\/CachedMessages//;
	    $mailbox =~ s/\/Messages//;
	    $mailbox =~ s/^.*\/([^\/]+\/[^\/]+)$/$1/;
	    $mailbox =~ s/\.mbox$//;
	    $mailbox =~ s/\.imapmbox$//;
	    $mailbox =~ s/^POP-//;
	}
        &parseIt;
        close INFILE;
        close INFILE2;
	if ( $parseFolderState ) {
	    unlink($filePath);
	}
    }
}

sub invalidFile {
    syswrite(LOGTMPFILE,"INVALID: $filePath is not a valid email file.\n",37+length($filePath));
    return;
}

sub parseIt {
    if ( !(-T INFILE) ) {
	&invalidFile;
	return;
    }
    syswrite(LOGTMPFILE,"$filePath\n",1+length($filePath));
    $body=$mday=$month=$year=$received=$addr=$addr2=$CC=$TO=$subject=$encoding=$boundary=$disposition=$charset=$content=$filename=$saveOrigBlob=$tagNotes=$tagKeywords=$tagCategory=$tagPriority=$digest="";
    $firstTime = 1;
#    $content = "text/plain";
    undef @boundarys;
    $attachCount = $chunkCount = 0;
    undef @chunkFiles;
    if ( $filePath =~ /\.partial.*$/ ) { &doChunkFiles; }
    while ( &readLine ) {
DOIT:
	if ( /^Attachment converted:[^:]+:([^\(]+)\(([^\/]+)\//i ||
#X-Attachments: :Fantom250:265923:redbldg.jpg:
#Attachment converted: Fantom250:redbldg.jpg (JPEG/ÇICÈ) (001051C3)
	     /X-Attachments:[^:]+:[^:]+:[^:]+:([^:]+):([^:]*)/i ) {
	    $eudoraFilename = $1;
	    $eudoraContent = lc $2;
	    chomp($eudoraFilename);
	    $eudoraFilename =~ s/\s+$//;
	    if ( $filePath !~ /eudora/i ) { next; }
	    &doEudoraAttachment;
	    $filename = $content = "";
	    if ( !eof(INFILE) ) { next; }
	    else { $_ = ""; }
	}
	if ( /^\<x-html\>/i ) {
	    $blob = "";
	    $blob .= $_;
	    if ( !/\<\/x-html\>/i ) {
		while ( &readLine && !eof(INFILE) ) {
		    $blob .= $_;
		    if ( /\<\/x-html\>/i ) { last; }
		}
	    }
#	    s/\<\/x-html\>//;
	    $attachTypes[$attachCount] = 'text/html';
	    $attachFilenames[$attachCount] = "attachment".$attachCount.".html";
	    $attachEncodings[$attachCount] = "";
	    $attachCharsets[$attachCount] = "";
	    $attachBlobs[$attachCount] = $blob;
	    $attachCount++;
	    $blob = "";
	    $filename = $content = "";
	    if ( !eof(INFILE) ) { next; }
	}
	if ( /^Related:/ ) { next; }
        if ( eof(INFILE) ) {
	    if ( $saveOrigBlob ne "" ) {
#            if ( $addr ne "" ) {
		$body .= $_;
		$saveFromDate = $fromDate;
                &stuffIt;
            }
            last;
        }
	if ( $year && $mday && $month ) {
	    if ( $month < 1 || $month > 12 ) {
		$month =~ s/(...).*/$1/;
		$month = $months{lc $month};
	    }
	    while (length($month) < 2) { $month = '0' . $month; }
	    while (length($mday) < 2) { $mday = '0' . $mday; }
	    if ( $year < 200 ) { $year += 1900; }
	    if ( $year < 1920 ) { $year += 100; }
	    $date = $year . "-$month" . "-$mday 00:00:00";
	    if ( $date lt $beginDate || $date gt $endDate ) {
		if ( $foundOne ) {
		    $foundOne = 0;
		    syswrite (STDOUT,"Looking for email",17);
		}
		if ( $file =~ /\.emlx$/ ) { last; }
		while ( !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE) ) {
		    &readLine;
		}
                $body=$mday=$month=$year=$received=$addr=$addr2=$CC=$TO=$subject=$encoding=$boundary=$disposition=$charset=$content=$filename=$saveOrigBlob=$tagNotes=$tagKeywords=$tagCategory=$tagPriority="";
#                $content = "text/plain";
                undef @boundarys;
                goto DOIT;
	    } else {
		$foundOne = 1;
	    }
	}
	if ( /^begin\s+\d+\s+[\S]+/ ) {
	    &doAttachment;
	    if ( eof(INFILE) ) { last; }
	    goto DOIT;
	}
        if ( /^Content-Transfer-Encoding: ([^\;]+)/i && ($encoding eq "" || $encoding eq "quoted-printable") ) {
	    $encoding = $1;
	    chomp($encoding);
	    next;
	}
	if ( /^Content-Disposition: ([^\;]+)/i ) {
            $disposition = $1;
            chomp($disposition);
	    if ( /filename=\s*([^\;]+)/i ) {
		$filename = $1;
		$filename =~ s/\"//g;
	    }
            next;
        }
        if ( /^Content-type:\s+/i ) {
	    &doContent;
	    if ( $content =~ /multipart/i ) {
		$content = $charset = $encoding = "";
	    }
	    goto DOIT;
	}
	if ( /^boundary=.+$/i && $body !~ /original message follows|-- Original Message --/i ) {
            &doBoundary;
            next;
        }
        if ( $boundary ne "" && &checkBoundary ) {
	    $content = $charset = $encoding = "";
            next;
        }
	if ( /^Date:/i && !$year ) {
	    $zone = "-0000";
	    if ( /^Date:\s*([A-Za-z]+),\s+([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
		$weekday = $1;
		$mday = $2;
		$month = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = $7;
		$zone = $8;
	    } elsif ( /^Date:\s*([A-Za-z]+),\s+([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)/i ) {
		$weekday = $1;
		$mday = $2;
		$month = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = $7;
	    } elsif ( /^Date:\s*([A-Za-z]+),\s+([A-Za-z]+)\s+(\d+),\s+(\d+)\s+(\d+):(\d+)/i ) {
#Date: Monday, July 31, 2000 11:37 AM
		$weekday = $1;
		$month = $2;
		$mday = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = '00';
	    } elsif ( /^Date:\s*([A-Za-z]+),\s+([A-Za-z]+)\s+(\d+)\s+(\d+)\s+(\d+):(\d+):(\d+)/i ) {
#Date: Mon, Jul 26 2004 03:27:10 +0000
		$weekday = $1;
		$month = $2;
		$mday = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = $7;
	    } elsif ( /^Date:\s*([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)/i ) {
		$weekday = "";
		$mday = $1;
		$month = $2;
		$year = $3;
		$hours = $4;
		$min = $5;
		$sec = $6;
	    } elsif ( /^Date:\s*([A-Za-z]+),\s+([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+)/i ) {
		$weekday = $1;
		$mday = $2;
		$month = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = '00';
	    } elsif ( /^Date:\s*([A-Za-z]+)\s+(\d+),\s+(\d+)\s+(\d+):(\d+):(\d+)/i ) {
		$weekday = "";
		$month = $1;
		$mday = $2;
		$year = $3;
		$hours = $4;
		$min = $5;
		$sec = $6;
		$month =~ s/^(...).+$/$1/;
	    } elsif ( /^Date:\s*([A-Za-z]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+[A-Z]*\s*(\d+)/i ) {
#	Date: Thu Sep 01 10:30:47 PDT 2005
#Date:        Tue Feb 23 15:26:42 1999
		$weekday = $1;
		$month = $2;
		$mday = $3;
		$hours = $4;
		$min = $5;
		$sec = $6;
		$year = $7;
	    } elsif ( /^Date:\s*(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/i ) {
# Date: 12/2/2004 8:44:37 AM
		$month = $1;
		$mday = $2;
		$year = $3;
		$hours = $4;
		$min = $5;
		$sec = $6;
	    } elsif ( /^Date:\s*([A-Za-z]+)\s+(\d+),\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)/i ) {
# Date: SAT 03, SEP 2005 23:03:47
		$weekday = $1;
		$mday = $2;
		$month = $3;
		$year = $4;
		$hours = $5;
		$min = $6;
		$sec = $7;
	    } else {
		$year = 1900;
		$month = "Jan";
		$mday = $hours = $min = $sec = '00';
	    }
	} elsif ( /^Date:/i ) {
	    next;
	} elsif ( /filename=\s*([^\;]+)/i ) {
            $filename = $1;
            $filename =~ s/\"//g;
	    next;
	} elsif ( /^Subject:\s*(.+)$/i && !$subject ) {
            $subject = $1;
            chomp($subject);
	    $saveSubject = $subject;
	    &readLine;
            while ( $_ =~ /^\s+([^\s].+)$/  && !eof(INFILE) ) {
		$junk = $1;
		$subject .= " $junk";
		chomp($subject);
		&readLine;
	    }
	    goto DOIT;
	} elsif ( /^From:/i && !$addr ) {
	    if ( /^From:\s*[^<>]+\s*<([^<>]+)>/i ) {
		$mailto = $1;
		$mailto =~ s/\"//g;
		$mailto =~ s/\s+$//;
		chomp ( $mailto );
	    } elsif ( /^From:\s*([^\"<>]+)/i ) {
		$mailto = $1;
		chomp ( $mailto );
	    }
	    /^From:\s*(.+)$/i;
	    $addr = $1;
	    chomp($addr);
	    &readLine;
	    while ( $_ =~ /^\s+([^\s].+)$/  && !eof(INFILE) ) {
		$addr .= $_;
		chomp($addr);
		&readLine;
	    }
	    goto DOIT;
	} elsif ( /^To:\s*(.+)$/i && $TO eq "" ) {
	    $TO = ",$1";
	    chomp($TO);
	    &readLine;
	    #while ( $_ =~ /\@/  && !/^[\S]+:/ && !eof(INFILE) ) {
	    while ( !/^[\S]+:/ && !/^\s*$/ && !eof(INFILE) ) {
		$_ =~ s/\n/,/;
		$TO .= "$_";
		chomp($TO);
		&readLine;
	    }
	    $TO =~ s/,,/,/g;
	    $TO =~ s/,$//;
	    goto DOIT;
	} elsif ( /^CC:\s*(.+)$/i && $CC eq "" ) {
	    $CC = ",$1";
	    chomp($CC);
	    &readLine;
	    while ( $_ =~ /\@/ && !/^[\S]+:/ && !eof(INFILE) ) {
		$_ =~ s/\n/,/;
		$CC .= "$_";
		chomp($CC);
		&readLine;
	    }
	    $CC =~ s/,,/,/g;
	    $CC =~ s/,$//;
	    goto DOIT;
	} elsif ( /^Received:\s*(.+)$/i && !$year ) {
	    $received = $1;
	    chomp($received);
	    &readLine;
	    while ( /^\s+/  && !eof(INFILE) ) {
		chomp($_);
		$received .= $_;
		&readLine;
	    }
	    if ( !$year ) { &getDate; }
	    goto DOIT;
	} elsif ( /^\S+:/ && !/^http:/ && $body =~ /^\s*$/ ) {
	    &readLine;
	    while ( /^\s+\S+/ && !eof(INFILE) ) {
		if ( /filename=\s*([^\;]+)/i ) {
		    $filename = $1;
		    $filename =~ s/\"//g;
		}
		&readLine;
	    }
	    goto DOIT;
	} elsif ( /^X-.+:/ ) { next; }
	elsif ( /^charset=([^\;]+)/i && !/\>/ ) {
	    $charset = $1;
	    $charset =~ s/\"//g;
	    chomp($charset);
	    if ( $charset =~ /^NULL$/ ) { $charset = ""; }
	    next;
	} elsif ( /\s+id\s\d/ ) { next; }
	elsif ( /^\d+\s*$/ && $body eq "" ) { next; }
	elsif ( /^\<\?xml / && $content !~ /html/ && $file =~ /\.emlx$/ ) {
	    $savexml = $_;
	    &readLine;
	    if ( /plist/ && /Apple/ ) {
		&getMailTags;
		while ( &readLine && !eof(INFILE) ) {
		    if ( /\<\/dict/ ) {
			&readLine;
			last;
		    }
		    if ( /^From\s/ && /\d\d:\d\d:\d\d/ ) {
			last;
		    }
		}
		$boundary = "";
	    } else {
		$body .= $savexml;
		$body .= $_;
	    }
	    next;
	} elsif ( /^\<x-flowed\>/i ) {
	    s/\<x-flowed\>//i;
	    $body .= $_;
	    while ( &readLine && !eof(INFILE) ) {
		$body .= $_;
		if ( /\<\/x-flowed\>/i ) { last; }
	    }
	    $body =~ s/\<\/x-flowed\>//i;
	    next;
	} elsif ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ ) {
	    $saveFromDate = $fromDate;
	    /^From\s+(.+)$/;
	    $fromDate = $1;
	    chomp($fromDate);
	    if ( !$firstTime ) {
		if ( !$savedBlob ) {
		    $saveOrigBlob = $origBlob;
		    $saveOrigBlob =~ s/From [^\n\r]+\d\d:\d\d:\d\d[^\n\r]*[\n\r]*$//i;
		    if ( $origBlob ne "RAW:\n" ) {
			$origBlob = "\nRAW:\n";
		    }
		    $origBlob .= $my_;
		}
		&stuffIt;
	    } else {
		$saveFromDate = $fromDate;
		$firstTime = 0;
	    }
	    while ( &readLine && !eof(INFILE) ) {
		if ( !/^[\S]+:/ ) { next; }
		$body=$mday=$month=$year=$received=$addr=$addr2=$CC=$TO=$subject=$encoding=$boundary=$disposition=$charset=$content=$filename=$saveOrigBlob=$tagNotes=$tagKeywords=$tagCategory=$tagPriority="";
#		$content = "text/plain";
		undef @boundarys;
		goto DOIT;
	    }
	} else {
	    if ( ($content =~ /text\/plain/i || $content eq "") && $file !~ /\.emlx$/ && $year && $subject && $addr && $addr2 && $boundary eq "" && $encoding !~ /base64/i ) {
		$bodyencoding = $encoding;
		$bodycharset = $charset;
		$_ = &checkCoding($_);
		$body .= $_;
		while ( &readLine ) {
		    if ( /^From\s/ && /\d\d:\d\d:\d\d/ ) {
			goto DOIT;
		    }
		    $_ = &checkCoding($_);
		    $body .= $_;
		}
		goto DOIT;
	    }
	    if ( $body =~ /original message follows|--\s*Original Message\s*--/i && $file =~ /\.emlx$/ && $content =~ /text\/plain/i ) {
		$_ = &checkCoding($_);
		$body .= $_;
		while ( &readLine  && !eof(INFILE) ) {
		    if ( &checkBoundary || /^\<\?xml / ) {
			last;
		    }
		    $_ = &checkCoding($_);
		    $body .= $_;
		}
		goto DOIT;
	    }

	    if ( (($content =~ /text\/plain/i || $content eq "") && $disposition !~ /attachment|inline/i) || ($filePath =~ /Eudora/ && $mboxState) ) {
		if ( $year eq "" && $month eq "" && $mday eq "" && $subject eq "" && $addr eq "" && $addr2 eq "" && $body eq "" ) {
		    next;
		}
		$bodyencoding = $encoding;
 		$bodycharset = $charset;
		if ( /^content-.+:\s/i ) { next; }
		if ( $charset =~ /ISO-8859-1/i ) {
		    s/\=A0/\n/g;
		}
		$_ = &checkCoding($_);
		$body .= $_;
KEEPREADING:
		&readLine;
		if ( /^[\S]+:/ && !/^http:/ && $body =~ /^\s*$/ ) {
		    goto DOIT;
		}
		if ( !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE) && !(/^\<\?xml / && $file =~ /\.emlx$/) && $boundary eq "" ) {
		    $_ = &checkCoding($_);
		    $body .= $_;
		    goto KEEPREADING;
		} else {
		    goto DOIT;
		}
		next;
	    } elsif ( $content =~ /multipart|application\/applefile/i ) {
		next;
	    } else {
		if ( $attachState || $htmlState ) {
		    &doAttachment;
		    if ( eof(INFILE) ) { last; }
		    goto DOIT;
		}
		next;
	    }
	}
    }
    if ( !/<\/plist>/ ) {
	$_ = &checkCoding($_);
	$body .= $_;
    }
    if ( $saveOrigBlob ne "" ) { &stuffIt; }
    return;
}

sub checkCoding ($) {
    my $myString = shift;
    my $saveString = "";
    if ( $encoding eq "" ) {
	$encoding = "quoted-printable";
    }
    if ( $encoding =~ /quoted-printable/i ) {
	$myString =~ s/\=00//g;
	$saveString = $myString;
	eval ( '$myString = &decode_qp($myString);' );
	if ($@) {
	    print STDERR "eval error: $@\n";
	    $myString = $saveString;
	}
    } elsif ( $encoding =~ /base64/i ) {
	$myString = &decode_base64($myString);
    }
#    if ( Encode::resolve_alias("$charset") && $charset !~ /ascii/i ) {
    if ( Encode::resolve_alias("$charset") && $charset !~ /ascii|utf-8/i ) {
	$saveString = $myString;
	eval ( '$myString = Encode::decode("$charset",$myString);' );
	if ($@) {
	    print STDERR "eval error: $@\n";
	    $myString = $saveString;
	}
    }
    return $myString;
}

sub getDate {
    $zone = "-0000";
    if ( $received =~ /([A-Za-z]+),\s+([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
	$weekday = $1;
	$mday = $2;
	$month = $3;
	$year = $4;
	$hours = $5;
	$min = $6;
	$sec = $7;
	$zone = $8;
    } elsif ( $received =~ /^Date:\s*([A-Za-z]+),\s+([A-Za-z]+)\s+(\d+),\s+(\d+)\s+(\d+):(\d+)/i ) {
#Date: Monday, July 31, 2000 11:37 AM
	$weekday = $1;
	$month = $2;
	$mday = $3;
	$year = $4;
	$hours = $5;
	$min = $6;
	$sec = '00';
	$zone = "-0000";
    } elsif ( $received =~ /([A-Za-z]+),\s+([A-Za-z]+)\s+(\d+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
#Date: Mon, Jul 26 2004 03:27:10 +0000
	$weekday = $1;
	$month = $2;
	$mday = $3;
	$year = $4;
	$hours = $5;
	$min = $6;
	$sec = $7;
	$zone = $8;
    } elsif ( $received =~ /([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
	$weekday = "";
	$mday = $1;
	$month = $2;
	$year = $3;
	$hours = $4;
	$min = $5;
	$sec = $6;
	$zone = $7;
    } elsif ( $received =~ /([A-Za-z]+),\s+([0-9]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+)/i ) {
	$weekday = $1;
	$mday = $2;
	$month = $3;
	$year = $4;
	$hours = $5;
	$min = $6;
	$sec = '00';
	$zone = "-0000";
    } elsif ( $received =~ /([A-Za-z]+)\s+(\d+),\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
	$weekday = "";
	$month = $1;
	$mday = $2;
	$year = $3;
	$hours = $4;
	$min = $5;
	$sec = $6;
	$zone = $7;
	$month =~ s/^(...).+$/$1/;
    } elsif ( $received =~ /([A-Za-z]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+[A-Z]+\s+(\d+)/i ) {
#	Date: Thu Sep 01 10:30:47 PDT 2005
	$weekday = $1;
	$month = $2;
	$mday = $3;
	$hours = $4;
	$min = $5;
	$sec = $6;
	$year = $7;
	$zone = "-0000";
    } elsif ( $received =~ /(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/i ) {
# Date: 12/2/2004 8:44:37 AM
	$month = $1;
	$mday = $2;
	$year = $3;
	$hours = $4;
	$min = $5;
	$sec = $6;
	$zone = "-0000";
    } elsif ( $received =~ /([A-Za-z]+)\s+(\d+),\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+([\+-]\d\d\d\d)/i ) {
# Date: SAT 03, SEP 2005 23:03:47
	$weekday = $1;
	$mday = $2;
	$month = $3;
	$year = $4;
	$hours = $5;
	$min = $6;
	$sec = $7;
	$zone = $8;
    } elsif ( $received =~ /([A-Za-z]+)\s+([A-Za-z]+)\s+(\d+)\s+(\d+):(\d+):(\d+)\s+(\d+)/i ) {
# From ???@??? Tue Aug 13 18:44:35 2002
	$weekday = $1;
	$month = $2;
	$mday = $3;
	$hours = $4;
	$min = $5;
	$sec = $6;
	$year = $7;
	$zone = "-0000";
    }
}

sub readLine {
    $savedBlob = 0;
    $my_ = <INFILE2>;
    $my_ =~ s/\r//g;
    $my_ =~ s/\n//g;
    chomp $my_;
    $my_ .= "\n";
    $_ = <INFILE>;
    s/\r//g;
    s/\n//g;
    chomp $_;
    $_ .= "\n";
    eval ( 's/This is a multi-part message in MIME format.//;' );
    eval ( 's/This is a multipart message in MIME format.//;' );
    eval ( 's/^> This message is in MIME format. Since your mail reader does not understand//;' );
    eval ( 's/^this format, some or all of this message may not be legible\.//;' );
    if ( /encoding=\"(.+)\"/ ) {
	$junk = $1;
	if ( !Encode::resolve_alias("$junk") || $junk =~ /ascii|utf-8|base64/i ) {
	    #binmode(INFILE, ":raw");
	} else {
	    #binmode(INFILE, ":raw :encoding($junk)");
	}
    } else {
	$save_ = $_;
	if ( $charset !~ /iso-2022-jp/i ) {
	    if ( /\$B.+\(B/ ) {
		eval ( '$_ = Encode::decode("iso-2022-jp",$_);' );
		if ($@) {
		    print STDERR "readLine eval error: $@\n";
		} else {
		    $charset = "iso-2022-jp";
		}
		$_ = $save_;
	    }
	}
    }

    if ( eof(INFILE) ) {
	$origBlob .= $my_;
	$saveOrigBlob = $origBlob;
	return 0;
    }
    if ( $origState ) {
	if ( $filePath =~ /\.emlx$/ || $filePath =~ /\/\d+$/ ) {
	    $origBlob .= $my_;
	} else {
	    if ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ && ($content eq "" || $boundary eq "") ) {
		$saveOrigBlob = $origBlob;
		if ( $origBlob ne "RAW:\n" ) {
		    $origBlob = "\nRAW:\n";
		}
		$savedBlob = 1;
	    }
	    $origBlob .= $my_;
	}
    }
    return 1;
}

sub getMailTags {
#    return;    # MailStewardLite

    while ( !/\<\/dict/ && !eof(INFILE) && !(/^From\s/ && /\d\d:\d\d:\d\d/) ) {
	if ( /<key>mailTagsAnnotation<\/key>/ ) {
	    &readLine;
	    if ( /<string>(.+)<\/string>/ ) {
		$tagNotes = $1;
	    } else { next; }
	} elsif ( /<key>mailTagsKeyWords<\/key>/ ) {
	    &readLine;
	    if ( !/<array>/ ) {
		if ( /<string>(.+)<\/string>/ ) {
		    $tagKeywords = $1;
		} else { next; }
	    } else {
		while ( !/<\/array>/ ) {
		    &readLine;
		    if ( /<string>(.+)<\/string>/ ) {
			$tagKeywords .= " $1";
		    } else { last; }
		}
	    }
	} elsif ( /<key>mailTagsProject<\/key>/ ) {
	    &readLine;
	    if ( !/<array>/ ) {
		if ( /<string>(.+)<\/string>/ ) {
		    $tagCategory = $1;
		} else { next; }
	    } else {
		while ( !/<\/array>/ ) {
		    &readLine;
		    if ( /<string>(.+)<\/string>/ ) {
			$tagCategory .= " $1";
		    } else { last; }
		}
	    }
	} elsif ( /<key>mailTagsPriority<\/key>/ ) {
	    &readLine;
	    if ( /<integer>(.+)<\/integer>/ ) {
		$tagPriority = $1;
	    } else { next; }
	}
	&readLine;
    }
    $tagKeywords =~ s/^\s*//;
    $tagCategory =~ s/^\s*//;
}

sub doBoundary {
    if ( /boundary=([^\;]+)\;/i ) {
        $boundary = $1;
    } elsif ( /boundary=([^\;]+)$/i ) {
        $boundary = $1;
    }
    chomp($boundary);
    $boundary =~ s/\"//g;
    $boundary =~ s/(\W)/\\$1/g;
    push @boundarys, $boundary;
}

sub checkBoundary {
    foreach $junk (@boundarys) {
        if ( $junk ne "" && /$junk/i ) {
	    $disposition = "attachment";
	    if ( $boundary ne "" ) {
		$content = $charset = $encoding = "";
	    }
            return 1;
        }
    }
    return 0;
}

sub doContent {
    if ( /^Content-type:\s+([^\;]+)/i && $content eq "" ) {
        $content = $1;
	if ( $content =~ /multipart\/digest/i ) {
	    $digest = 1;
	}
#	$disposition = "";
    } else {
	&readLine;
	return;
    }
    chomp($content);
    if ( /boundary=.+$/i ) {
        &doBoundary;
    }
    if ( /name=$/i ) {
	&readLine;
	$filename = $_;
	chomp($filename);
	$filename =~ s/^\s+//;
	$filename =~ s/\s+$//;
        $filename =~ s/\"//g;
    } elsif ( /name=([^\;]+)/i ) {
        $filename = $1;
        $filename =~ s/\"//g;
    }
    if ( /charset=([^\;]+)/i ) {
        $charset = $1;
        $charset =~ s/\"//g;
        chomp($charset);
	if ( $charset =~ /^NULL$/ ) { $charset = ""; }
    }
    &readLine;
    while ( /^\s+[\S].+$/  && !eof(INFILE) ) {
        if ( /boundary=.+$/i ) {
	    &doBoundary;
	}
	if ( /name=([^\;]+)/ ) {
            $filename = $1;
            $filename =~ s/\"//g;
        }
	if ( /filename=([^\;]+)/i ) {
            $filename = $1;
            $filename =~ s/\"//g;
        }
        if ( /charset=([^\;]+)/i ) {
	    $charset = $1;
	    $charset =~ s/\"//g;
	    chomp($charset);
	    if ( $charset =~ /^NULL$/ ) { $charset = ""; }
	}
	&readLine;
    }
}

sub doEudoraAttachment {
    $blob = "";
    my $saveBlob = "";
    my $attachDir = $filePath;
    if ( $attachDir =~ /IMAP/ ) {
	$attachDir =~ s/\/[^\/]+\/[^\/]+$/\/IMAP Attachments/;
    } else {
	$attachDir =~ s/(Eudora Folder[^\/]*)\/.+$/$1\/Attachments Folder/;
    }
    if ( !(open ( CHUNK, "<$attachDir/$eudoraFilename" )) ) { print STDERR "problem opening $attachDir/$eudoraFilename\n"; return; }
#    binmode(CHUNK, ":raw");
    while ( $_ = <CHUNK> ) {
	chomp($_);
	$blob .= encode_base64($_);
    }
    close CHUNK;

    $attachTypes[$attachCount] = $eudoraContent;
    $attachFilenames[$attachCount] = $eudoraFilename;
    $attachEncodings[$attachCount] = 'base64';
    $attachBlobs[$attachCount] = $blob;
    $attachCount++;
    $eudoraContent = $eudoraFilename = "";
}

sub doAttachment {
    syswrite (STDOUT,"attachment\n",11);
    $blob = "";
    while ( ($boundary eq "" || !&checkBoundary) && !eof(INFILE) ) {
	if ( $digest ) {
	    &doDigest;
	    return;
	}
	if ( /^begin\s+\d+\s+([\S]+)/ ) {
	    $filename = $1;
	    $filename =~ s/\"//g;
	    if ( $content eq "" ) {
		$content = "application";
	    }
	    $saveContent = $content; $saveEncoding = $encoding; $saveCharset = $charset;
	    $noEncoding = 0;
	    $blob = $_;
	    while ( !/^end/ && !eof(INFILE) ) {
		&readLine;
		$blob .= $_;
	    }
	    &readLine;
	    last;
	}
	if ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ && $boundary eq "" ) {
	    last;
	}
	if ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ && $content eq "" ) {
	    last;
	}
	if ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ ) {
	    last;
	}
        if ( /^Content-Transfer-Encoding:\s*([^\;]+)/i ) {
	    $encoding = $1;
	    &readLine;
	    next;
	} elsif ( /^Content-type:\s+/i ) {
            &doContent;
            if ( $content =~ /multipart/i ) {
		$content = $charset = $encoding = "";
		return;
	    }
	    next;
	} elsif ( /^charset=([^\;]+)/i && !/\>/ ) {
	    $charset = $1;
	    $charset =~ s/\"//g;
	    chomp($charset);
	    if ( $charset =~ /^NULL$/ ) { $charset = ""; }
	    &readLine;
	    next;
	} elsif ( /filename=([^\;]+)/i ) {
	    $filename = $1;
	    $filename =~ s/\"//g;
	    &readLine;
	    next;
	} elsif ( /boundary=.+$/i ) {
	    &doBoundary;
	    &readLine;
	    next;
	} elsif ( /^\s*$/ ) {
	    &readLine;
	    $saveContent = $content; $saveEncoding = $encoding; $saveCharset = $charset;
	    $noEncoding = 0;
	    while ( ($boundary eq "" || !&checkBoundary) && !eof(INFILE) ) {
		if ( /^From\s/ && /\d\d:\d\d:\d\d/ && $file !~ /\.emlx$/ ) {
		    last;
		}
		if ( /boundary=.+$/i ) {
		    &doBoundary;
		    &readLine;
		    next;
		}
		if ( /\sfilename=([^\;]+)/i ) {
		    $filename = $1;
		    $filename =~ s/\"//g;
		    &readLine;
		    next;
		}
		if ( /^\<\?xml / ) {
		    $savexml = $_;
		    &readLine;
		    if ( /plist/ && /Apple/ && $file =~ /\.emlx$/ ) {
			&getMailTags;
			while ( &readLine ) {
			    if ( /\<\/plist\>/ ) {
				&readLine;
				last;
			    }
			}
			$boundary = "";
			next;
		    } else {
			$blob .= $savexml;
		    }
		}
		if ( $content =~ /text\/plain|text\/html/i && $filename !~ /winmail\.dat|\.pdf/ ) {
		    if ( $encoding =~ /base64/i ) {
			$noEncoding = 1;
			$_ = &decode_base64($_);
		    }
		}
		$blob .= $_;
		if ( eof(INFILE) ) {
		    $_ = "";
		    last;
		}
		&readLine;
	    }
	    next;
	} else {
	    &readLine;
	    next;
	}
    }
    $content = $saveContent;
    $encoding = $saveEncoding;
    $charset = $saveCharset;
    if ( $noEncoding ) { $encoding = ""; }
    if ( $content eq "" ) { return; }
    chomp($filename);
    $noFile = 0;
    if ( $filename eq "" ) {
	$noFile = 1;
	$filename = "attachment" . $attachCount;
    }
    if ( $filename =~ /win.*\.dat/i ) {
    } elsif ( $content =~ /html/i && $filename !~ /\.htm/i ) {
	$filename .= '.html';
    } elsif ( $content =~ /text\/enriched/i && $filename !~ /\.etf$/i ) {
	$filename .= '.etf';
    } elsif ( $content =~ /msword/i && $filename !~ /\.doc$/i ) {
	$filename .= '.doc';
    } elsif ( $content =~ /pdf/i && $filename !~ /\.pdf$/i ) {
	$filename .= '.pdf';
    } elsif ( $content =~ /jpeg/i && $filename !~ /\.jpg$/i && $filename !~ /\.jpeg$/i ) {
	$filename .= '.jpg';
    } elsif ( $content =~ /gif/i && $filename !~ /\.gif$/i ) {
	$filename .= '.gif';
    } elsif ( $content =~ /tiff/i && $filename !~ /\.tif/i ) {
	$filename .= '.tiff';
    }
    chomp($encoding);
    $saveBlob = $blob;
    if ( $filePath =~ /\.partial.*$/ && $content !~ /text\/plain/i && length($blob) < 5) {
	&doChunk;
	$myorigBlob = $origBlob;
	$myorigBlob =~ s/(\n[^\n]+\n)$/\n/;
	$myorigBlob .= $blob;
	$myorigBlob .= $1;
#	$myorigBlob .= "\n";
	$origBlob = $myorigBlob;
	$myorigBlob = "";
    }
    if ( $content =~ /text\/plain/i && $noFile && $encoding !~ /base64/i ) {
	if ( $saveBlob !~ /^\s*$/ ) {
	    if ( $charset =~ /ISO-8859-1/i ) {
		$saveBlob =~ s/\=A0/\n/g;
	    }
	    $saveBlob = &checkCoding($saveBlob);
	    if ( length($saveBlob) > length($body) ) {
		$bodyencoding = $encoding;
		$bodycharset = $charset;
	    }
	    $body .= $saveBlob;
	    if ( $chunkCount ) { $chunkCount--; }
	} elsif ( $blob !~ /^\s*$/ ) {
	    if ( $charset =~ /ISO-8859-1/i ) {
		$blob =~ s/\=A0/\n/g;
		$blob =~ s/\=0//g;
	    }
	    $blob = &checkCoding($blob);
	    $body .= $blob;
	    $bodyencoding = $encoding;
	    $bodycharset = $charset;
	}
	$filename = $content = $charset = $encoding = "";
	return;
    }
    if ( $blob !~ /^\s*$/ && $blob ne "" ) {	
	if ( $content =~ /html|enriched/i && !$htmlState ) {
	    $filename = $content = "";
	    return;
	}
	if ( $content !~ /html|enriched/i && !$attachState ) {
	    $filename = $content = "";
	    return;
	}
	if ( $charset =~ /ISO-8859-1/i ) {
	    $blob =~ s/\=A0/\n/g;
	}
	if ( $content =~ /text\/plain|text\/html|text\/xml/ && $encoding !~ /base64/i ) {
	    $blob = &checkCoding($blob);
	    if ( $charset =~ /utf-8/i ) {
		eval ( '$blob = Encode::decode("utf-8", $blob);' );
	    }
	} elsif ( $encoding !~ /base64/i ) {
	    if ( $encoding =~ /quoted-printable/i ) {
		$blob = &decode_qp($blob);
	    }
	    $blob = encode_base64($blob);
	    $encoding = 'base64';
	}
	if ( ($largeAttachState && length($blob) > $attachSize) || ($content =~ /text\/html/ && $blob !~ /<html/i && $blob !~ /<body/i && $blob !~ /<img /i && $blob !~ /<p>|<br>|<br \/>/i && $blob !~ /<font/i) ) {
	    $blob = "";
	} else {
	    $attachTypes[$attachCount] = $content;
	    $attachFilenames[$attachCount] = $filename;
	    $attachEncodings[$attachCount] = $encoding;
	    $attachCharsets[$attachCount] = $charset;
	    $attachBlobs[$attachCount] = $blob;
	    $attachCount++;
	}
    }
    if ( $content =~ /html|enriched|xml/i && $encoding !~ /base64/i && ($body eq "" || $body =~ /^\s*$/) ) {
	$body .= $blob;
	$bodyencoding = $encoding;
	$bodycharset = $charset;
    }
    $filename = $content = $charset = $encoding = "";
    return;
}

sub doChunkFiles {
    my $targetdir = $filePath;
    $targetdir =~ s/\/([^\/]+)\.partial.*$//;
    my $file = $1;
    opendir(TARGETDIR, "$targetdir") || print STDERR "problem opening $targetdir\n";
    @chunkFiles = sort grep (/^$file\.\d/, readdir(TARGETDIR));
    closedir TARGETDIR;
}

sub doChunk {
    $chunkCount++;
    if ( $chunkCount > ($#chunkFiles + 1) ) {
	$chunkCount--;
    }
    if ( !$htmlState && $body ne "" ) {
        $blob = "";
        return;
    }
    if ( !$attachState && $content !~ /html|enriched/ ) {
        $blob = "";
        return;
    }
    my $targetdir = $filePath;
    $targetdir =~ s/\/([^\/]+)\.partial.*$//;
    my $file = $chunkFiles[$chunkCount-1];
    if ( $file eq "" ) { return; }
    if ( !(open ( CHUNK, "<$targetdir/$file" )) ) { print STDERR "problem opening $targetdir/$file\n"; return; }
    $tmp = $/;
    undef $/;
    $blob = <CHUNK>;
    $/ = $tmp;
    close CHUNK;
}

sub doDigest {
    while ( !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE) ) {
	&readLine;
	if ( /^Content-type:\s+/i ) {
	    $content = "";
	    &doContent;
	    if ( $content !~ /text\/plain/ && $content !~ /digest/ ) {
		$digest = "";
		&doAttachment;
		$digest = 1;
	    }
	}
	while ( !&checkBoundary && !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE) ) {
	    if ( /^Date:|^To:|^From:|^Subject:/i ) {
		$body .= &myDecode($_);
	    } elsif ( /^Content-type:\s+/i ) {
		$content = "";
		&doContent;
		if ( $content !~ /text\/plain/ && $content !~ /digest/ ) {
		    $digest = "";
		    &doAttachment;
		    $digest = 1;
		}
	    } elsif ( /^charset=([^\;]+)/i && !/\>/ ) {
		$charset = $1;
		$charset =~ s/\"//g;
		chomp($charset);
		if ( $charset =~ /^NULL$/ ) { $charset = ""; }
	    } elsif ( /^Content-Transfer-Encoding: ([^\;]+)/i ) {
		$encoding = $1;
		chomp($encoding);
	    } elsif ( /^\s*$/ ) {
		while ( !&checkBoundary && !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE)  ) {
		    $body .= &checkCoding($_);
		    &readLine;
		}
	    }
	    &readLine;
	    if ( /^\s*$/ && $content eq "" ) {
		&readLine;
	    }
	}
	if (  !(/^From\s/ && /\d\d:\d\d:\d\d/) && !eof(INFILE)  ) {
	    &readLine;
	    if ( /^Content-type:\s+/i ) {
		$content = "";
		&doContent;
		if ( $content !~ /text\/plain/ && $content !~ /digest/ ) {
		    $digest = "";
		    &doAttachment;
		    $digest = 1;
		}
	    }
	}
    }
    $digest = "";
}

sub stuffIt {
    if ( $year eq "" && $month eq "" && $mday eq "" && $subject eq "" && $addr eq "" && $addr2 eq "" && $body eq "" ) {
	goto DONE;
    }
    my $i = 0;
    if ( !$year ) {
	$received = $saveFromDate;
	&getDate;
    }
    if ( $month < 1 || $month > 12 ) {
	$month =~ s/(...).*/$1/;
	$month = $months{lc $month};
    }
    while (length($month) < 2) { $month = '0' . $month; }
    while (length($mday) < 2) { $mday = '0' . $mday; }
    if ( $year < 200 ) { $year += 1900; }
    if ( $year < 1920 ) { $year += 100; }
    $date = $year . "-$month" . "-$mday" . " $hours:$min:$sec $zone";

    if ( $year < $beginYr ) { goto DONE; }
    if ( $year == $beginYr && $month < $beginMo ) { goto DONE; }
    if ( $year == $beginYr && $month == $beginMo && $mday < $beginDa ) { goto DONE; }
    if ( $year > $endYr ) { goto DONE; }
    if ( $year == $endYr && $month > $endMo ) { goto DONE; }
    if ( $year == $endYr && $month == $endMo && $mday > $endDa ) { goto DONE; }
    
    $addr = &myDecode($addr);
    $addr2 = $TO . $CC;
    $addr2 =~ s/^,//;
    $addr2 =~ s/,,/,/g;
    $addr2 = &myDecode($addr2);
    $subject = &myDecode($subject);
    $i = $subject;
    if ( $subject =~ /\$B.+\(B/ ) {
	eval ( '$subject = Encode::decode("iso-2022-jp",$subject);' );
	if ($@) {
	    print STDERR "stuffit eval error: $@\n";
	    $subject = $i;
	}
    }
    $addr =~ s/\"//g;
    $addr2 =~ s/\"//g;
#    $body =~ s/\&copy\;/©/g;

    if ( $filePath =~ /Eudora/ ) {
	$body =~ s/\<x-[^\>]+\>//;
	$body =~ s/\<\/x-[^\>]+\>//;
    }

    if ( $stuffitCount ) { &waitForSignal; }
    if ( $origState ) {
	$saveOrigBlob =~ s/^\s*//;
	$saveOrigBlob .= "\nENDOFRAW:\n";
	open ( RAWTMPFILE, ">$rawtemppath" ) || print STDERR "problem opening $rawtemppath\n";
	binmode(RAWTMPFILE, ":raw :utf8");
	syswrite (RAWTMPFILE,$saveOrigBlob,length($saveOrigBlob));
	close RAWTMPFILE;
    }
    if ( $tagCategory || $tagKeywords || $tagNotes ) {
	eval ( '$tagCategory = Encode::decode("utf-8", $tagCategory);' );
	if ($@) {
	    print STDERR "eval error in $tagCategory: $@\n";
	    $tagCategory = "";
	}
	eval ( '$tagKeywords = Encode::decode("utf-8", $tagKeywords);' );
	if ($@) {
	    print STDERR "eval error in $tagKeywords: $@\n";
	    $tagKeywords = "";
	}
	eval ( '$tagNotes = Encode::decode("utf-8", $tagNotes);' );
	if ($@) {
	    print STDERR "eval error in $tagNotes: $@\n";
	    $tagNotes = "";
	}
    }
    $i = $mailbox;
    eval ( '$mailbox = Encode::decode("utf-8", $mailbox);' );
    if ($@) {
	print STDERR "eval error in $mailbox: $@\n";
	$mailbox = $i;
    }
    if ( $tagCategory || $tagKeywords || $tagNotes || $tagPriority ) {
	$saveOrigBlob = "MAILBOX: $mailbox\nFROM:$addr\nTO:$addr2\nSUBJECT:$subject\nDATE:$date\nMAILTO:$mailto\nTAGCAT:$tagCategory\nTAGKEY:$tagKeywords\nTAGNOTES:$tagNotes\nTAGPRIORITY:$tagPriority\nBODY:";
    } else {
	$saveOrigBlob = "MAILBOX: $mailbox\nFROM:$addr\nTO:$addr2\nSUBJECT:$subject\nDATE:$date\nMAILTO:$mailto\nBODY:";
    }
    open ( TMPFILE, ">$temppath" ) || print STDERR "problem opening $temppath\n";
    binmode(TMPFILE, ":raw :utf8");
    syswrite (TMPFILE,$saveOrigBlob,length($saveOrigBlob));
    $saveOrigBlob = "$body\nENDOFBODY:\n";
    if ( $bodyencoding =~ /base64/i ) {
	$encoding = "quoted-printable";
	$saveOrigBlob = &checkCoding($saveOrigBlob);
	$bodyencoding = "quoted-printable";
    } else {
	if ( $bodycharset =~ /utf-8/i ) {
	    eval ( '$saveOrigBlob = Encode::decode("utf-8", $saveOrigBlob);' );
	}
    }

    if ( ($attachState || $htmlState) && $attachCount ) {
        for ( $i=0; $i<$attachCount; $i++ ) {
            $attachType = $attachTypes[$i];
	    $attachFilename = $attachFilenames[$i];
	    $attachFilename = &myDecode($attachFilename);
	    $attachFilename =~ s/\//-/g;
	    $saveOrigBlob .= "ATTACH:\nTYPE:$attachType\nFILENAME:$attachFilename\nENCODING:$attachEncodings[$i]\nBLOB:\n$attachBlobs[$i]\nENDATTACH:\n";
        }
        if ( $i ) {
	    $saveOrigBlob .= "ENDATTACHMENTS:\n";
	}
    }
    $saveOrigBlob .= "ENDOFEMAIL:\n";
#    if (0) {
    if ( $bodyencoding =~ /quoted-printable/i && $bodycharset =~ /utf-8/i ) {
	binmode(TMPFILE, ":raw");
	print TMPFILE $saveOrigBlob;
    } else {
	binmode(TMPFILE, ":raw :utf8");
	syswrite (TMPFILE,$saveOrigBlob,length($saveOrigBlob));
    }
    close TMPFILE;
    $bodyencoding = "";
    $bodycharset = "";
    $stuffitCount++;
  DONE:
    undef @attachTypes;
    undef @attachFilenames;
    undef @attachBlobs;
    undef @attachEncodings;
    undef @attachCharsets;
    $attachCount = 0;
    $saveOrigBlob = "";
    $saveFilePath = $filePath;
}

sub waitForSignal {
    $saveSubject =~ s/\"//g;
    $saveSubject = substr($saveSubject,0,300);
    eval ( '$saveSubject = Encode::decode("utf-8", $saveSubject);' );
    if ($@) {
	print STDERR "eval error in $saveSubject: $@\n";
	$saveSubject = "";
    }
    if ( $mboxState ) {
#	syswrite (STDOUT,"$saveFilePath",length($saveFilePath));
	eval ( 'syswrite (STDOUT,"$saveFilePath\n$saveSubject",length($saveFilePath)+length($saveSubject)+1);' );
	if ($@) {
	    print STDERR "eval error: $@\n";
	    syswrite (STDOUT,"$saveFilePath",length($saveFilePath));
	    #$subject = $saveSubject;
	}
    } else {
#	syswrite (STDOUT,"~/Library/Mail/$saveFilePath",length($saveFilePath)+15);
	eval ( 'syswrite (STDOUT,"~/Library/Mail/$saveFilePath\n$saveSubject",length($saveFilePath)+length($saveSubject)+16);' );
	if ($@) {
	    print STDERR "waitForSignal: eval error: $@\n";
	    syswrite (STDOUT,"~/Library/Mail/$saveFilePath",length($saveFilePath)+15);
	    #$subject = $saveSubject;
	}
    }
    $mysignal = "";
    while ( $mysignal eq "" ) {
	sysread(STDIN,$mysignal,8000);
    }
}

sub myDecode ($) {
    my $res = shift;
    my $saveres = $res;
    if( $res =~ /=\?[^?]+\?[^?]\?[^\?]+\?=/ ) {
	eval ( '$res = Encode::decode("MIME-Header", $res);' );
	if ($@) {
	    print STDERR "eval error: $@\n";
	    $res = $saveres;
	}
    }
    return $res;
}

