(x41,x42,x51,x52,x55,x56,x76,x77,x47,x74) ; Main refinement group loop
;
; grploop.pam -- Main refinement group loop   al Nov 2000
;
; MASTER COPY: /net/bali/usr1/spider/docs/techs/recon/newprogs/
; 
; PURPOSE:    Runs  for each defocus group on each iteration
;
; CALLED FROM: pub_starter.pam  
;
; INPUT REGISTERS:
;    x41                     Angular steps           (varies with iter)
;    x42                     Restrict angular search (varies with iter)
;    x51                     Radius of the structure
;    x52                     Image size
;    x55                     Shift allowed is +-x55
;    x56                     Radius of the structure used in porjection
;    x74                     Starting alignment iteration    
;    x76                     Alignment step iteration counter  (varies with iter)
;    x77                     Defocus group                     (varies with group)
; OUTPUT REGISTERS:
;    x47                     % of images whose proj. angle moved by > 1.5*x41
;
;
; INPUT FILES (SET IN: refine_settings  refine_settings.pam.pam):
;    input/order_select                   [order_select]        Image ID doc. fil
;    work/select_{***group}               [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}_{***group}       [next_group_align]
;    input/data{***grp}@                  [unaligned_images]    Unaligned stacked image file  
;    final/angvoea_{**iter}               [iter_ang_voea]        
;    final/selvoea_{**iter}               [iter_select_voea] 
;
; OUTPUT FILES(SET IN: refine_settings refine_settings.pam.pam):
;    work/dala{**iter+1}_{***grp}@        [next_aligned_images]
;    final/align{**iter+1}_{***group}     [next_group_align]
;    work/vol{**iter}_{***group}          [next_group_vol]
;    work/vol_{**iter+1}_odd_{***group}   [next_group_vol]_odd  (Deleted in mergegroups)
;    work/vol_{**iter+1}_even_{***group}  [next_group_vol]_even (Deleted in mergegroups)
;    local/refproj{**iter}_{***grp}@      [temp_ref_projs]      (Created & deleted)
;    final/dres{**iter+1}_{***group}      [next_group_dres]     (Created dres output doc. file
; 
; PROCEDURES CALLED: 
;
; INLINE BUFFERS USED: _1, _4, _8

      VM
      echo "In grploop, Iteration: {**x76}  Group: {***x77}"
      VM
      date

      x54=5.0                 ; First radius for AP (Can alter this)
      x17=1.5*x41             ; Convergence criterion angular distance limit.
 
      x58=int(x52/2)+1        ; Image center
      x86=x76+1               ; Next iteration
      x48=0                   ; Number of angular changes
      x46=0                   ; Number of angular changes greater than iteration stop limit
      x99=1

      UD N,x53
      [iter_select_voea]
      MY FL                   ; Flush results file

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

      ; Multiply Fourier of current volume by CTF file for this group
      MU                      ; Multiply
      [iter_vft]              ; Fourier of current volume (final/vft{iter}
      [temp_ctf_file]         ; CTF  file     (work/ctf{grp})
      _1                      ; _1 created here
      *
 
      FT                      ; Fourier transform
      _1                      ; Fourier of CTF corrected current volume
      _4                      ; CTF corrected current volume created here 

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

      ; Create stack holding angular reference projections from input volume.
      PJ 3Q                   ; Create reference projections
      _4                      ; CTF corrected current volume     (input)
      x56                     ; Radius of object
      [iter_select_voea]      ; Ref. angles selection doc. file  (input) - selvoea
      [iter_ang_voea]         ; Ref. angles doc. file            (input)
      [temp_ref_projs]@****** ; Template for ref. projections    (output) - refproj

      DE                   ; _4 can be deleted here
      _4                   ; CTF corrected current volume

      CP                   ; Copy current aligned images to inline stack
      [aligned_images]     ; Input file needed 
      _8@                  ; Current aligned images stack _8 created here (large)
      x79                  ; Number of images in stack _8@

      DE                   ; Remove existing next alignment doc output file  
      [next_group_align]   ; Alignment doc file

      MY FL                ; Flush results file

      ; Find reference projection matching current aligned image
      AP REF 
      [temp_ref_projs]@******   ; Template of existing ref. projections 
      (1-x53)                   ; Ref. projections file numbers
      x55                       ; Shift search range
      (x54,x51,1)               ; First, last ring & skip
      [iter_ang_voea]           ; Ref. angles file  (input)
      work/SCR_{**x76}_{***x77} ; No scratch file if fits in-core
      _8@******                 ; Template for current exp. aligned images 
      (1-x79)                   ; Current exp. images file numbers
      [group_align]             ; Exp. images alignment doc. file < < < .....
      x42                       ; Angular projection search restriction
      (1)                       ; Check mirrored projections
      [next_group_align]        ; Alignment doc file (output)

      ; Close input doc file       
      UD ICE
      [iter_ang_voea]           ; Finished with  angvoea

      ; Use cross-correlation to center 2D images
      ; Use already calculated projections as reference images

      x91 = 0.0                 ; Average correlation coefficient
      x37 = 0.0                 ; Average degredataion
      x38 = 0.0                 ; Average improvement
      x39 = 0.0                 ; Improvement counter
      x40 = 0.0                 ; Degredation counter

      IQ FI x95                 ; See if have previous alignment
      [group_align]             ; Doc file from previous alignment
      x96 = 0
      IF (x95.GT. 0) THEN       ; Find cols. in previous align. doc file
         UD N,x95,x96
        [group_align]           ; Doc file from previous alignment
      ENDIF

      DO LB5 x21=1,x79          ; Loop over all sample images

         ; Retrieve new alignment file data (just created above)
         ;          PSI,THE,PHI, REF#,EXP#,  ANG,SX,SY,   NPROJ,DIFF,CCROT
         UD IC,x21, x80,x80,x80, x81,x80,    x61,x62,x63, x80,x12,x31
         [next_group_align]                 ; Doc file just created by 'AP REF'

         IF (x96 .GT. 0) THEN 
            ; Find changes in CC for this iteration

            ;          PSI,THE,PHI, REF#,EXP#,  ANG,SX,SY,   NPROJ,DIFF,CCROT
            UD IC,x21, x80,x80,x80, x93,x80,    x80,x80,x80, x80,x94,x90
            [group_align]                   ; Doc file from previous  'AP REF

            IF (x31 .LT. x90) THEN
               x39 = x39 + (x90-x31)        ; Sum average degredation
               x40 = x40 + 1                ; Degredations counter
               ;;VM
               ;;echo {***x21} DEGRADES - Ref: {******x93} Diff: {%f6.1%x94}
            ELSE
               x38 = x38+(x31-x90)          ; Sum average improvement
               x37 = x37+1                  ; Improvements counter
               ;;VM
               ;;echo {***x21} BETTER --- Ref: {******x93} Diff: {%f6.1%x94} CCROT: {%f6.0%x90}...{%f6.0%x31}"
             ENDIF
         ENDIF

         IF (x81 .NE. 0) THEN
            ; Reference projection found within restricted search area
            x48 = x48 + 1                 ; Count successful searches
            IF (x12.GT.x17)x46 = x46 + 1  ; Count large angle displacements
            x91 = x91+x31                 ; Sum rotational CC's (for average).
         ENDIF

         ; Apply combined transformation to original exp. sample image
         IF (x81 .GE. 0) THEN            ; No mirror
            RT SQ                        ; Rotate & shift
            [unaligned_images]{******x21}; Unaligned original images (stack)
            _8@{******x21}               ; Current aligned images (output)
            x61                          ; Inplane rotation angle
            x62,x63                      ; Shifts

         ELSE                            ; Mirrored
            RT SQ                        ; Rotate & shift
            [unaligned_images]{******x21}; Unaligned original image
            _1                           ; Temp. output file
            x61                          ; Inplane rotation angle
            x62,x63                      ; Shifts

            MR                           ; Mirror
            _1                           ; Rotated, unaligned original image
            _8@{******x21}               ; Current aligned images (output)
            Y                            ; Around Y axis
         ENDIF
      LB5

      ; Close doc files       
      UD ICE
      [next_group_align]                 ; Finished with align. doc file
      UD ICE
      [group_align]                      ; Finished with align. doc file

      ; Check size of change in proj. angle
      ; Return % of image whose proj. angle moved by > 1.5*x41 criterion
      x46 = x46 / x48
      x47 = x46 * 100
      VM
      echo "Iteration: {**x76} Group: {*****x77}   Excessive changes: {***x47}%"

      x92 = x91 / x48                     ; Averaged CCROT
      IF (x40 .GT. 0) x39 = x39 / x40     ; Average degredation
      x40 = x40 / x79                     ; Percent CCROT Degredation
      IF (x37 .GT. 0) x38 = x38 / x37     ; Average improvement

      SD -1,x92,x40,x39,x38               ; Save avg. CC in doc file
      [next_group_align]

      SD E
      [next_group_align]                 ; Finished with next group align doc. file

      ; Remove temp. inline files
      DE
      _1

      ; Store aligned projections 
      CP                             ; Create hard copy of aligned images
      _8@
      [next_aligned_images]          ; No longer overwrites input files!!

      VM                             ; Echo this for isolating stack overflow
      echo "Commencing back projection"

      MY FL

      ; Calculate new, refined volume using centered projections  and 
      ; the corrected angles from align doc. file
      BP 32F                         ; Back Projection - 3D Fourier
      _8@******                      ; Template for current aligned images
      [group_select]                 ; Selection doc. file   - select
      [next_group_align]             ; Alignment doc file    - align
      *                              ; No symmetries  
      [next_group_vol]tmp            ; Reconstructed 3D file - voltmp
      [next_group_vol]_odd           ; Reconstructed 3D file - vol_odd
      [next_group_vol]_even          ; Reconstructed 3D file - vol_even

      DE                             ; _8 no longer needed
      _8

      MY FL

      ; Center 3D
      CG PH,x11,x11,x11,x21,x22,x23  ; Center of Gravity of new vol.
      [next_group_vol]tmp
      MY FL

      SH F                           ; Shift new vol.
      [next_group_vol]tmp            ; Input  file - voltmp
      [next_group_vol]               ; Output file - vol
      -x21,-x22
      -x23
      DE                             ; Delete temp file - vol{iter}tmp
      [next_group_vol]tmp

      RF 3                           ; Phase Residual &  shell correl.
      [next_group_vol]_odd           ; First  volume input file  
      [next_group_vol]_even          ; Second volume input file
      (0.5)
      (0.2,2.0)
      C
      (90.0)
      (3)
      [next_group_dres]              ; Output document file - dres

      VM                           ; Remove - refproj (no longer needed)
      \rm -f [temp_ref_projs]*.$DATEXT 

      IF(x76.LT.x75) THEN          ; Not last iteration
         DE                        ; Remove group vol. from this iter
         [group_vol]               ;   work/vol_{**x76}_{***x77}      
         DE                        ; Remove odd group vol.
         [group_vol]_odd           ;   work/vol_{**x76}_{***x77}_odd
         DE                        ; Remove even group vol.
         [group_vol]_even          ;   work/vol_{**x76}_{***x77}_even
         DE                        ; Remove current aligned images
         [aligned_images]          ;   work/dala{**x76}_{***x77}
      ENDIF

      MY FL
RE
;