#!/usr/bin/perl
#
# Ex 8.6, pg 180 in "Beg. Perl for Bioinf"
#
# Write a subroutine that checks an array of data
# and returns true if its in FASTA format.
#
# See pg 170 and 171 for routines
# that read this file format and
# return the data - assuming its in the right format.
#

my $filename = "fasta_example.dna";
my @data     = get_file_data($filename);
my $sequence = extract_sequence_from_fasta_data(@data);
my $length   = length($sequence);
print qq{
 FASTA file is '$filename'.
 Sequence length is $length.

};
print_sequence($sequence, 40);

# Usage: if (is_fast(@data)){ ... }
#  Return true if the given lines of data are in legal FASTA form;
#  false otherwise.
sub is_fasta {
 my @data = @_; 
 foreach my $line (@data){
   next if m/^>/;    # This line is OK if it starts with a ">" character.
   return 0 if ...;  # Fail if there's a character that isn't legal.
 }
 return 1;  # Nothing illegal was seen, so the file is OK.  Return true.
}

# -------------------------------------------------------------------------
# -- Some subroutines from Tinsdale chap 8, and BeginPerlBioinf.pm
# --
# --    @data = get_file_data('filename');
# --    $seq  = extract_sequence_from_fasta_data(@data);
# --    print_sequence($seq, 60);  # formatted length of each line to print
# --    
# -- I've edited the style a bit.  - Jim M.
# ---------------------------------------------

# A Subroutine to Read FASTA Files
sub get_file_data {
    my($filename) = @_;
    my @filedata = (  );     # Initialize variables
    unless( open(GET_FILE_DATA, $filename) ) {
        print STDERR "Cannot open file \"$filename\"\n\n";
        exit;
    }
    @filedata = <GET_FILE_DATA>;
    close GET_FILE_DATA;
    return @filedata;
}

# A subroutine to extract FASTA sequence data from an array
sub extract_sequence_from_fasta_data {
    my(@fasta_file_data) = @_;
    my $sequence = '';  # Declare and initialize variables
    foreach my $line (@fasta_file_data) {
        if ($line =~ /^\s*$/) {		# discard blank line
            next;
        } elsif($line =~ /^\s*#/) {	# discard comment line
            next;
        } elsif($line =~ /^>/) {	# discard fasta header line
            next;
        } else {			# keep line, add to sequence string
            $sequence .= $line;
        }
    }
    # remove non-sequence data (in this case, whitespace) from $sequence string
    $sequence =~ s/\s//g;
    return $sequence;
}

# A subroutine to format and print sequence data 
sub print_sequence {
    my($sequence, $length) = @_;
    # Print sequence in lines of $length
    for ( my $pos = 0 ; $pos < length($sequence) ; $pos += $length ) {
        print substr($sequence, $pos, $length), "\n";
    }
}

