; Controls refinement of a reconstruction
;
; SOURCE: refine.pam        New                  ArDean Leith Nov  2000
;                           Rewritten            ArDean Leith Mar  2004
;                           [] variables         ArDean Leith Dec  2005
;                           Ampenhance fixed     ArDean Leith May  2006
;                           More stacks          ArDean Leith Dec  2006
;
; PURPOSE: Controls refinement 
;
; MASTER COPY: /net/bali/usr1/spider/docs/techs/recon/newprogs/
;
; I/O Registers and files are set in: refine settings refine settings.pam.pam); INPUT REGISTERS:
;
; INPUT REGISTERS:
;    [maxspfreq]              Maximum spatial freq[a-1] (used in prepare)
;    [radius]                 Radius of structure
;    [alignsh]                Shift allowed is +- this value
;    [prj-radius]             Radius of structure for projection
;    [iter1]                  Starting iteration
;    [iter-end]               Ending   iteration
;    [lambda]                 Lambda(angstroms) (used in prepare)
;    [small-ang]              Small angle refinement flag (1 is true) 
;    [converg]                Convergence criterion percentage
;
; INPUT FILES:
;    [params]                 input/params           Parameter doc. file
;    [order_select]           input/order_select     Group selection file
;    [start_vol]              input/vol01            Initial starting volume
;    [sel_particles]          input/select_***       Particle selection files 
;    [start_group_align]      input/align_01_***     Alignment parameter input file 
;    [unaligned_images]       input/data***          Unaligned stacked image files
;    [start_aligned_images]   input/dala01_***       Aligned stacked image files
;
; PROCEDURES CALLED:
;    refine_settings          refine_settings.pam
;    prepare                  prepare.pam
;
;    grploop                  grploop.pam    OR           
;    smangloop                smangloop.pam            
;
;    mergegroups              mergegroups.pam
;    ... enhance              enhance.pam
;    ... saveresp             saveresp.pam
;    endmerge                 endmerge.pam
; 
;    endrefine                endrefine.pam  
;    ... saveresp             saveresp.pam
;
; ---------------------------------------------------------------------

MD
TR OFF                       ; Loop info turned off
MD
VB OFF                       ; File info turned off
MD
() OFF                       ; No need for () in DO loops          
MD
SET MP                       ; Use all available OMP processors
0

; Input initial parameters & file names
@refine_settings([maxspfreq],[radius],[alignsh],[prj-radius],[iter1],[iter-end],[lambda],[small-ang],[winsize],[converg])

IF([iter1].LE.1) THEN
   ; Prepare input files (only needs to be done once) 
   @prepare([maxspfreq],[lambda],[iter1])
ENDIF

MY FL

;  Loop over all iterations
DO LB1 [iter]=[iter1],[iter-end]

   RR S [ang-step]
   ([ang-steps])           ; Angular step for projection angle (varies with iteration)
   [iter]
   RR S [ang-limit]        ; Restriction on angular degree search (varies with iteration)
   ([ang-limits])
   [iter]
   RR S [ampenhance]       ; Amplitude enhancement flag (varies with iteration)
   ([amp-enhance-flags])
   [iter]

   FT                      ; Fourier on current volume 
   [current_vol]           ; Volume produced by previous iter.   
   [iter_vft]              ; Fourier of volume (used by all groups on this iter. in grploop) 

   ; Create reference angle & ref. selection doc files for this iteration 
   DE
   [iter_ang_voea]         ; Ref. angles doc file
   DE
   [iter_select_voea]      ; Ref. angle selection doc file 

   IF ([small-ang].EQ.0) THEN ; Regular angle refinement
      VO EA [num-angles]   ; Sets [num-angles] to number of reference projections
      [ang-step]           ; Angular step (varies with iteration)
      (0,90.0)             ; Angles
      (0,359.9)            ; Angles
      [iter_ang_voea]      ; Create ref. angles doc file    (output)

   ELSE                    ; Small angle refinement
      VO EA [num-angles]   ; Sets [num-angles] to number of reference projections
      [ang-step]           ; Angular step 
      (0,[ang-limit])      ; Small Angles
      (0,0)                ; Small Angles
      [iter_ang_voea]      ; Create ref. angles doc file    (output)
   ENDIF

   DOC CREATE              ; Create ref. angle selection doc file   
   [iter_select_voea]      ; Ref. angle selection doc file  (output)
   (1)                     ; First register
   1-[num-angles]          ; Select all angles

   UD N [num-grps]         ; Get number of defocus groups
   [order_select]

   ; Process all defocus groups one by one
   [num-big] = 0           ; Number of large proj. angle displacements
   DO LB3 [i]=1,[num-grps]
      UD S [i],[grp]       ; Get defocus group number from unsorted list  
      [order_select]

      VM
      date  '+ TIME: %x  %X'
      VM
      echo " Processing group: {***[grp]}"
      MY FL                ; Flush results file
 
      ; grploop/smangloop returns [stop] 
      IF([small-ang].EQ.0)THEN  ; Runs main refinement smangloop tasks
         @grploop([ang-step],[ang-limit],[radius],[alignsh],[prj-radius],[iter],[grp],[stop],[maxspfreq])
      ELSE
         @smangloop([ang-step],[radius],[alignsh],[prj-radius],[iter],[grp],[stop],[iter1],[maxspfreq])
      ENDIF

      ; Check size of projection angular changes
      ; [stop] returns % of images whose proj. angle moved by >1.5*[ang-step]
      IF([stop].GT.[converg])  [num-big]=[num-big]+1  ; Excessive ang. change for this group  

      MY FL                  ; Flush results file
   LB3
   UD E                      ; Finished with incore doc file

   VM
   echo " Iteration: {**[iter]} Excessive proj. ang. changes in: {***[num-big]} groups"
 
   ; If projection angular changes were small in all groups, can stop now
   IF([num-big].EQ.0) GOTO LB71  

   ; Consolidate data for CTF corrections
   @mergegroups([maxspfreq],[iter],[ampenhance])

   DE                       ; Delete vft file.
   [iter_vft]               ; Used by all groups this iter.  

   DE                       ; Delete ref. angle selection file
   [iter_select_voea]       ; Ref. angle selection doc file 

   MY FL                    ; Flush results file
LB1
LB71

VM
echo ' ' ; echo " Alignment halting after iteration: {***[iter]}"
VM
date '+ TIME: %x  %X'
VM
echo ' '

DO [i]=1,[num-grps]     
  UD IC [i], [grp]         ; Get defocus group number from list
  [order_select]

  @endmerge([prj-radius],[grp],[iter])
ENDDO

UD ICE
[order_select]

; Prepare final resolution files
@endrefine([maxspfreq],[iter])    

VM
date '+ TIME: %x  %X'
VM
echo ' '

VM
echo " SUCCESS, FINISHED REFINEMENT"

EN
;