#!/usr/bin/perl

## atomtype    num     mean    dev     min     max
#        C3    14583   9.372   0.634   7.223  13.748

$numres = 21;

while ($line = <STDIN>)  {
    chop($line);
    @vols = split(' ', $line);
    $nv = @vols;
    if ($vols[0] eq "#")  {  # broke of conditional to avoid header line
	if($vols[1] eq "for")  {
	    $ll = $nv-1;
	    $resfile = $vols[$ll];
	}
    } else {
	$atom = $vols[0];
	$atomNum{$atom} = $vols[1];
	$atomVol{$atom} = $vols[2];
	$atomDev{$atom} = $vols[3];
	$atomMin{$atom} = $vols[4];
	$atomMax{$atom} = $vols[5];
    }
}

print "# used residue typefile $resfile\n";
print "   atom  Count  Mean volume    SD       SD(\%)    Minimum  Maximum\n";

open(RES,$resfile) || die "couldn't open or find $resfile\n";
$jj=0;
while($jj<$numres)  {
    $rline = <RES>;
    chop($rline);
    @res = split(' ', $rline);
    $nres = @res;
    if (  $nres > 0 )  {
	print "$res[0]\n";
	$Tnum = 0.0; $Tvol = 0.0; $Tdev = 0.0;
	for($ii=0;$ii<$res[1];$ii++)  {
	    $rline = <RES>;
	    @atoms = split(' ', $rline);
	    if( !($atoms[1] =~ /=/) )  {
		$atom = $atoms[1];
		if($atomVol{$atom} == 0.0)  {
		    $SDpercent = 0.0;
		} else  {
		    $SDpercent = 100*($atomDev{$atom}/$atomVol{$atom});
		}
		printf("   %-4s %7d   %7.3lf   %7.3lf   %7.3lf    %7.3lf  %7.3lf\n",
		       $atoms[0], $atomNum{$atom}, $atomVol{$atom}, $atomDev{$atom},
		       $SDpercent, $atomMin{$atom}, $atomMax{$atom});
		$Tnum += $atomNum{$atom};
		$Tvol += $atomVol{$atom};
		$Tdev += $atomDev{$atom}*$atomDev{$atom};

		if($res[0] eq "CYS" && $atoms[0] eq "SG")  {
		    $Cysteine = 1;
		} else {
		    $Cysteine = 0;
		}
	    }
	}
	$jj++;
	if($Tnum == 0.0 || $Tvol == 0.0)  { 
	    $Tsd = 0.0; $Tsdp = 0.0;
	} else { 
	    $Tsd = sqrt($Tdev); $Tsdp = $Tsd/$Tvol; 
	}
	printf("\n Total %8.0lf   %7.3lf   %7.3lf   %7.3lf\n\n", $Tnum, $Tvol, $Tsd, $Tsdp);
    }
}				
close(RES);	


    
