#  Copyright (c) 1997-2004
#  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.4 2004/10/26 19:00:06 gawrilow Exp $

package SplitsTree::File;

sub new
{
   my $class=shift;
   if (@_%2) {
      croak( "usage: new $class KEY => value ..." );
   }
   bless { @_ }, $class;
}

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

[! polymake data ]

BEGIN taxa;
    DIMENSIONS ntax=$ntax;
TAXLABELS
.
   map { $text .= "    $_\n" } @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=shift(@taxa);
      my @d=(split /\s+/, shift(@metric))[0..$n];
      $text .= "    $this_tax  @d\n";
    }
    $text .= << ".";
    ;
END;
.
    return $text;
}

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:
