#!/usr/bin/perl

use Jcode;
use MIME::Base64;

$datdir=$ARGV[0]; #新月の dat ディレクトリの位置 ex) ../shingetsu-0.4b1/dat
$str=$ARGV[1]; #スレッドのタイトル ex) "ネタ板"

$str = Jcode->new($str)->h2z->utf8;
$filename = unpack("H*", $str);
$datfile = "$datdir/thread_\U$filename\E.dat";
$str =~ s|[^\w]|'%' . uc(unpack('H2', $&))|eg;
#print "$datfile\n";

$num=0;

open(IN, "$datfile") or die;
@list = <IN>;
close(IN);

foreach(@list){
	$dat = @list[$num];
	@thread = split(/<>/, $dat);
	#print "@thread\n";
		foreach(@thread){
			$_ =~ s/body:.*//;
			$_ =~ s/filename:.*//;
			if ($_ =~ /attach:/){ $attach = $_; }
			if ($_ =~ /suffix:/){ $suffix = $_; }
		}
	$name = @thread[0];
	#$url = @thread[1];

	$attach =~ s/attach://;
	$attach =~ s/\n//;
	$suffix =~ s/suffix://;
	
	#print $attach;
	if ($attach ne ""){
		open(OUT, "> $name.$suffix");
		$dec_attach = decode_base64($attach);
		print OUT "$dec_attach";
		close(OUT);
	}

	$num = $num +1;
	$dec_attach = "";
	$attach = "";
	$suffix = "";
}

