#!/usr/bin/perl

($mfile,$snd,$bdr,$dir)=@ARGV;
$start=0;
open(M,"<$mfile") or die("ERROR: cannot read $mfile: $!");
while(<M>){ chomp($_); $line=$_;
	if($start==0 and index($line, "--$bdr")==0){
println("- found boundary");
		$start=1;
	}
	if(index($line, "--$bdr--")==0){
println("- mail closed");
		$start=1;
		close(T);
	}
	if($line=~/filename=/){
		$start=2;
		$filename=$1 if($line=~/^.+_(\d+)\.jpg/);
		println("$filename.$snd.jpg");
		open(T, ">/tmp/$filename.$snd.jpg") or die("ERROR: cannot write file /tmp/$filename.$snd.jpg: $!");
	}
	if($start!=2){
		next;
	}
	print T $line."\n" if($line=~/\S/);
}
close(T);
close(M);

sub println{
	my $msg = shift;
	print $msg."\n";
}

