#!/usr/local/bin/perl
# Usage: mask.pl masked.file quality.file > STDOUT

use strict;

my $fasta_file = $ARGV[0] || die "Specify a fasta file\n";
my $qual_file = $ARGV[1];

my ($id,%seq_list,%qual_list);
my $seq;

#-------------------------------------------------------------#
# Read fasta
open(FASTA,$fasta_file) || die "Cannot open fasta file $fasta_file\n";
while(<FASTA>) {

	if (/^>(\S+)/) {

		$seq_list{$id} = $seq if ($seq);
		$seq = undef;
		$id = $1;
		next;
	}
	
	chomp;
	$seq .= $_;
}
$seq_list{$id} = $seq if ($seq);
$seq = $id = undef;

#-------------------------------------------------------------#
# Read quality
if ($qual_file) {
	
	open(QUAL,$qual_file) || die "Cannot open fasta file $qual_file\n";
	while(<QUAL>) {

		if (/^>(\S+)/) {

			$qual_list{$id} = $seq if ($seq);
			$seq = undef;
			$id = $1;
			next;
		}
	
		chomp;
		$seq .= "$_ ";
	}
	$qual_list{$id} = $seq if ($seq);
}

#-------------------------------------------------------------#
# Clean files from 'X'
open(FASTA,">$fasta_file.clean");
open(QUAL,">$qual_file.clean") if ($qual_file);

foreach $id (keys %seq_list) {

	my ($i,$max,$len);
	my @size;
	my ($x,$y);
	my @seq = split /(X)/,$seq_list{$id};
	
	for ($i=0; $i<scalar(@seq); $i++) {

		$size[$i] = length($seq[$i]);
		
		if ($size[$i] > $len) {

			$max = $i;
			$len = $size[$i];
		}
	}
	
	print FASTA ">$id\n";
	
	while (length($seq[$max])>0) {
                
                my $out = substr($seq[$max],0,60);
                substr($seq[$max],0,60) = '';
                print FASTA "$out\n";
        }
	
	if ($qual_file) {
		
		for ($i=0; $i<$max; $i++) {

			$x+= $size[$i];
		}
		$y = $x+$size[$max]-1;
		$x = $x+1;
		
		my @qual = split /\s+/,$qual_list{$id};
		
		print QUAL ">$id\n";
		
		for ($i=$x;$i<$y;$i++) {
			
			print QUAL "$qual[$i] ";
		}
		print QUAL "\n";
	}
}
