#!/usr/bin/perl -w
use strict;
##
## Description: Script for expanding the comlimentsets into joint media 
## Auther:  Niels
## Date:    Jan 2010
##
#######################################################################

my $infile  = $ARGV[0];
my $outfile = $ARGV[1] or die "Usage: $0 <infile> <outfile>\n";

open my $INFILE, "<", $infile or die "Can't open $infile: $!\n";

my $base_line = <$INFILE>;

## find the base media sets!
chomp $base_line;
my $base_mets  = {};
my $met_pos    = [];
my $base_count = 0;

foreach my $met ( split /,/, $base_line ){
    $base_count += 1;
    $base_mets->{$met} = [$met];
    $met_pos->[$base_count] = $met; 
}

## find replacements for them!
while ( my $line = <$INFILE> ){
    chomp $line;
    my $media_mets = {};
    my $new_mets = {};
    foreach my $met ( split /,/, $line ) {
        if ( exists ( $base_mets->{$met} ) ){
            $media_mets->{$met} = 1;
        }
        else{
            $new_mets->{$met} = 1;
        }
    }

    foreach my $met ( keys %{$base_mets} ){
        if ( ! exists $media_mets->{$met} ){
            my $new_met_string = join( ',', keys %{$new_mets} );
            push @{$base_mets->{$met}}, $new_met_string; 
        }
    }
}

close $INFILE;

## new find all pairwise cominations...
my $count_array = [];
for ( my $i=1; $i <= $base_count; $i+= 1 ){
    $count_array->[$i] = 0;
}
open my $OUTFILE, ">", $outfile or die "Can't open $outfile: $!\n";


my %media_set;
map { $media_set{$_} = 1 } split ',',  join( ',', @{$met_pos}[1..$base_count] );

print $OUTFILE join( ',', sort {$a <=> $b} keys %media_set ) . "\n";

while ( $count_array = update_array( $count_array, $base_mets, $met_pos ) ){
    my @media_set;

    for ( my $i=1; $i <= $base_count; $i+= 1 ){
        push @media_set, $base_mets->{$met_pos->[$i]}->[$count_array->[$i]];
    }

    my %media_set;
    map { $media_set{$_} = 1} split ',',  join( ',', @media_set );

    print $OUTFILE join( ',', sort {$a <=> $b} keys %media_set ) . "\n";
}

close $OUTFILE;

sub update_array {
    my $ud_array = shift;
    my $mets     = shift;
    my $met_ids  = shift;

    for ( my $i =1; $i <= scalar( keys %{$mets} ); $i+= 1 ) {
        
        if ( $ud_array->[$i] + 1 == scalar( @{$mets->{$met_ids->[$i]}} ) ){
            $ud_array->[$i] = 0;
            
            # break for the fuction....
            if ( $i == scalar( keys %{$mets} )) {
                return 0;
            }
        }
        else {
            $ud_array->[$i] += 1;
            return $ud_array;
        }
    }
}
