#!/usr/bin/perl
use lib '../lib';
use Query;
use Include;
use DirectoryLoop;
my($y,$m,$d)=(localtime())[5,4,3];
my $today	= sprintf("%04d%02d%02d",$y+1900,$m+1,$d);
my @all		= grep {$_} DirectoryLoop{ $1	if($_[1]=~/(\d+)\.pl$/)} 'bin/';
my(@next,@back);
my %f	= Query::toHash();
for my $i(sort{$b<=>$a} @all){
	local %Form;
	$Form{CODE}=$i;
	eval{ require "bin/$i.pl" } || next;
	my $date = sprintf("%04d%02d%02d",@Form{YEAR,MON,DAY});
	next	unless($Form{PUB});
	if($f{CODE}){#バックナンバー表示
		if($date > $today){
			push(@next,\%Form);
		} elsif($i > $f{CODE}){
			push(@nback,\%Form);
		} else {
			push(@back,\%Form);
		}
	} else {
		if($date > $today){
			push(@next,\%Form);
		} else {
			push(@back,\%Form);
		}
	}
}
unless(@back){
	print "Location: 404.html\n\n";
	exit;
}
my $next	= pop @next;
my $now		= shift @back;
unshift(@back,@nback);
my @list	= ();
map {
	local %hash;
	eval{ require 'bin/detail/'.$now->{CODE}."/$_.pl" };
	if($hash{PUB}){
		push(@list,$_);
		$now->{$_}	= \%hash;
	}
} grep {$_} DirectoryLoop{ $1	if($_[1]=~/(\d+)\.pl$/)} 'bin/detail/'.$now->{CODE};
print "Content-Type: text/html\n\n";
print include('format/index.txt',{
	hash	=> $now,
	list	=> \@list,
	CODE	=> $now->{CODE},
	THEME	=> $now->{THEME},
	PHOTO1	=> (-f 'photo/0/'.$now->{CODE}.'-'.$list[0].'.jpg')?'photo/0/'.$now->{CODE}.'-'.$list[0].'.jpg':'img/spacer.gif',
	PHOTO2	=> (-f 'photo/0/'.$now->{CODE}.'-'.$list[1].'.jpg')?'photo/0/'.$now->{CODE}.'-'.$list[1].'.jpg':'img/spacer.gif',
	PHOTO3	=> (-f 'photo/0/'.$now->{CODE}.'-'.$list[2].'.jpg')?'photo/0/'.$now->{CODE}.'-'.$list[2].'.jpg':'img/spacer.gif',
	PHOTO4	=> (-f 'photo/0/'.$now->{CODE}.'-'.$list[3].'.jpg')?'photo/0/'.$now->{CODE}.'-'.$list[3].'.jpg':'img/spacer.gif',
	PHOTO5	=> (-f 'photo/0/'.$now->{CODE}.'-'.$list[4].'.jpg')?'photo/0/'.$now->{CODE}.'-'.$list[4].'.jpg':'img/spacer.gif',
	NEXT	=> ($next)?include('format/next.txt',$next):'',
	NEW		=> ($f{CODE})?include('format/new.txt'):'',
	LIST	=> (@back)?join("\n",map{include('format/list.txt',$_)} @back):include('format/null.txt')
});
