#  Copyright (c) 1997-2006
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
#  http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-----------------------------------------------------------------------------
#  $Project: polymake $$Id: SplitsTree.pm,v 1.5 2006/03/07 17:50:53 gawrilow Exp $

package SplitsTree::File;

use Struct (
   [ new => '$;$' ],
   [ '$workfile' => '#1' ],
   [ '$title' => '#2' ],
   '@metric',
   '@taxa',
);

sub toString
{
   my ($self) = @_;
   my $title=$self->title || "unnamed";
   my $ntax=@{$self->taxa};
   if (@{$self->metric} != $ntax) {
      croak( "metric/taxa dimension mismatch" );
   }
   my $text = << ".";
#NEXUS

[! $title ]

BEGIN taxa;
    DIMENSIONS ntax=$ntax;
TAXLABELS
.
   map { $text .= "    $_\n" } @{$self->taxa};
   $text .= << ".";
;
END;

BEGIN distances;
    DIMENSIONS ntax=$ntax;
    FORMAT
        triangle=LOWER
        diagonal
        labels
        missing=?
    ;
    MATRIX
.
    for (my $n=0; $n < $ntax; ++$n) {
       my $this_tax=$self->taxa->[$n];
       my @d=(split /\s+/, $self->metric->[$n])[0..$n];
       $text .= "    $this_tax  @d\n";
    }
    $text .= << ".";
    ;
END;
.
}

sub print_it
{
   my ($self) = @_;
   open my $file, ">".$self->workfile
      or die ref($self), "::print_it: could not write file ", $self->workfile, ": $!\n";
   print $file $self->toString;
   close $file;
}

1

# Local Variables:
# c-basic-offset:3
# End:
