#!/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){
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 ([\w\.]+@[\w\.]+)/ ) {
		print "New mail from: $1\n" if $opt_d;
		if ($mail ne "" && $file ne "") {
			open (FILE,">$PREDIR/$file") || die ("Could not create $file\n");
			print FILE $mail;
			close FILE;
			print "Created $file\n" if $opt_d;
		}
		$mail=""; $file="";
		print "New mail found\n" if $opt_d;
		$add_mail=1;}
	if ($add_mail==1){		
		print "Adding $line" if $opt_d;
		$mail=$mail.$line;}
	if ($line =~ /^Message-ID: (.*)$/i ) {
		$file=$1;
		print "ID found for message: $file\n" if $opt_d;
		}
} # del while $line
close FILEREAD;
} # del if -f
} # del while shift

exit 0;
