#!/bin/tcsh
set file=$1
set numstruc = `grep -c ENERGY $file`
set numatom = `grep -c ATOM $file`
set numatom = `echo "($numatom / $numstruc)+3" | bc`
set i = 1
set j = 2
echo "TER" > TER

set num1 = `echo $numatom + 1 | bc`
set num2 = $num1
rm structur*.pdb

echo $i $numstruc $numatom $num1 $num2

rm tempo
echo "NUMATOM" $numatom
grep -A $numatom ENERGY $file > tempo

while ($i <= $numstruc)
echo a$i
tail -99999999999 tempo | head -$num2 | tail -$num1 > structur$i.pdb
set num2 = `echo $num2 + $num1 +1 | bc`
echo b$i $num1 $num2
set i = `echo $i+1 | bc`
end

set i = 1
set j = 2
while ($j <= $numstruc)
grep -v TER structur$j.pdb > structure$i.pdb
grep " A " structure$i.pdb > structure${i}a.pdb
egrep " B | C " structure$i.pdb > structure${i}b.pdb
/users2/vetinari/pulchra306/pulchra -q -f -g structure${i}a.pdb
/users2/vetinari/pulchra306/pulchra -q -f -g structure${i}b.pdb

grep "ATOM" structure${i}a.rebuilt.pdb > temps1
grep "ATOM" structure${i}b.rebuilt.pdb > temps2

awk -F "" '{print $1$2$3$4$5$6$7$8$9$10$11$12$13$14$15$16$17$18$19$20$21"A"$23$24$25$26$27$28$29$30$31$32$33$34$35$36$37$38$39$40$41$42$43$44$45$46$47$48$49$50$51$52$53$54}' temps1 > temps1a
awk -F "" '{print $1$2$3$4$5$6$7$8$9$10$11$12$13$14$15$16$17$18$19$20$21"B"$23$24$25$26$27$28$29$30$31$32$33$34$35$36$37$38$39$40$41$42$43$44$45$46$47$48$49$50$51$52$53$54}' temps2 > temps2a


cat temps1a TER temps2a > structure${i}.pdb

set i = `echo $i+1 | bc`
set j = `echo $j+2 | bc`
end

rm TER tempo temps1 temps2 temps1a temps2a structure*a*.pdb structure*b*.pdb

foreach file (structur[0-9].pdb structur[0-9][0-9].pdb)
rm $file
end
