; Split selection file
;
; SOURCE: res.spi 
;
; PURPOSE:
; Determine where the Fourier shell correlation drops below threshold
; (either 0.5 or 0.15), and at this point, identify the corresponding
; spatial frequency.   resolution = pixel size/spatial frequency
;
; MASTER COPY: /net/bali/usr1/spider/docs/techs/recon/newprogs/
;
; I/O PARAMETERS AND FILES ARE SET HERE:
;
;  -------------------- Parameters -----------------------------------

[threshold] = 0.5     ; Cutoff threshold for Fourier shell correlation curve
[crossing] = 0        ; Use the Nth time the curve crosses the threshold.
                      ; 0 = use last crossing

; -------------------- Input files -----------------------------------

FR G
[params]../params     ; Parameter file

FR G
[combires]combires    ; Input doc file with combined resolution curve

; -------------------------- Output files ---------------------------
FR G
[res_file]resolution       ; Doc file with resolution data

; -------------- END BATCH HEADER ---------------------------------

UD N, [nlines]
[combires]

IF ([crossing] .EQ. 0) THEN    ; Use the last crossing

   ; Get the last line ([freq2] = right, [freq1] = left)

   UD [nlines],[freq2],[dpr],[fsc2]     
   [combires]

   [lim] = [nlines]-1
   DO LB2 [key] = 1, [lim]
      [index] = [nlines] - [key]

      UD [index],[freq1],[dpr],[fsc1]     
      [combires]

      IF ([fsc1] .GT. [threshold]) THEN
         IF ([fsc2] .LE. [threshold]) GOTO LB20
      ENDIF

      [freq2] = [freq1] 
      [fsc2]  = [fsc1]
   LB2

   GOTO LB20
ENDIF

; Otherwise, use the Nth crossing. Keep track with a counter.

[counter] = 1 ; counter to compare with [crossing]

; Get the first line ([freq1] = previous, [freq2] = next)

UD 1,[freq1],[dpr],[fsc1]     
[combires]

DO LB1 [key]=1,[nlines]

   UD [key], [freq2],x32,[fsc2]
   [combires]

   IF ([fsc2].LT.[threshold]) THEN
      IF ([fsc1].GT.[threshold]) THEN
         IF ([counter].EQ.[crossing]) THEN
            GOTO LB20 
         ELSE
            [counter] = [counter] + 1
         ENDIF
      ENDIF
   ENDIF

   [freq1] = [freq2] 
   [fsc1]  = [fsc2]
LB1

LB20

; Find the interpolated spatial freq. ----------------------------

[tmp61] = ([threshold]-[fsc2]) / ([fsc1]-[fsc2])
[spatfreq] = [freq2] - ([tmp61] * ([freq2]-[freq1])) 

UD 5,[pixel_size]    ; Pixel size
[params]

; Resolution = pixel size/spatial frequency
[res_value]  = [pixel_size]/[spatfreq] 

DE
[res_file]

SD /    NORM'D FREQ  CUTOFF      ANGSTROMS
[res_file]

SD 1,[spatfreq],[threshold],[res_value]
[res_file]

VM                                      
echo ' 'Resolution: {%f5.2%[res_value]} Angstroms stored in: [res_file].$DATEXT 
VM                                      
echo ' '

EN D
;