#! /usr/bin/perl -w

my $FIELD_LEN = 8;
# my $factor = 0.95;

my $fin = $ARGV[0];
my $fout = $ARGV[1];
my $factor = $ARGV[2];


open(FIN, "$fin") || die "Cannot open input $fin : $!\n";
my @lines = <FIN>;
close(FIN);

my $sumx=0.0;
my $sumy=0.0;
my $sumz=0.0;
my $nca=0;
for(@lines) {
	next unless /^ATOM/;
	my $type=substr($_,12,4);
	if($type eq " CA "){ # pdb line format, e.g: ATOM      2  CA  MET     1     489.230 945.691 891.975  1.00  5.00
		my $xpos=substr($_,30,8);
		if($xpos=~/(-?\d+\.?\d+)/){ $xpos=$1; }	
		$sumx += $xpos;
	
		my $ypos=substr($_,38,8);
		if($ypos=~/(-?\d+\.?\d+)/){ $ypos=$1; }	
		$sumy += $ypos;

		my $zpos=substr($_,46,8);
		if($zpos=~/(-?\d+\.?\d+)/){ $zpos=$1; }	
		$sumz += $zpos;

		$nca++;
	}			

}

my $x0 = $sumx/$nca;
my $y0 = $sumy/$nca;
my $z0 = $sumz/$nca;

open(FOUT, "> $fout") || die "Cannot open output $fout : $!\n";
for(@lines) {
	next unless $_=~/^ATOM/;

	my $xpos=substr($_,30,8);
	if($xpos=~/(-?\d+\.?\d+)/){ $xpos=$1; }	
	my $x1 = $x0 + $factor*($xpos-$x0);

	my $ypos=substr($_,38,8);
	if($ypos=~/(-?\d+\.?\d+)/){ $ypos=$1; }	
	my $y1 = $y0 + $factor*($ypos-$y0);

	my $zpos=substr($_,46,8);
	if($zpos=~/(-?\d+\.?\d+)/){ $zpos=$1; }	
	my $z1 = $z0 + $factor*($zpos-$z0);

	my $trans_line = $_;
	my $xfield = sprintf("% ${FIELD_LEN}s", substr($x1,0,$FIELD_LEN-1));
	substr($trans_line, 30,8) = $xfield;		
	my $yfield = sprintf("% ${FIELD_LEN}s", substr($y1,0,$FIELD_LEN-1));
	substr($trans_line, 38,8) = $yfield;		
	my $zfield = sprintf("% ${FIELD_LEN}s", substr($z1,0,$FIELD_LEN-1));
	substr($trans_line, 46,8) = $zfield;

	print FOUT $trans_line;
}
close(FOUT);

print "Structure from $fin is shrunk by the factor of $factor and written to $fout\n";
