#!/usr/bin/perl
# Changes mail folders into folders with separate files
# named by Message-ID
# (c) Javier Fernandez-Sanguino Pea 1998
# Distributed under the GNU GPL License

use Getopt::Std;
getopts('d:');
$mail="";
$add_mail=0;
while ($file_to_folder=shift(ARGV)) {
	if (-f $file_to_folder){
		my $file = 0;
		open (FILEREAD,"<$file_to_folder") || die ("Could not read $file_to_folder\n");
		print "Opening $file_to_folder for reading\n" if $opt_d;
		mkdir $file_to_folder.".folder",0700 || die ("Could not creat directory for $file_to_folder\n");
		$PREDIR="./".$file_to_folder.".folder";
		print "Creating directory $PREDIR\n" if $opt_d;
		while ($line=<FILEREAD>) {
			if ($line =~ /^From (.+) / ) {
				print "New mail from: $1\n" if $opt_d;
				if ($mail ne "") {
					open (FILE,">$PREDIR/$file") || die ("Could not create $file\n");
					print FILE $mail;
					close FILE;
					print "Created $file\n" if $opt_d;
				}
				$mail=""; 
				$add_mail=1;
			}
			if ($add_mail==1){		
				print "Adding $line" if $opt_d > 2;
				$mail=$mail.$line;
			}
			if ($line =~ /^Message-ID: (.*)$/i ) {
				$id=$1;
				$file++;
				print "Saving at $file ID found for message: $id\n" if $opt_d;
			}
		} # del while $line
		close FILEREAD;
	} # del if -f
} # del while shift

exit 0;
