([ang-step],[r2],[alignsh],[prj-radius],[iter],[grp],[pixsiz],[bp-type],[iter-end]) ; Small angle refinement group loop
 ;
 ; SOURCE: spider/docs/techs/recon1/Procs/smangloop.spi
 ;         New                                 ArDean Leith  Nov 2002
 ;         Rewrite                             ArDean Leith  Oct 2004
 ;         Avg CCROT degredations              ArDean Leith  Feb 2005
 ;         []                                  ArDean Leith  Dec 2005
 ;         More stacks                         ArDean Leith  Dec 2006
 ;         Removed iter1 parameter             ArDean Leith  Feb 2007
 ;         Filenames & UD NEXT                 ArDean Leith  Dec 2009
 ;         COG centering removed               ArDean Leith  Sep 2010
 ;         TF COR                              ArDean Leith  Nov 2010
 ;         For CTF corrected images            ArDean Leith  Oct 2013
 ;         For gold standard reconstruction    ArDean Leith  May 2014
 ; 
 ; PURPOSE: Small angle refinement group loop.  Runs for each group on each iteration.
 ;          Finds parameters ('AP REF') which align experimental images with 
 ;          projections from current reference volume,
 ;          rotationally aligns ('RT SF') images ,  and 
 ;          backprojects ('BP **') images into new volume.

 ; CALLED FROM: pub_refine_start OR   
 ;              refine.spi  
 ;
 ; REGISTERS AND FILES ARE SET IN: refine settings.spi
 ;
 ; INPUT REGISTERS:
 ;    [ang-step]             Angular step                    
 ;    [r2]                   Pixel radius of object used in alignment
 ;    [alignsh]              Shift allowed is +-[alignsh]
 ;    [prj-radius]           Radius (pixels) of structure for projection
 ;    [iter]                 Alignment step iteration counter  
 ;    [grp]                  Current defocus group                      
 ;    [pixsiz]               Pixel size                              
 ;    [bp-type]              Type of 'back projection'                              
 ;
 ;   '##' denotes iteration,  '##+' denotes next iteration, and '***' denotes group
 ; INPUT FILES:
 ;    [sel_parts_s]          input/select_***        Group particle selection files  (one/group)
 ;    [iter_refangs]         work/ref_angs_##        Ref. angles doc file            (one/iteration)       
 ;    [unaligned_images]     input/data_***          Unaligned stacked image files   (one-stack/group)
 ;    [ref_projs_s]          work/ref_projs_##_s@    Reference projections           (two/iteration)
 ;    [group_align_s]        final/align##_***_s@    Alignment parameter doc files   (two/iteration/group)    
 ;
 ; OUTPUT FILES:
 ;    [next_group_align_s]   final/align##+_***s@    Alignment parameter doc files   (two/iteration/group)
 ;    [next_group_vol_s]     work/vol_##+_***_s@     Group subset volumes            (two/iteration/group)
 ;    [next_group_vol]       work/vol##+_***         Reconstructed group volumes     (one/iteration/group)
 ;
 ;    [temp_out_images]      work/dala##+_***        Aligned stacked image file      (one/group)
 ;    [ang_vora]             final/angvora_##_***    Projection angles doc file      (one/group)        
 ;    [temp_ref_projs]       _5@                     Reference projections           (created & deleted)
 ;
 ; INLINE BUFFERS USED: _5@
 ;
 ; ----------------- END BATCH HEADER -------------------------------------

 SYS
   echo -n "  Starting: small-angle refine loop  Iteration: {%I0%[iter]}  Group:{%I3%[grp]} --- " ; date '+ %x  %X'

 [r1]        = 5.0                   ; First radius for 'AP REF' (Can alter this)
 [big_move]  = 1.5 * [ang-step]      ; Angular distance for big moves.
 [next-iter] = [iter]+1
 
 FI H [maxim],[nx],[ny]              ; Find total number of images (not [numparts])
   [unaligned_images]@               ; Input file needed                  (input)
   MAXIM, NX, NY                     ; Max. image number, image size

 UD N [num-refs]                     ; Get number of reference images used
   [ang_voea]                        ; Reference images angles doc file (input)

 MS                                  ; Make MT inline stack for ref. projections
   [temp_ref_projs]                  ; Empty stack                        (output)
   [nx],[nx],1                       ; Image size
   [num-refs]                        ; Number of images allowed in stack

 MY FL                               ; Flush results file

 DE                                  ; Delete existing files  
   [next_group_align]_s1             ; Alignment parameter doc file   (deleted)
 DE                                  ; Delete existing files  
   [next_group_align]_s2             ; Alignment parameter doc file   (deleted)

 ; Make header for next group align doc files 
 SD /PSI, THE, PHI, REF, EXP, ANG, SX, SY, NPROJ, DIFF, CCROT, ANG, SX, SY, MIR-CC
    [next_group_align]_s1            ; Alignment parameter doc file   (output)
 SD /PSI, THE, PHI, REF, EXP, ANG, SX, SY, NPROJ, DIFF, CCROT, ANG, SX, SY, MIR-CC
    [next_group_align]_s2             ; Alignment parameter doc file   (output)

 [num-big]    = 0                    ; Number of angular changes above iter. stop limit
 [toobig]     = 0                    ; Not OK to stop iterating
 [sum-ccrot]  = 0.0                  ; Sum of CCROT correlation coefficients
 [num-degred] = 0.0                  ; Number of CCROT degredations
 [sum-degred] = 0.0                  ; Sum of CCROT degredations
 [num-impr]   = 0.0                  ; Number of CCROT improvements
 [sum-impr]   = 0.0                  ; Sum of CCROT improvements
 [sum-diff]   = 0.0
 [num-imgs]   = 0                    ; Number of images in current group

 DO [s] = 1,2                        ; Loop over resolution subsets ---------------

   DO                                ; Loop over all particles
     UD NEXT [key],[img]             ; Get particle number  
       [sel_parts_s]                 ; Group particle selection file   (input) 
     IF ( [key] <= 0 ) EXIT          ; End of images in selection doc file
 
     [num-imgs] = [num-imgs] + 1     ; # of images in current group

     ; Format of alignment parameters doc file is:
     ;         PSI,THE,PHI,           REF#,EXP#, ANG,SX,SY,   NPROJ,DIFF,CCROT
     UD IC [img], [psi],[the],[phi],  [d],[exp], [d],[d],[d], [d],[d],[old-ccrot]
       [group_align_s]               ; Input alignment parameters doc file

     DE                              ; Delete  
       [ang_vora]                    ; angvora doc file                (removed)

     VO RAS                          ; Rotate projection dir.   
       [ang_voea]                    ; Relative angles file            (input)
       -[phi],-[the],-[psi]          ; Offset
       1, 0                          ; Psi set to zero
       [ang_vora]                    ; Doc file for angles to search   (output)

     ; Create stack holding set of reference projections from input volume.
     PJ 3Q                           ; Create ref. projections
      [vol]                          ; Current volume                  (input)  
      [prj-radius]                   ; Radius of computed object
      1-[num-refs]                   ; Ref. projection file numbers 
      [ang_vora]                     ; Angles in search area doc file  (input)
      [temp_ref_projs]******         ; Template for ref. projections   (output)

     ; Find ref. image matching exp. image.  Output to registers not doc file
     ;       PSI,THE,PHI,       REF#,EXP#, ANG,  SX, SY,    NPROJ,DIFF,     CCROT,  CURRENT_ALIGN
     AP REF  [psi],[the],[phi], [ref],[exp], [inp],[sx],[sy], [nproj],[diff], [ccrot], [t0],[t1],[t2],[t3]
       [temp_ref_projs]******         ; Template of existing ref. projections (input) 
       1-[num-refs])                  ; Ref. projection file numbers
       [alignsh]                      ; Shift search range
       [r1], [r2], 1                  ; First, last ring, & skip
       [ang_vora]                     ; Ref. angles file                   (input)
       SCR.{******[grp]}              ; No scratch file (usually will fit in-core)
       [unaligned_images]@******      ; Original unaligned  image stack    (input)
       [img]                          ; Current exp. image file number
       [group_align_s]                ; Alignment parameters doc file      (input)
       0                              ; Angular projection restriction
       N, Y                           ; No mirrored projection check,  align first 

     ;         PSI,THE,PHI,         REF#,EXP#, ANG,  SX,  SY,   NPROJ,DIFF,CCROT
     SD [img], [psi],[the],[phi],  [ref],[img],[inp],[sx],[sy], [num-refs],[diff],[ccrot], [t0],[t1],[t2],[t3]
       [next_group_align_s]                              ; Next align. doc file (output)

     IF ( [ccrot] < [old-ccrot] ) THEN
       [sum-degred]=[sum-degred]+([old-ccrot]-[ccrot]) ; Sum average CCROT degredation
       [num-degred]=[num-degred]+1                     ; Increment   CCROT degredations counter
     ELSE
       [sum-impr] = [sum-impr]+([ccrot]-[old-ccrot])   ; Sum average CCROT improvement
       [num-impr] = [num-impr]+1                       ; Increment   CCROT improvements counter
     ENDIF

     IF ( [diff] > [big_move]) [num-big]=[num-big]+1   ; Increment large displacement counter
     [sum-ccrot] = [sum-ccrot]+[ccrot]                 ; Sum rotational CCC (for average).
     [sum-diff]  = [sum-diff]+[diff]                   ; Sum of angular differences
      
     ; Apply combined transformation to original particle image
     RT SF                                             ; Rotate & shift
       [unaligned_images]@{******[img]}                ; Unaligned original images stack (input)
       [temp_out_images]{******[img]}                  ; Temp aligned exp. images stack  (output)
       [inp]                                           ; Inplane rotation angle
       [sx],[sy]                                       ; X & Y shift

   ENDDO                       ; End of loop over all particles --------------------

   ; Calculate new, refined subset volume using centered projections and 
   ; angles from align doc. file.  

   @refine-bp([iter],[iter-end],[grp],[s], [bp-type],[prj-radius])

   UD ICE                      ; Close this file here
     [group_align_s]           ; Doc file                         (closed)                 

 ENDDO                         ; End of loop over resolution subsets ----------------------------

 DE
   [ang_vora]                  ; Doc file                         (removed)
 DE                            ; Delete
   [temp_ref_projs]            ; Ref. projections file            (removed)
 DE                            ; Delete
   [temp_out_images]@          ; Aligned image stack              (removed)

 ; Find % of images showing excessive change in angular displacement
 [toobig]=100*[num-big]/[num-imgs]  ; % of images with excessive change in ang. displacement

 SYS
   echo " Iteration: {%I2%[iter]} Group: {%I3%[grp]}   Excessive changes: {%I3%[toobig]}%"

 [avg-ccrot]  = [sum-ccrot]/[num-imgs]                        ; Average CCROT 
 [avg-degred] = 0.0                                           ; Average CCROT degredation
 IF ( [num-degred] > 0)[avg-degred]=[sum-degred]/[num-degred] ; Average CCROT degredation
 [avg-impr]   = 0.0                                           ; Average CCROT improvement
 IF ([num-impr] > 0) [avg-impr] = [sum-impr]/[num-impr]       ; Average CCROT improvement
 [per-degred] = 100*[num-degred]/[num-imgs]                   ; Percent images with CCROT degredation
 [avg-diff]   = [sum-diff]/[num-imgs]                         ; Average angular difference

 SYS
   echo " CCROT degred.: {%I3%[per-degred]}%  Avg degred.: {%F8.2%[avg-degred]}  Avg improve: {%F8.2%[avg-impr]}"

 SD / %Large angles, Avg. Ang-diff,  Avg. CCROT, % degred.,  Avg degred.,  Avg improv.
   [next_group_align]                                         ; Alignment doc file   (output)
 SD -2, [toobig],[avg-diff],[avg-ccrot],[per-degred],[avg-degred],[avg-impr]
   [next_group_align]                                         ; Alignment doc file   (output)
 SD E                                                         ; Close doc file  
   [next_group_align]                                         ; Alignment doc file   (closed)
 
 RE
 ;