#!/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/attach:.*//;
			$_ =~ s/filename:.*//;
		}
	$name = @thread[0];
	#$url = @thread[1];
	if (@thread[2] =~ /attach:/){ $attach = @thread[2]; }
	if (@thread[3] =~ /attach:/){ $attach = @thread[3]; }
	if (@thread[4] =~ /attach:/){ $attach = @thread[4]; }

	if (@thread[2] =~ /suffix:/){ $suffix = @thread[2]; }
	if (@thread[3] =~ /suffix:/){ $suffix = @thread[3]; }
	if (@thread[4] =~ /suffix:/){ $suffix = @thread[4]; }

	$attach =~ s/attach://;
	$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 = "";
}

