#!/usr/pkg/bin/perl
#
# tdf_join.pl: 日毎の tdf ファイルを月毎にまとめる
################################################################

use strict;
use lib qw(lib);

use Getopt::Std;

use JConv;
use TDS;
use TDS::System;
use TDS::DirInfo;

require 'conf.ph';

my %opt;

my @orig_files;

getopts("ay:m:", \%opt);

my $diary_dir = $TDS::DirInfo::DiaryDir;

my @yms;

if ($opt{a})
{
    my $status = new TDS::Status;
    my $now_year = (localtime)[5]+1900;
    for ($status->start_year..$now_year){
	my $year = $_;
	my $dir = "$diary_dir/$year";
	opendir(DIR, $dir) || next;
	for (sort readdir(DIR)){
	    next if (! -d "$dir/$_") || $_ !~ /^(\d\d)$/;
	    push(@yms, "$year/$1");
	}
    }
} else {
    my $year = $opt{y} || (localtime)[5]+1900;
    my $month = $opt{m} || (localtime)[4]+1;

    push(@yms, sprintf("%04d/%02d", $year, $month));
}
	

for (@yms){
    my ($year, $month) = split('/');
    my $dir = "$diary_dir/$year/$month";    # yet: DirSplit = 1;
#    print STDERR "$dir, ";

    my $outfile = "$diary_dir/$year/$month.tdf";
    print STDERR "->$outfile\n";
    open(OUT, ">$outfile") || die $outfile;
    opendir(DIR, $dir) || die $dir;
    for (sort readdir(DIR)){
	next unless /^(\d\d)\.tdf$/;
	my $day = $1;
	my $file = "$dir/$day.tdf";
	print OUT "DIARY $year $month $day\n";
	print STDERR "$year/$month/$day\n";
	open(F, $file) || die $file;
	while (<F>){
	    jconv(*_, 'euc');
	    print OUT $_;
	}
	close F;
    }
    closedir(DIR);
    close(OUT);
}

	
	
    
