#! /usr/bin/perl

#sliding_fasta.pl
#Gene W. Tyson, modified minutely by V. Rich

use strict;

### Input files ###

my $n_args = @ARGV;

if ($n_args != 3) {
    print "\nThis program takes a fasta file and using a sliding window\n";
    print "reports sequences for fragments of a desired length and overlap.\n";
    print "Usage: ./sliding_fasta.pl [fasta file] [length of sequence] [overlap] \n\n";
    exit;
}

open (CONTIGS, $ARGV[0]) || die "Couldn't open $ARGV[0]\n";
open (OUT, "> $ARGV[0]_tiled.fna");

$/= ">";

while (my $fasta = <CONTIGS>) {
    chomp $fasta;
    next unless $fasta;
    my ($name, @sequence) = split (/\n/, $fasta);
    my $seq = join "", @sequence;
    
    my $count = 1;
    my $x;
    for ($x = 0; $x < length($seq) - $ARGV[1]; $x+=$ARGV[2]) {
	my $final_pos = $x + $ARGV[1];
	my $sub_seq = substr($seq,$x,$ARGV[1]);
	print OUT ">", $name, "_", $count, ,"_", $x,"-",$final_pos,"\n";
	print OUT "$sub_seq\n";
	$count++;
    }
}
close CONTIGS;
close (OUT); 
