#!/bin/csh -f
#
#   Display file header
#
#help
#help frealign_calc_reconstructions - calculate 3D reconstructions
#help Usage: frealign_calc_reconstructions <cycle> [<first particle> <last particle>]
#help Control parameters must be set in local mparameters file
#
set working_directory	= `pwd`

if ( ! -e mparameters ) then
  echo
  echo "ERROR: no mparameters file."
  echo "Terminating..."
  echo
  exit
endif

set raw_images		= `grep raw_images_low mparameters | awk '{print $2}'`
if ( $raw_images == "" ) set raw_images = `grep raw_images mparameters | awk '{print $2}'`
set raw_images = `echo ${raw_images:r}`
ls $raw_images.* >& /dev/null
if ( $status ) then
  set raw_images = ${working_directory}/${raw_images}
endif
ls $raw_images.* >& /dev/null
if ( $status ) then
  echo 
  echo "ERROR: particle image stack not found."
  echo "Terminating..."
  echo
  exit
endif

if ( ${1} == "" ) then
  echo
  echo "ERROR: cycle number missing"
  echo "Terminating..."
  echo
  exit
endif

set SCRATCH		= `grep scratch_dir mparameters | awk '{print $2}'`
if ( $status || $SCRATCH == "" ) then
  set SCRATCH		= ${working_directory}/scratch
endif
if ( ! -d $SCRATCH ) then
  mkdir $SCRATCH
endif
#
if ( ! -d $SCRATCH ) then
  echo "ERROR: cannot create scratch directory"
  exit
endif

cp mparameters $SCRATCH/mparameters_run

set bin_dir             = `grep frealign_bin_dir $SCRATCH/mparameters_run | awk '{print $2}'`
if ( $status || $bin_dir == "" ) then
  set bin_dir           = `which frealign_v9.exe`
  set bin_dir           = ${bin_dir:h}
endif
#
set extension		= `ls $raw_images.* | head -1`
if ( $extension == "" ) then
  set raw_images = ${working_directory}/${raw_images}
  set extension		= `ls $raw_images.* | head -1`
endif
set extension		= `echo ${extension:e}`
if ( ${2} == "" || ${3} == "" ) then
  set first = 1
  set last = `${bin_dir}/fheader.exe ${raw_images}.${extension} | grep --binary-files=text NX | awk '{print $6}'`
else
  set first = ${2}
  set last = ${3}
endif

echo "Starting reconstruction..." > frealign.log
echo "Starting reconstruction..."

echo "monitor reconstruct" > $SCRATCH/pid.log
${bin_dir}/mult_reconstruct.com ${first} ${last} ${1} >& $SCRATCH/mult_reconstruct.log &
set pid = $!
${bin_dir}/monitor_frealign.com >& $SCRATCH/monitor_frealign.log $pid &

