#!/usr/bin/perl
use strict;
use List::Util 'shuffle';

my $filename;
my @all_lines;
my @total_seq;
my @new_seq;
my @output;

##################
### Data input ###
##################

print "\n\n #############################\n";
print " ### Single Base Shuffling ###\n";
print " #############################\n\n";
print " This program shuffles N-fold times original DNA sequences\n conserving the base composition of the original sequences\n\n";
print " Enter the filename of the input DNA sequences: ";

my $dna_filename = <STDIN>;                               
chomp $dna_filename;

unless ( open(DNAFILE, $dna_filename) ) 
{   print "Cannot open file \"$dna_filename\"\n";
	die;
}

@all_lines = <DNAFILE>;

close DNAFILE;

print " Enter the number of shufflings of the original sequences(ex: 1, 2, 3, .....):= ";
my $frequency = <STDIN>;
open my $ofh, '>','single-base-shuffling-output.txt';

#################
### shuffling ###
#################

for(my $i=0;$i<@all_lines;$i++) {
  chomp $all_lines[$i];
  
  if(substr($all_lines[$i],0,1) eq ">"){
        } else {
          $filename = join "", "$filename", "$all_lines[$i]";
        }
}

for(my $i=0;$i<length($filename);$i++) {
  $total_seq[$i]=substr($filename,$i,1);
}

for(my $round=0;$round<$frequency;$round++)
{
  @new_seq = shuffle(@total_seq);

  for(my $i=0;$i<@all_lines;$i++) {
    chomp $all_lines[$i];

     if(substr($all_lines[$i],0,1) eq ">"){
        print $ofh "$all_lines[$i]\n"
       } else {
         my $num=length($all_lines[$i]);
         for(my $s=0;$s<$num;$s++) {
           $output[$s]=shift(@new_seq);
           }
            @output = join '',@output;
            print $ofh "@output\n";
        }
   }
}

print " Please see the results in the output file \"single-base-shuffling-output.txt\"\n\n";

### END ###