#!/usr/bin/perl

# Program to split sequences at runs of NNNNs
# Useful to see if this improves an assembly
# USAGE: fasta_split_Ns.pl <input fasta> <output fasta>

use strict;
use warnings;

my $input_fasta = $ARGV[0];
my $output_fasta = $ARGV[1];

# Parse input fasta
my %sequences;
my $last_seqname;
my $last_seq;
open (INPUT, "<$input_fasta") or die "\nCouldn't open $input_fasta\n";
while (<INPUT>)
{
	my $line = $_;
	chomp $line;
	if (substr($line, 0, 1) eq ">")
	{
		if (defined $last_seqname)
		{
			$sequences{ $last_seqname } = $last_seq;
		}
		my @linearray = split (" ", $line);
		$last_seqname = substr($linearray[0], 1);
		$last_seq = "";
	} else {
		$last_seq = $last_seq . uc($line);
	}
}
close INPUT;
# For last sequence
$sequences{ $last_seqname } = $last_seq;

# Split sequences and output
open (OUTPUT, ">$output_fasta") or die "\nCouldn't open $output_fasta\n";
foreach my $sequence (keys %sequences)
{
	my @sequencearray = split (/N+/, $sequences{ $sequence });
	my $sequence_counter = 1;
	foreach my $seq_chunk (@sequencearray)
	{
		my $seq_header = ">" . $sequence . "_" . $sequence_counter;
		print OUTPUT "$seq_header\n";
		print OUTPUT "$seq_chunk\n";
		$sequence_counter++;
	}
}
close OUTPUT;
