(x41,x42,x51,x52,x55,x56,x76,x77,x47,x74,x14) ; Small angle refinement group loop
;
; SOURCE: smangloop.pam -- Small angle refinement group loop    al Nov. 2002
;                                                               al Oct. 2004
;                                       exp images name bug     al Jan. 2005
;                                       BP align bug            al Feb. 2005
;                                       avg CCROT degredations  al Feb. 2005
; MASTER COPY: /net/bali/usr1/spider/docs/techs/recon/programs/
; 
; PURPOSE:    Runs for each defocus group on each iteration
;
; CALLED FROM: refine.pam and 
;              pub_starter.pam  
;
; REGISTERS AND FILES ARE SET IN: refine_settings.pam
;
; INPUT REGISTERS:
;    x41                     Angular difference stopping limit   
;    x42                     Angular search range      
;    x47                     Iteration ending flag   (returned)
;    x51                     Radius (pixels) of the structure
;    x52                     Image size
;    x55                     Shift allowed is +-x55
;    x56                     Radius (pixels) of structure for projection
;    x74                     Starting alignment iteration    
;    x76                     Alignment step iteration counter  
;    x77                     Current defocus group                      

; INPUT FILES:
;    input/order_select                   [order_select]       Image ID doc. file
;    work/defgrp(***grp}/select           [group_select]       (from prepare)
;    final/vft{**iter}                    [iter_vft]           (from refine)
;    work/ctf{***grp}                     [temp_ctf_file]      (from prepare)
;    input/dala{**iter}_{***group}@       [aligned_images]     Aligned stacked image files
;    final/align{**iter+1}_{***grp}       [group_align]        (from inital alignment)
;    input/data{***grp}@                  [unaligned_images]   Unaligned stacked image file  
;    final/angvoea_{**iter}               [iter_ang_voea]        
;    final/selvoea_{**iter}               [iter_select_voea] 
;
; OUTPUT FILES:
;    work/dala{**iter+1}_{***grp}@           [next_aligned_images]
;    final/align{**iter+1}_{***grp}          [group_align]
;    work/defgrp{***grp}/vol{**iter}         [next_group_vol]
;    work/defgrp{***grp}/vol_{**iter+1}_odd  [next_group_vol]_odd  (deleted in mergegroups)
;    work/defgrp{***grp}/vol_{**iter+1}_even [next_group_vol]_even (deleted in mergegroups)
;    _5@                                     [temp_ref_projs]      (created & deleted)
;    final/defgrp{***grp}/dres{**iter+1}     [next_group_dres]     (created dres output doc. file
;    final/angvora_{**iter}_{***iter}        [img_ang_vora]        
; 
; INLINE BUFFERS USED: _1

   VM
   echo " In smangloop, Iteration: {**x76}  Group: {***x77}"
   VM
   date '+ Time: %x  %X'

 x54 = 5.0                             ; First radius for 'AP REF' (Can alter this)
   x16 = 1.5 * x41                     ; Angular distance limit for stopping iters.
 
   x86 = x76 + 1                       ; Next iteration number

   UD N x53                            ; Get number of ref. projections for this iteration
   [iter_select_voea]

   UD IC x77, x79                      ; Get number of experimental images in this group
   [order_select]
   UD ICE
   [order_select]

   MY FL                               ; Flush results file

   MU                                  ; Multiply Fourier vol by CTF 
   [iter_vft]                          ; Fourier'd iteration vol      (final/vft{iter} (input)
   [temp_ctf_file]                     ; Group CTF correction file    (work/ctf{grp})  (input)
   _1                                  ; Multiplied volume                             (output)
   *
 
   FT                                  ; Back Fourier transform
   _1                                  ; Fourier of CTF corrected current volume      (input)
   _4                                  ; CTF corrected current volume created here    (output)

   DE                                  ; _1 can be deleted here 
   _1                                  ; Fourier of CTF corrected current volume

   MS                                  ; Make empty inline stack for ref. projections
   [temp_ref_projs]                    ;                                              (output)
   (x52,x52,1)                         ; Image size
   x53                                 ; Number of images allowed in stack

   DE                                  ; Remove any existing next group align doc file 
   [next_group_align]

   x91 = 0                             ; Number of angular changes above iteration stop limit
   x47 = 0                             ; Not OK to stop iterating
   x93 = 0.0                           ; Average CCROT correlation coefficient
   x94 = 0                             ; CCROT degredation counter
   x95 = 0.0                           ; Average CCROT degredation
   x97 = 0                             ; CCROT improvement counter
   x96 = 0.0                           ; Average CCROT improvement
   x92 = 0.0                           ; Average angular difference

   DO LB1 x50=1,x79                    ; Loop over experimental sample images

      ; Format of the alignment parameters doc. file is:
      ;         PSI,THE,PHI,  REF#,EXP#, ANG,SX,SY,   NPROJ,DIFF,CCROT

      UD IC x50, x17,x18,x19, x11,x20,   x23,x24,x25, x29,x12,x90
      [group_align]                    ; Alignment parameters doc. file   (input)

      DE                               ; Remove existing angvora doc. file  
      [img_ang_vora]                   ; 

      VO RAS                           ; Create proj. angles file for this image
      [iter_ang_voea]                  ; Relative angles file            (input)
      -x19,-x18,-x17                   ; Offset
      (1,0)                            ; Psi set to zero
      [img_ang_vora]                   ; Doc. file for angles to search  (output)

      ; Create stack holding set of reference projections from input volume.
      PJ 3Q                            ; Create ref. projections
      _4                               ; CTF corrected current volume     (input)              
      x56                              ; Radius of computed object
      (1-x53)                          ; Ref. projection file numbers 
      [img_ang_vora]                   ; Angles in search area doc. file  (input)
      [temp_ref_projs]******           ; Template for ref. projections    (output)

      ; Find reference image matching experimental image, parameters to doc. file
      ;       PSI,THE,PHI,  REF#,EXP#, ANG,SX,SY,   NPROJ,DIFF,CCROT
      AP REF  x11,x11,x11,  x11,x11,   x11,x11,x11, x11,x12,x31     
      [temp_ref_projs]******           ; Template of ref. projection files (input) 
      (1-x53)                          ; Ref. projection file numbers
      x55                              ; Shift search range
      (x54,x51,1)                      ; First, last ring, & skip
      [img_ang_vora]                   ; Ref. angles file                  (input)
      SCR.{******x77}                  ; No scratch file (usually in-core)
      [aligned_images]******           ; Aligned original images - dala    (input)
      x50                              ; Current exp. image file number
      [group_align]                    ; Alignment parameters doc. file     (input)
      (0)                              ; Angular projection search restriction
      (0)                              ; Mirrored projection check flag 
      [next_group_align]               ; Next align. doc file               (output)

      IF (x31 .LT. x90) THEN
         x95 = x95 + (x90 - x31)       ; Sum average CCROT degredation
         x94 = x94 + 1                 ; Increment   CCROT degredations counter
      ELSE
         x96 = x96 + (x31 - x90)       ; Sum average CCROT improvement
         x97 = x97 + 1                 ; Increment   CCROT improvements counter
      ENDIF
 
      IF (x12 .GT. x16) x91 = x91 + 1  ; Increment large displacement counter

      x92 = x92 + x92                  ; Average CCROT 
      x93 = x93 + x31                  ; Sum rotational CCC (for average).

   LB1

   UD ICE                              ; Close previous align. file here
   [group_align]                  

   ; Apply combined transformations to original experimental image stack (whole stack)
   RT SQ                               ; Rotate & shift
   [unaligned_images]                  ; Unaligned original images stack       (input)
   [next_aligned_images]               ; New aligned experimental images stack (output)
   (6,0,7,8)                           ; Angle, scale, X & Y shift registers
   [next_group_align]                  ; Next align. doc file                  (input)

   ; Calculate refined 3D structure using centered projections and new angles. 
   BP 32F                              ; Back projection, 3D, Fourier space
   [next_aligned_images]******         ; Template for aligned images      (input)
   [group_select]                      ; Selection doc. file              (input)
   [next_group_align]                  ; Align parameters doc file        (input)
   *                                   ; No symmetries  
   [next_group_vol]tmp                 ; Reconstructed 3D file - voltmp   (output)
   [next_group_vol]_odd                ; Reconstructed 3D file - vol_odd  (output)
   [next_group_vol]_even               ; Reconstructed 3D file - vol_even (output)

   CG PH,x11,x11,x11,x21,x22,x23       ; Find center of gravity of new vol.
   [next_group_vol]tmp

   SH F                                ; Shift new vol. to center of gravity
   [next_group_vol]tmp                 ; volume file - voltmp            (input)
   [next_group_vol]                    ; volume file - vol               (output)
   -x21,-x22,-x23                      ; Shift

   DE                                  ; Delete temp vol. file - vol{iter}tmp
   [next_group_vol]tmp

   DE                                  ; Delete  file
   [next_group_dres]                   ; FSC document file - dres 

   RF 3 x69,x68                        ; Phase Residual &  shell corr.
   [next_group_vol]_odd                ; First  volume file              (input) 
   [next_group_vol]_even               ; Second volume file              (input) 
   (0.5)                               ; Ring width
   (0.2,2.0)                           ; Lower & upper scale factor
   C                                   ; Missing cone
   (90.0)                              ; Max tilt angle
   (3)                                 ; Noise ocmparison factor
   [next_group_dres]                   ; FSC document file - dres       (output)

   @saveresp(x14,x76,x77,x68)          ; Record group resolution in grp summary doc file
   [grp_resol]                         ; Output file

   ; Find % of images showing excessive change in angular displacement
   x47 = 100 * x91 / x79  ;   % of images with excessive change in angular displacement

   x92 = x92 / x79                      ; Average angular difference 
   x93 = x93 / x79                      ; Average CCROT 
   IF (x94 .GT. 0) x95 = x95 / x94      ; Average CCROT degredation
   IF (x97 .GT. 0) x96 = x96 / x97      ; Average CCROT improvement
   x94 = x94 / x79                      ; Percent images with CCROT degredation

   ; '%BIG-ANGDIF, AVG-ANGDIF, AVG-CCROT, %WORSE, AVG-WORSE,  AVG-BETTER'
   SD -2, x47,      x92,        x93,       x94,    x95,        x96
   [next_group_align]                  ; Next align. doc file
   SD E
   [next_group_align]                  ; Next align. doc file

   VM
   echo " Iteration: {**x76} Group: {***x77}  Big angular changes: {***x47}%"

   VM
   echo " Degred.: {%f6.2%x94}%  Avg. degred.: {%f10.2%x95}  Avg. improve: {%f10.2%x96}"

   DE                                  ; Remove - refproj 
   [temp_ref_projs] 

   IF (x76 .GT. x74) THEN              ; Not first iteration
      DE                               ; Remove previous vol 
      [group_vol]
      DE                               ; Remove previous vol_odd
      [group_vol]_odd
      DE                               ; Remove previous vol_even
      [group_vol]_even
   ENDIF

   MY FL
RE