#!/usr/bin/perl

use Mail::Util;

if ($#ARGV < 0) {
  print "usage: mboxes2mh.pl <list of mboxes>\n";
  print "       Creates in the current directory subdirs that contain all\n",
        "       the messages in the order they are in the mbox files. The\n",
		  "       name of the directory is that of the mbox file.\n";
  exit;
}

# Loop over alle given arguments:
for ($i=0; $i <= $#ARGV; $i++) {
  my $file = $ARGV[$i];
  my @filepath = split('/', $file);
  my $filename = $filepath[$#filepath];
  print "MBOX: $file into $filename:\n";
  if (!(-e $filename)) {
    mkdir( $filename);
  };
  # now get the ref to the message arrays.
  my $mboxref = Mail::Util::read_mbox( $file );
  # make mbox the array of message arrays
  @mbox = @$mboxref;
  # loop over all messages
  $k = 1;
  foreach $message (@mbox) {
	 # $message is a reference to an array
    open( MESSG, ">$filename/$k");
    print "\t ".$k."\n";
	 print MESSG @$message;
    close( MESSG);
	 $k++;
  }
}
