#!usr/bin/perl
use strict;
use List::Util qw(sum);
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(FORMAT, SMOOTH, IntX);

#####################################################################
sub FORMAT
	{
	my @tmp = @_;
	my $pdb = $tmp[0];
	my $file = $tmp[0];
	
	#~ print "$file\_all_SMD.dat\n";
	
#	print "~/Work/SMD/Wt/dat/$file\_all_SMD.dat\n";
#	print "~/Work/SMD/Wt/dat/$file\_SMD_formated.dat
	#~ open(SMD, "< /home/lyman/Work/SMD/Wt/dat/$file\_all_SMD.dat");
	open(SMD, "< ../dat/$file\_all_SMD.dat");
	open(OUT, "> ../dat/$file\_SMD_formated.dat");
	while(<SMD>)
		{
		my $in = $_;
		my @break = split(/ +/,$in);
		my $step = $break[1];
		my $x = $break[2];
		my $y = $break[3];
		my $z = $break[4];
		my $Fx = $break[5];
		my $Fy = $break[6];
		my $Fz = $break[7];
		chomp($Fz);
		my $F = sqrt(($Fx * $Fx) + ($Fy * $Fy) + ($Fz * $Fz));
		
		#print "$step	$F\n";
		
		print OUT "$step	$F\n";
		}
	
	close(OUT);
	
	}

#####################################################################
sub SMOOTH
	{
	my @tmp = @_;
	my $pdb = $tmp[0];
	my $file = $tmp[0];
	#  2N + 1 must be odd 
	# $N = 100 makes it so that we smooth out the fS steps into the pS scale (force output is every 10 fS).
	
	chomp($pdb);
	chomp($file);
		
	my $N = 100;
	
	# so that $i - $N is not negative.
	
	my $i = $N;
	my $ys = 0;
	
	open(DAT, "< ../dat/$file\_SMD_formated.dat");
	open(OUT, "> ../dat/$file\_SMD_smooth.dat");
	my @noisy_data;
	
	
	while(<DAT>)
		{
		$_;
		my $in = $_;
		if ($in  =~ m/^\d/)
			{
			my @break = split(/\t/,$in);
			my $value = $break[1];
			chomp ($value);
			push(@noisy_data, $value);
			}
		}

	for(my $counter = $N; $counter <= @noisy_data - $N; $counter++)
		{
		my $A = (1/(2*$N+1));
		my $B = 0;
		$ys = 0;
		for(my $M = (-1 * $N); $M <= $N; $M++)
			{
			my $index = $i + $M;
			$B = $B + $noisy_data[$index];
			}
		$ys = $A * $B;
		print OUT "$i	$ys\n";
		$i++;
		}

	close(OUT);
	close(DAT);		

	}


#####################################################################
sub MaxForce
	{
	my @tmp = @_;
	my $pdb = $tmp[0];
	my $file = $tmp[0];
	chomp($pdb);
	chomp($file);
	open(DATA, "< ../dat/$file\_SMD_smooth.dat");
	
	my @force = ();
	my $i = 0;
	while(<DATA>)
		{
		my $in = $_;
		my @break = split(/\t/, $in);
		if($i > 200 && $i < 2000)
			{
			push @force, $break[1];
			}
			$i ++;
		
		}
	
	my @force_sorted = sort {$b <=> $a} @force;
	
	my $max	= $force_sorted[1];
	chomp($max);
	
#	print "Max Force = $max pN\n";
	
	return($max);	
	
	}















1;

