#!/usr/local/bin/perl

# 
# memomerg.pl: 
# 
#     Nov.25,'95. neco.
#     Dec.26,'95. neco. 並べ変え
#     Dec.29,'95. neco diff オプション '-d' 追加
#
#     [1996/06/17] OSHIRO Naoki. オプション判定修正
#     [1996/07/25] OSHIRO Naoki. 
#          先頭のバナー部（'-*- memo -*-' など）を並び換えないよう
#          別に扱うようにした．
#     [1996/09/02] OSHIRO Naoki.
#          メモ区切り直後の日付文字列のみをソートに使うようにした．
#     [1996/10/07] OSHIRO Naoki.
#          空のバナー部を出力しないようにした．
#     [1996/12/22] OSHIRO Naoki.
#        バナー部と区切り出力を調整．
#     [1997/07/28] OSHIRO Naoki.
#        逆順オプション '-r' を付加．
#
#     $Log: memomerg,v $
#     Revision 1.1  1996/07/25 04:28:23+09  oshiro
#     Initial revision
#
#

#
# Memo: 
#    [1997/01/27] 
#       コマンドライン引数でなく，パイプなどの標準入力を使うと
#       出力がなくなるよ．バナー部を処理するためにはしょうがない？
#

require "getopts.pl";
&Getopts("dcr"); # d: diff, c: common, r: reverse

$date_init="[----/--/--]";
$date=$date_init;
foreach $fname (@ARGV) {
    # $lcnt=0; # これを生かしたほうがいいのかどうか？
    if (!open(F, "<$fname")) {
	print STDERR "Cannot open '$fname'\n";
	next;
    }
    $banner="";
    while (<F>) {
	if (/^-+\s*$/) {
		$new=1;
		last;
	}
	$banner.=$_;
    }
    $banner{$banner}++ if ($banner ne "");
    $str=$_;
    while (<F>) {
	if (/^-+\s*$/ || eof(F)) {
	    $lstr=sprintf("%06d", $lcnt);
	    $memo{$date . $lstr . $fname}=$str unless ($cnt{$str}++);
	    $date=$date_init;
	    $str=$_;
	    $new=1;
	    next;
	}
	$str.=$_;
	$date=$1 if (/^(\[[^\]]+\])\s*$/ && $new==1);
	$lcnt++;
	$new=0;
    };
    close(F);
}

# 出力部
$out_cnt=0;	
# バナー部の出力
@banner=keys(%banner);
$b=shift(@banner);
$cnt=$banner{$b};
if (!($b=~/^\s*$/) && ((!$opt_d && !$opt_c) || ($opt_d && $cnt==1) || ($opt_c && $cnt>1))) {
    print "$b";
    $out_cnt++;
}
foreach $b (@banner) {
    next unless (!($b=~/^\s*$/) && ((!$opt_d && !$opt_c) || ($opt_d && $cnt==1) || ($opt_c && $cnt>1)));
    print "---\n$b";
    $out_cnt++;
}

# メモ本体の出力
@key=sort(keys(%memo));
@key=reverse @key if ($opt_r);
foreach $d (@key) {
    $str=$memo{$d};
    $cnt=$cnt{$str};
    if ((!$opt_d && !$opt_c) || ($opt_d && $cnt==1) || ($opt_c && $cnt>1)) {
	print "$str";
	$out_cnt++;
    }
}
print "---\n" if ($out_cnt>0);
