#!/bin/csh -f
set stack=$1
set CTFstack=$2
set tiltfile=$3
set Nprocs=32
set Nimgs=25
echo Stacked tilt series $stack containing $Nimgs images
set j=0
set i=1
while ($i <= $Nimgs)
    set i3=`printf "%03d" $i`
    set tiltangle=`head -n $i $tiltfile | tail -n 1`
    echo Correcting image $i for the CTF, tilt angle = $tiltangle
    newstack -verbose 0 -secs $j $stack /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__image$i3.mrc > __ctfimage$i3.log
    set running=`ps -c | grep CTFcorrect.exe | wc -l | awk '{printf("%d",$1+1)}'`
    if($running < $Nprocs) then
        /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0007/stack/CTFcorrect.csh /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__image$i3.mrc /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage$i3.mrc $tiltangle >> /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage$i3.log  ; rm -f __image$i3.mrc &
    else
        /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0007/stack/CTFcorrect.csh /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__image$i3.mrc /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage$i3.mrc $tiltangle >> /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage$i3.log  ; rm -f __image$i3.mrc
    endif
@ j ++
@ i ++
end
wait
newstack /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage???.mrc $CTFstack
cat /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage???.log > /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//$CTFstack.log
#rm -f /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage???.mrc*  /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__image???.mrc* /gpfs/appion/jchase/16sep28d/protomo_alignments/tiltseries0005/stack//__ctfimage???.log
