; Sort defocus groups doc file
; sort.pam                                     Mar 2002  ArDean Leith
;                                      []      Dec 2005   ArDean Leith
; 
; MASTER COPY: sort.pam
;
; PURPOSE : Sorts order_select doc file by number of particles
;
; CALLED FROM:
;    pub_refine.pam   pub_refine.pam or
;    refine.pam       refine.pam 
;
; OUTPUT REGISTER (SET ABOVE):
;    [tot-part]                          Total number of particles
;    
; INPUT FILES (SET IN: refine_settings.pam) :
;    input/order_select        [order_select]  Input doc file
;
; OUTPUT FILES (SET IN: refine_settings.pam):
;    input/order_select_sort    [sorted_order_select] ( Output doc file, big to samll) 
;    input/order_select_rev      Output doc file, small to big
;
; CALLS: none
;
;.......................................................................

FR L
[tmp1]order_select_jnk1 ; temp output file (deleted)

FR L
[tmp2]order_select_jnk  ; temp output file (deleted)

FR L
[tmp3] order_select_rev ; temp output file (deleted)
FR L
[tmp4] order_select_jnk2; temp output file (deleted)

;----------------------------------------------------------------------

UD N [nkey]      ; Get [nkey]=number of highest key in use
[order_select]   ; Input file

DOC CREATE       ; Create consecutively numbered keys with 1.0 in reg:1
[tmp1]           ; Temp output file #1
0
1-[nkey]

DOC MERGE
[tmp1]           ; File with consecutively numbered keys 
[order_select]   ; Input file
[tmp4]           ; Temp output file #4 Merged output
0

[ngrp]=0
[tot-part]=0
DO LB1 [grp]=1,[nkey]  ; Loop over defocus groups -----------------

   ;            PARTICLES, CUM.TOTAL, DEFOCUS              
   UD IC [grp], [part],    [cum],     [def]    
   [tmp4]                          ; Input file (temp file #4)
   
   IF ([part].GT.1) THEN
      [ngrp]=[ngrp]+1              ; Number of groups in use

      ;         GROUP, PARTICLES, DEFOCUS              
      SD [ngrp], [grp], [part],   [def] ; Key is now consecutive number
      [tmp2]                            ; Temp output file #2
   ENDIF
LB1

UD ICE
[order_select]
SD E
[tmp2]

DE
[tmp3]
DE
[tmp4]
DE
[tmp1]

; DOC file sorting
DOC SORT
[tmp2]      ; Temp input file
[tmp3]      ; Output file (Temp file #3)
2           ; Sort column
Yes         ; Renumber keys

DE
[tmp2]
DE
[sorted_order_select]

UD N, [nkey]
[tmp3]

; Reverse sorting order of output doc file
DO LB2 [i]=1,[nkey]   ; Loop over defocus groups -------------------

   [grp]=[nkey]-[i]+1   ; Reverse order

   ;         GROUP, PARTICLES, DEFOCUS              
   UD IC,[grp], [grp],  [part],       [def]
   [tmp3]   ; Input file

   ;       GROUP, PARTICLES,  DEFOCUS              
   SD [i], [grp],    [part],       [def]
   [sorted_order_select]   ; Output file
LB2

UD ICE
[tmp3]
DE
[tmp3]
SD E
[sorted_order_select]

RE
;