use strict;

my %a;
my %b;
my %c;
my %d;

my %d_alg;

my $n=shift;

# a
my $a_file = "a/" . $n . ".txt";
open (A, $a_file);
while (<A>) {
	chomp;
	s/ \|\] */\]\^/;
    	if (s/^\[\d+-(\d+)\] *//) {
		$a{$1}=$_;
    	}
}

# b
my $b_file = "b/" . $n . ".txt";
open (B, $b_file);
while (<B>) {
    chomp;
    s/ \|\] */\]\^/;
    if (s/^\[\d+-(\d+)\] *//) {
        $b{$1}=$_;
    }
}

# c
my $c_file = "c/" . $n . ".txt";
open (C, $c_file);
while (<C>) {
    chomp;
    s/ \|\] */\]\^/;
    if (s/^\[\d+-(\d+)\] *//) {
        $c{$1}=$_;
    }
}

# d
my $d_file = "d/" . $n . ".txt";
open (D, $d_file);
while (<D>) {
    chomp;
    s/ \|\] */\]\^/;
    if (s/^\[\d+-(\d+)\] *//) {
        $d{$1}=$_;
    }
}
my $d_alg_file = "d/" . $n . ".alg";
open (DA, $d_alg_file);
while (<DA>) {
    my ($a,$d)=split;
    my @a = split(/,/, $a);
    my @d = split(/,/, $d);
    foreach my $a_el (@a) {
        foreach my $d_el (@d) {
            $d_alg{$a_el} .= " " . $d{$d_el};
        }
    }
    
}



foreach my $aa (sort {$a <=> $b} keys %a) {

	my $tpp_id = $aa;
	while ((length $tpp_id) < 3) { $tpp_id = "0" . $tpp_id }
	$tpp_id = "[" . $n . $tpp_id . "a]";
	print $tpp_id, " ", $a{$aa}, "\n";

	my $tpp_b_id = $aa;
	while ((length $tpp_b_id) < 3) { $tpp_b_id = "0" . $tpp_b_id }
	$tpp_b_id = "[" . $n . $tpp_b_id . "b]";
	print $tpp_b_id, " ", $b{$aa}, "\n";

	my $tpp_c_id = $aa;
	while ((length $tpp_c_id) < 3) { $tpp_c_id = "0" . $tpp_c_id }
	$tpp_c_id = "[" . $n . $tpp_c_id . "c]";
	print $tpp_c_id, " ", $c{$aa}, "\n";

	my $tpp_d_id = $aa;
	while ((length $tpp_d_id) < 3) { $tpp_d_id = "0" . $tpp_d_id }
	$tpp_d_id = "[" . $n . $tpp_d_id . "d]";
	print $tpp_d_id, "", $d_alg{$aa}, "\n";



	print "\n";

}
