#!perl -w

=pod

=head1 NAME

Neuron::SWC::Write - Write the SWC file format

=head1 SYNOPSIS

Neuron::SWC::Write provides functions to output a neural morphology to an SWC
file.

=head1 FUNCTIONS

=over 0

=item *
writeHeader(I<header>, I<file>);

write header hash into SWC file.

=item *
writeData(I<neuron>, I<file>);

writes data from array of hashes into SWC file.

=back

=head1 AUTHOR

Gunther Schmidl <gschmidl@gmx.at>

=cut

package Neuron::SWC::Write;
use strict;
use warnings;

# prepare variable export

use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(writeHeader writeData);
@EXPORT_OK = qw();
$VERSION = 1.00;






#==============================================================================
#
# writeHeader(hash, file) - write header from hash to file.
#
#==============================================================================

sub writeHeader(%, $)
{
    my($desc, $val);

    open HDROUT, ">$_[1]" || die "$_[1] could not be opened: $!";

    while (($desc,$val) = each %{$_[0]})
    {
        printf HDROUT "# %21.21s %s\n", $desc, $val;
    }
    print HDROUT "# " . chr(0x1a) . "\n";
    close HDROUT;
    return 0;
}






#==============================================================================
#
# writeData(array, file) - write data from 2d array to file.
# Will append to already existing file in case a header is wanted.
#
#==============================================================================

sub writeData(@, $)
{
    my ($i, @n);

    @n = @{$_[0]};
    open FILE, ">>$_[1]" || die "$_[1] could not be opened: $!";

    # print all the lines
    for ($i = 1; $i <= $#n; $i++)
    {
        print FILE " $n[$i]->{'number'} $n[$i]->{'flag'} $n[$i]->{'x'} " .
            "$n[$i]->{'y'} $n[$i]->{'z'} $n[$i]->{'d'}  $n[$i]->{'parent'}\x0d";
    }

    close FILE;
    return 0;
}
