package FASTA::FileIO;
BEGIN{ push(@INC, $ENV{LOCAL_PERL_MODULES}); }
use Carp;
use warnings;
use strict;
use FASTA::Sequence;

my $numCharactersPerLine = 60;

###################################################
sub parse {
    my $filename = shift or croak "Input file name is not specified.";
    my $seqs     = [];
    open IN, $filename or croak "Can't open $filename to read.";
    my $curSeq;
    while(<IN>){
	chomp;
	if( /^>(.+)$/ ){
	    pushSeq( $seqs, $curSeq );
	    $curSeq = instantiateSequence();
	    $curSeq->setTitle($1);
	} elsif( /(\w+)/ ) {
	    $curSeq->appendSequence($_);
	}
    }
    pushSeq( $seqs, $curSeq );
    close IN;
    return $seqs;
}

###################################################
sub pushSeq {
    my $seqs = shift;
    my $seq  = shift;
    if( $seq and $seq->getSequence() ){
	push( @$seqs, $seq );
    }
}

###################################################
sub instantiateSequence {
    my $self = shift;
    return FASTA::Sequence->new();
}

###################################################
sub output {
    my $filename = shift or croak "Output file name is not specified.";
    my $seqs = shift or croak "FASTA sequences are not specified.";
    open OUT, ">$filename" or croak "Can't open $filename to write.";
    foreach my $seq (@$seqs){
	print OUT getLines($seq);
    }
    close OUT;
}


###################################################
sub getLines {
    my $seq   = shift;
    my $lines = '>' . $seq->getTitle() . "\n";
    my $i;
    for( $i=0; $i<$seq->getLength() ; $i+=$numCharactersPerLine ){
	if( $i+$numCharactersPerLine<$seq->getLength() ){
	    $lines .= substr( $seq->getSequence(), $i, $numCharactersPerLine )
		. "\n";
	} else {
	    $lines .= substr( $seq->getSequence(), $i ) . "\n";
	}
    }
    return $lines;
}

1;
