package Maasha::Fastq;

# Copyright (C) 2006-2009 Martin A. Hansen.

# 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
# of the License, or (at your option) any later version.

# 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.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

# http://www.gnu.org/copyleft/gpl.html


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


# Routines for manipulation of FASTQ files and FASTQ entries.

# http://maq.sourceforge.net/fastq.shtml


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


use warnings;
use strict;
use Data::Dumper;
use Maasha::Calc;
use vars qw( @ISA @EXPORT );

use constant {
    SEQ_NAME => 0,
    SEQ      => 1,
    SCORES   => 2,
};

@ISA = qw( Exporter );

use Inline ( C => <<'END_C', DIRECTORY => $ENV{ "BP_TMP" } );

int phred2score( char c )
{
    /* Martin A. Hansen, July 2009 */

    /* Converts a FASTQ/phred score in octal (a char) to a decimal score, */
    /* which is returned. */

    /* http://maq.sourceforge.net/fastq.shtml */

    int score = 0;

    score = ( int ) c - 33;

    return score;
}


int solexa2score( char c )
{
    /* Martin A. Hansen, July 2009 */

    /* Converts a Solexa score in octal (a char) to a decimal score, */
    /* which is returned. */

    /* http://maq.sourceforge.net/fastq.shtml */
    /* $Q = 10 * log(1 + 10 ** (ord($sq) - 64) / 10.0)) / log(10); */

    int score = 0;
    int ascii = ( int ) c - 64;

    score = 10 * log( 1 + pow( 10, ascii / 10 ) ) / log( 10 );

    return score;
}


char score2phred( int score )
{
    /* Martin A. Hansen, July 2009 */

    /* Converts a decimal score in decimal to an octal score (a char), */
    /* which is returned. */

    /* http://maq.sourceforge.net/fastq.shtml */

    char c;

    if ( score <= 93 ) {
        c = ( char ) score + 33;
    } else {
        c = ( char ) 93 + 33;
    }

//    printf( "score: %d   char: %c\n", score, c );

    return c;
}


void lowercase_low_scores( char *seq, char *scores, int threshold )
{
    /* Martin A. Hansen, July 2009 */

    /* Given a sequence string and a score string (in FASTQ/Phread range) */
    /* lowercases all residues where the decimal score is below a given threshold. */

    int i = 0;

    for ( i = 0; i < strlen( seq ); i++ )
    {
        if ( phred2score( scores[ i ] ) < threshold ) {
            seq[ i ] = tolower( seq[ i ] );
        }
    }
}


void solexa2phred( char *scores )
{
    /* Martin A. Hansen, July 2009 */

    /* Convert Solexa scores to Phred scores for use with FASTQ format.*/

    int  i     = 0;
    int  score = 0;
    char c;

    for ( i = 0; i < strlen( scores ); i++ )
    {
        score       = solexa2score( scores[ i ] );
        c           = score2phred( score );

//        printf( "scores[i]: %c  score: %d  char: %c\n", scores[ i ], score, c );

        scores[ i ] = c;
    }
}


END_C


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


sub get_entry
{
    # Martin A. Hansen, July 2009.

    # Gets the next FASTQ entry from a given filehandle.

    my ( $fh,   # filehandle
       ) = @_;

    # Returns a list

    my ( $seq, $seq_name, $qual, $qual_name );

    $seq_name  = <$fh>;
    $seq       = <$fh>;
    $qual_name = <$fh>;
    $qual      = <$fh>;

    return unless $seq;

    chomp $seq;
    chomp $seq_name;
    chomp $qual;
    chomp $qual_name;

    $seq_name =~ s/^@//;

    return wantarray ? ( $seq_name, $seq, $qual ) : [ $seq_name, $seq, $qual ];
}


sub put_entry
{
    # Martin A. Hansen, July 2009.

    # Output a FASTQ entry to STDOUT or a filehandle.

    my ( $entry,   # FASTQ entry
         $fh,      # filehandle - OPTIONAL
       ) = @_;

    # Returns nothing.

    $fh ||= \*STDOUT;

    print $fh "@" . $entry->[ SEQ_NAME ] . "\n";
    print $fh $entry->[ SEQ ] . "\n";
    print $fh "+\n";
    print $fh $entry->[ SCORES ] . "\n";
}


sub fastq2biopiece
{
    # Martin A. Hansen, July 2009.
    
    # Converts a FASTQ entry to a Biopiece record, where
    # the FASTQ quality scores are converted to numerics.

    my ( $entry,     # FASTQ entry,
       ) = @_;

    # Returns a hash.

    my ( $record );

    $record->{ 'SEQ' }        = $entry->[ SEQ ];
    $record->{ 'SEQ_NAME' }   = $entry->[ SEQ_NAME ];
    $record->{ 'SCORES' }     = $entry->[ SCORES ];
    $record->{ 'SEQ_LEN' }    = length $entry->[ SEQ ];

    return wantarray ? %{ $record } : $record;
}


sub biopiece2fastq
{
    # Martin A. Hansen, July 2009.
    
    # Converts a Biopiece record to a FASTQ entry.

    my ( $record,   # Biopiece record
       ) = @_;

    # Returns a list.

    my ( $list );

    if ( exists $record->{ 'SEQ' } and exists $record->{ 'SEQ_NAME' } and exists $record->{ 'SCORES' } )
    {
        $list->[ SEQ_NAME ] = $record->{ 'SEQ_NAME' };
        $list->[ SEQ ]      = $record->{ 'SEQ' };
        $list->[ SCORES ]   = $record->{ 'SCORES' };
    
        $list->[ SCORES ] =~ s/(\d+);/chr( ( $1 <= 93 ? $1 : 93 ) + 33 )/ge;

        return wantarray ? @{ $list } : $list;
    }

    return;
}


# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
