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

my $numCharactersPerLine = 60;
my $MILLION = 1000000;

###################################################
sub new {
    my $pkg = shift;
    my $prefix = shift;
    bless {
	filename => undef, 
	fileHandler => undef, 
	numReads => 0,
	prefix => $prefix
    }, $pkg;
}

###################################################
sub open {
    my $self = shift;
    my $filename = shift or croak "File name is not specified.";
    $self->{filename} = $filename;
    open $self->{fileHandler}, ">$filename" 
	or croak "Can't open $filename to write.";
    print $self->{prefix} . " "
	. "Outputting to a FastA file...\n"
	. "\tfilename = " . $filename . "\n";
}

###################################################
sub close {
    my $self = shift;
    close $self->{fileHandler};
    print $self->{prefix} . " "
	. "\t" . $self->{numReads} . " sequences were output to "
	. $self->{filename} . ".\n"
	. "...done.\n\n";
}

###################################################
sub sendSequence {
    my $self = shift;
    my $seq  = shift;
    my $fh   = $self->{fileHandler};
    print $fh getLines( $seq );
    ++$self->{numReads};
    $self->progressReport();
}

###################################################
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;
}

###################################################
sub progressReport {
    my $self = shift;
    if( $self->{numReads} % 1000000 == 0 ){
	print $self->{prefix} . " "
	    . "\t" . $self->{numReads}/1000000
	    . " million sequences were output to "
	    . $self->{filename} . ".\n";
    }
}

1;

