;+ ***********************************************************************
; NAME:
;	TRI_CENTRES
;
; PURPOSE:
;	Tri en position(s) les volumes gaussiens determines apres la procedure
;	SCAN_SOURCES
;
; CATEGORY:
;	RH_2D, Recherche de position
;
; CALLING SEQUENCE:
;	TRI_CENTRES, Fich1, Fich2, Nbposi, Nbhit
;
; OPTIONAL INPUTS:
;	Fich1:	nom du fichier binaire dans lequel est stocke la description
;		des volumes gaussiens (defaut centres.dat)
;
; OUTPUTS:
;	Nbposi:	nombre de positions trouvees
;	Nbhit:	nombre maximum de sources par position
;
; OPTIONAL OUTPUTS:
;	Fich2:	nom du fichier binaire qui contient la description des volumes
;		gaussiens classes par position (defaut positions.dat)
;
; EXAMPLE:
;	TRI_CENTRES, 'cent2101_2.dat', 'posi2101_2.dat', nbposi, nbmaxhit
;
; MODIFICATION HISTORY:
;	Ecrit par: C. Renié
;	LE 13/09/00	Rajout BUFSIZE=0 pour openr
;-*******************************************************************

PRO TRI_CENTRES, fichcent, fichposi, nbposi, nbmaxhit
COMMON OPTPOSI, str_opt

	t = {temps:0L, numpos:0.0, source:{GAUSS}}
	tmp = {temps:0L, numpos:0.0, source:{GAUSS}}
	OPENR, filetmp, fichcent, /GET_LUN, BUFSIZE=0
	; ecriture de la premiere source dans le fichier position	
	READU, filetmp, t
	t.numpos = 0
	OPENW, filetmp1, fichposi, /GET_LUN
	WRITEU, filetmp1, t
	FREE_LUN, filetmp1

	zoneX = str_opt.ZoneX & zoneY = str_opt.ZoneY
	
	nbposi = 1
	WHILE (NOT EOF(filetmp)) DO BEGIN 
		READU, filetmp, t
		OPENU, filetmp1, fichposi, /GET_LUN
		; parcours des positions deja archivees
		WHILE (NOT EOF(filetmp1)) DO BEGIN 
			READU, filetmp1, tmp
			critx = ABS(tmp.source.xmax-t.source.xmax)
			crity = ABS(tmp.source.ymax-t.source.ymax)
			crit = (t.temps NE tmp.temps) AND (critx LT zoneX) AND (crity LT zoneY)
			IF crit EQ 1 THEN BEGIN	
				t.numpos = tmp.numpos
				; va en fin du fichier position
				WHILE (NOT EOF(filetmp1)) DO READU, filetmp1, tmp
			ENDIF
		ENDWHILE
		IF t.numpos EQ -1.0 THEN BEGIN
			t.numpos = nbposi
			nbposi= nbposi + 1
			; va en fin du fichier position
			WHILE (NOT EOF(filetmp1)) DO READU, filetmp1, tmp
		ENDIF
		;PRINT, 'position num', t.numpos
		WRITEU, filetmp1, t
		FREE_LUN, filetmp1
	ENDWHILE
	FREE_LUN, filetmp

	; determination du nombre de sources max par position
	OPENR, filetmp, fichposi, /GET_LUN
	nbmaxhit=0
	FOR i=0, nbposi-1 DO BEGIN
		nbhits = 0
		WHILE (NOT EOF(filetmp)) DO BEGIN 
			READU, filetmp, t
			IF t.numpos EQ i THEN nbhits = nbhits + 1
		ENDWHILE
		IF nbhits GT nbmaxhit THEN nbmaxhit = nbhits
		POINT_LUN, filetmp,0	; retour au debut du fichier de positions
		;PRINT, 'posi ', i, 'nbhits=', nbhits
	ENDFOR
	FREE_LUN, filetmp
	;PRINT, 'nbpos=', nbposi, 'nbmaxhit=', nbmaxhit
END
