
; ---------------------------------------------------------------------
;                                 rh_open_fits
; ---------------------------------------------------------------------
; Ouvre un fichier RH et definit le common RH (cf rh_common.inc)
; Le keyword MONO ou SEL definit le mode de lecture.
; ---------------------------------------------------------------------
; 
; CALLING SEQUENCE: 
;       status = rh_open_fits(fichier) 
; 
; INPUTS:
;	fichier : nom du fichier a ouvrir 
;
; OUTPUTS: 
;       status : = 1 lecture correcte
;	         = 0 erreur 
;                   !ERROR contient le code de l'erreur
;	            !SYSERR_STRING contient le message d'erreur
;
; KEYWORD:
;	MONO  : lecture acquisition par acquisition
;	        sinon par jeu de frequences
;	SEL   : lecture par jeu, mais selection d'une frequence 
;	        non polar ou polar
;	MALAX : initialise malax
;
; COMMON BLOCKS: 
;	common RH
; HISTORY
;       Mars 2002 : operation antennes anti_alias
;                   44 antennes ---> 48 antennes
;                   576 correlations ---> 576 + 4*18 = 648
;                   correlations
;       Mars 2003 : les structures nommees sFI et entFI sont
;       remplacees par des structures anonymes, ce qui leur permet de 
;       changer de definition au cours d'une session IDL ( avec ou sans 
;       antennes anti-alias )
;       pour menu_rh : appel de rh_init_initmalax.pro quand /malax
;       Oct. 2003 : Ajout de l'heure (hr,mn) du phasage dans entcor
;                   La reference de la source passe de 6 octets a 2 octets
;                   l'heure occupe 2 integer*2
;          Pour verifier faire help,entfi.entcor,/str ( 368/400 octets sans 
;          /avec antennes anti-alias)
;          print,'>', string(entfi.entcor(0).ref(*)),'<'
;          > 3C405<   -->  > 3< 
;          les sources sont : Cy Ca Hy ou Vi
;       Octobre 2003   : lecture des donnees 3D
;       Septembre 2005 : saut des num de freq >0 du debut de fichier 
;       dans les fichiers suite quand lecture par paquets de freq
;       (non-MONO)et donnees sans compression.
; 08/02/2007 : suppression du dernier evenement sans compression
;              remplacé par la configuration du recepteur (80 octets)
; 14/02/2011 : Adaptation de rh_open.pro pour fichiers visibilites
;       fits (A Bouteille) entfi.rep =1 pour fichiers fits
; -----------------------------------------------------------------------------

FUNCTION rh_open_fits, fichier, MONO = MONO, SEL=SEL, MALAX=MALAX
@rh_common.inc



; Fichier natif ou fichier fits ?

   CHAMP = Str_sep( Fichier, '.')
   EXTEN = Champ((size(champ))(1)-1)
   print,'rh_open',champ,exten

; fichier FITS
;   if exten eq 'fts' then begin
      H = HEADFITS( Fichier)
      instrume = fxpar(h,'instrume') & content = strcompress(fxpar(h,'NRH_DATA'),/remove_all)
print,'content',content
      IF INSTRUME EQ 'NRH2' AND Content EQ '2DA' THEN begin
; c est un fichier fits de type visibilities
;         H1 = HEADFITS( Fichier,EXTEN =1)
         FXBOPEN, Chan, Fichier,1,H1
         freq  = FXPAR(h1,'FREQ')
         ncorr = FXPAR(h1,'NCORR')
         nacq  = FXPAR(h1,'NAXIS2')
         val = ncorr
     
      END ELSE BEGIN
         print,' not a visibilities Nrh2 fits file --- return'
         return, 0
      ENDELSE
;   END 

; determination de nbcorel1 et nbant1 necessaires a la definition de la structure entfi

  CASE val/4 OF 
  11 : BEGIN
            nbant1 = 44L
            nbcorel1 = 576L
        END
  576 : BEGIN
            nbant1 = 44L
            nbcorel1 = 576L
        END
  12 : BEGIN
            nbant1 = 48L 	; = 44 + 4
            nbcorel1 = 648L	; = 576 + 4 x 18
        END
  648 : BEGIN
            nbant1 = 48L 	; = 44 + 4
            nbcorel1 = 648L	; = 576 + 4 x 18
        END
  90  : BEGIN                   ; 1D 
            nbant1 = 44L
            nbcorel1 = 90L
        END
  126  : BEGIN                  ; 1D avec NS45-NS (2 barrettes)
            nbant1 = 44L
            nbcorel1 = 126L
        END
  ELSE : BEGIN
            print,' Not a NRH file : ', fichier, val/4
stop
            goto, ERR
         END   
 ENDCASE
;Structure de la table de correction 

  entCOR=replicate({                    $ 	; def table de correction
		frq:0,			$
		dat:intarr(3),		$
		ref:bytarr(2),		$    ; 2 caracteres au lieu de 6
                heure:intarr(2),        $    ; ajout heure du phasage(oct2003)
		coeff_gain:0,		$
		gain_np:intarr(nbant1),	$
		gain_p:intarr(nbant1),	$
		phase_np:intarr(nbant1),	$
		phase_p:intarr(nbant1) },10)

;Structure de la tete de fichier

  entFI = {     lgent:0L,		$ 	; def entete du fichier
		filesize:0L,   	 	$
		lg:0,   	 	$
		typ:0,			$
		cod:0,	    		$
		rep:0,			$
		lgtet:0,		$
		nval:0,	       		$
		nval_2d:0,     		$
		nval_ew:0,     		$
		nval_ns:0,		$
		d_typ:bytarr(6),	$
		itg:0L, 		$
		dat:intarr(3),		$
		ref:bytarr(6),		$
		mer:intarr(4),		$
		dec:intarr(4),		$
		hg:0,			$
		hdeb:intarr(4),		$
		hfin:intarr(4),		$
		nf:0,	     		$
		frq:intarr(10),	        $
		trj:0,	       		$
		comp:0,			$
		cyclms:0,		$
		d_obs:bytarr(78),	$
		depew:0,		$
		dephew:0, 		$
		rotew:0,		$
		rotns:0,		$
		pxant:lonarr(nbant1),	$		
		pyant:lonarr(nbant1),	$
		corel:intarr(2,nbcorel1),	$	
		entCOR:entCOR,		$
		descrip:bytarr(80,2),   $
		activ:bytarr(80),	$
		pannes:bytarr(80,3),	$
		evenements:bytarr(80,14), $
		recepteur:bytarr(80),   $
		endian:0L,		$
		klumax:0L,              $
                dtu:0L,                 $
		nbant: 0L, 		$
		nbcorel: 0L, 		$
		g_recept:intarr(nbant1), $
		tab_gain:intarr(16,nbant1), $
		offset:intarr(nbant1) $
;		libre:lonarr(54) $
                }

 

; lecture de entfifi dans l'extension 2 du fichier fits
;  la structure est legerement differente 

         entfifi = mrdfits(fichier,2,h2)
; MRDFITS: Binary table.  (TFIELDS =) 109 columns by  1 rows

; determination de entfi a partir de entfifi
   names = tag_names(entfi)
   i=0
   while names(i) ne 'PXANT' do begin
      entfi.(i) = entfifi.(i)
      i=i+1
  endwhile
   entfi.activ = entfifi.activ
   entfi.pannes = entfifi.pannes
   entfi.evenements = entfifi.events(*,0:13)
   entfi.recepteur = entfifi.events(*,14)
   entfi.endian = entfifi.endian
   entfi.klumax = nacq -1    ;entfifi.klumax
   nof = where (entfi.frq eq nint(freq*10))
; ceci est une astuce pour connaitre le numero de frequence dans les
; routines rh_read
   entfi.rep = 10 + nof    ; 0 si fichier natif et >0 si fichier fits  = 10+nof(numero de frequence)

print,' names(i):',i
   entfi.pxant = entfifi.xyant(*,0)
   entfi.pyant = entfifi.xyant(*,1)
   entfi.corel = entfifi.correl
; remplissage de entcor
   entcor(0).frq = entfifi.cal_frq1  
   entcor(0).dat = entfifi.cal_date1  
   entcor(0).ref = entfifi.cal_src1  
   entcor(0).heure = entfifi.cal_tim1
   entcor(0).coeff_gain = entfifi.cal_coefg1
   entcor(0).gain_np = entfifi.cal_gain1(*,0)
   entcor(0).gain_p = entfifi.cal_gain1(*,1)
   entcor(0).phase_np = entfifi.cal_phase1(*,0)
   entcor(0).phase_p = entfifi.cal_phase1(*,1)

   entcor(1).frq = entfifi.cal_frq2 
   entcor(1).dat = entfifi.cal_date2  
   entcor(1).ref = entfifi.cal_src2  
   entcor(1).heure = entfifi.cal_tim2
   entcor(1).coeff_gain = entfifi.cal_coefg2
   entcor(1).gain_np = entfifi.cal_gain2(*,0)
   entcor(1).gain_p = entfifi.cal_gain2(*,1)
   entcor(1).phase_np = entfifi.cal_phase2(*,0)
   entcor(1).phase_p = entfifi.cal_phase2(*,1)


   entcor(2).frq = entfifi.cal_frq3  
   entcor(2).dat = entfifi.cal_date3  
   entcor(2).ref = entfifi.cal_src3  
   entcor(2).heure = entfifi.cal_tim3
   entcor(2).coeff_gain = entfifi.cal_coefg3
   entcor(2).gain_np = entfifi.cal_gain3(*,0)
   entcor(2).gain_p = entfifi.cal_gain3(*,1)
   entcor(2).phase_np = entfifi.cal_phase3(*,0)
   entcor(2).phase_p = entfifi.cal_phase3(*,1)

   entcor(3).frq = entfifi.cal_frq4  
   entcor(3).dat = entfifi.cal_date4  
   entcor(3).ref = entfifi.cal_src4  
   entcor(3).heure = entfifi.cal_tim4
   entcor(3).coeff_gain = entfifi.cal_coefg4
   entcor(3).gain_np = entfifi.cal_gain4(*,0)
   entcor(3).gain_p = entfifi.cal_gain4(*,1)
   entcor(3).phase_np = entfifi.cal_phase4(*,0)
   entcor(3).phase_p = entfifi.cal_phase4(*,1)

   entcor(4).frq = entfifi.cal_frq5  
   entcor(4).dat = entfifi.cal_date5  
   entcor(4).ref = entfifi.cal_src5  
   entcor(4).heure = entfifi.cal_tim5
   entcor(4).coeff_gain = entfifi.cal_coefg5
   entcor(4).gain_np = entfifi.cal_gain5(*,0)
   entcor(4).gain_p = entfifi.cal_gain5(*,1)
   entcor(4).phase_np = entfifi.cal_phase5(*,0)
   entcor(4).phase_p = entfifi.cal_phase5(*,1)

   if entfi.nf gt 5 then begin

   entcor(5).frq = entfifi.cal_frq6  
   entcor(5).dat = entfifi.cal_date6  
   entcor(5).ref = entfifi.cal_src6  
   entcor(5).heure = entfifi.cal_tim6
   entcor(5).coeff_gain = entfifi.cal_coefg6
   entcor(5).gain_np = entfifi.cal_gain6(*,0)
   entcor(5).gain_p = entfifi.cal_gain5(*,1)
   entcor(5).phase_np = entfifi.cal_phase6(*,0)
   entcor(5).phase_p = entfifi.cal_phase6(*,1)

   entcor(6).frq = entfifi.cal_frq7  
   entcor(6).dat = entfifi.cal_date7  
   entcor(6).ref = entfifi.cal_src7  
   entcor(6).heure = entfifi.cal_tim7
   entcor(6).coeff_gain = entfifi.cal_coefg7
   entcor(6).gain_np = entfifi.cal_gain7(*,0)
   entcor(6).gain_p = entfifi.cal_gain7(*,1)
   entcor(6).phase_np = entfifi.cal_phase7(*,0)
   entcor(6).phase_p = entfifi.cal_phase7(*,1)

   entcor(7).frq = entfifi.cal_frq8  
   entcor(7).dat = entfifi.cal_date8  
   entcor(7).ref = entfifi.cal_src8  
   entcor(7).heure = entfifi.cal_tim8
   entcor(7).coeff_gain = entfifi.cal_coefg8
   entcor(7).gain_np = entfifi.cal_gain8(*,0)
   entcor(7).gain_p = entfifi.cal_gain8(*,1)
   entcor(7).phase_np = entfifi.cal_phase8(*,0)
   entcor(7).phase_p = entfifi.cal_phase8(*,1)

   entcor(8).frq = entfifi.cal_frq9  
   entcor(8).dat = entfifi.cal_date9  
   entcor(8).ref = entfifi.cal_src9  
   entcor(8).heure = entfifi.cal_tim9
   entcor(8).coeff_gain = entfifi.cal_coefg9
   entcor(8).gain_np = entfifi.cal_gain9(*,0)
   entcor(8).gain_p = entfifi.cal_gain9(*,1)
   entcor(8).phase_np = entfifi.cal_phase9(*,0)
   entcor(8).phase_p = entfifi.cal_phase9(*,1)

   entcor(9).frq = entfifi.cal_frq10  
   entcor(9).dat = entfifi.cal_date10  
   entcor(9).ref = entfifi.cal_src10  
   entcor(9).heure = entfifi.cal_tim10
   entcor(9).coeff_gain = entfifi.cal_coefg10
   entcor(9).gain_np = entfifi.cal_gain10(*,0)
   entcor(9).gain_p = entfifi.cal_gain10(*,1)
   entcor(9).phase_np = entfifi.cal_phase10(*,0)
   entcor(9).phase_p = entfifi.cal_phase10(*,1)

   endif

; MODIF ANTIALIASING

  entFI.nbant = nbant1
  entFI.nbcorel = entFI.nval/4
; MODIF heure du phasage non definie pour les manip a 44 antennes
;***on met le cygne sur les vieilles manip (print,entfi.entcor(*).ref)
  if entFI.nbant eq 44 then begin
      entfi.entcor(0:entfi.nf-1).heure=[18,0]  ; pour rh_corr_antennes.pro
      entfi.entcor(0:entfi.nf-1).ref=byte('Cy')
  endif 

; MODIF ANTIALIASING : RECEPTEUR DE GAIN EW (0) OU NS (1)
  if entFI.nbant eq 44 then begin
    FOR k=0, 18 DO BEGIN
    	entfi.g_recept(k)=0
    endfor	
    FOR k=19, entfi.nbant-1 DO BEGIN
    	entfi.g_recept(k)=1
    endfor	

; MODIF ANTIALIASING : TABLE DES GAINS PAR ANTENNES
    FOR k=0, 15 DO BEGIN
    	entfi.tab_gain(k,*)=SQRT(2.^(k*1.))*100.
    endfor
  endif 

   entfi.dat(2) = rh_date100(entfi.dat(2),/full)
   status = 1

;Remplissage de sFI pour fichier fits
  sFI = {	unit:0L,		$
		name:'',		$
		mode:0 ,		$
		tFI:intarr(4,entFI.nbcorel)	$
      }
  sFI.unit = chan*1L
  pos = strpos(fichier,'/',/reverse_search)
  fich=strmid(fichier,pos+1)
  sFI.name = fich
  sFI.mode = 1
  IF keyword_set(MONO) THEN sFI.mode = 0
  FOR k=0, entFI.nbcorel-1 DO BEGIN
      sFI.tFI(*,k) = 2
      IF entFI.corel(0,k) LT 19 AND entFI.corel(1,k) LT 19 THEN sFI.tFI(*,k)=0
      IF (entFI.corel(0,k) GE 19 AND entFI.corel(0,k)LT 44 ) AND $
         (entFI.corel(1,k) GE 19 AND entFI.corel(1,k)LT 44) THEN sFI.tFI(*,k)=1
  ENDFOR
  stop
;Structure decrivant une acquisition decodee
  nbgain=2
  IF entFI.typ EQ 2 then nbgain = 3
  luFI={ g:intarr(nbgain), pt:fltarr(4, entfi.nval/4)}
  IF NOT KEYWORD_SET(MONO) THEN luFI = replicate(luFI, entFI.nf)
  IF KEYWORD_SET(SEL) THEN luFI = { g:intarr(nbgain), $
                                    pt:fltarr(2, entfi.nval/4)}

;Association de la variable aFI au numero logique u

;Structure decrivant une acquisition brute
  CASE entFI.typ OF
     '1': bFI={ c:0, nof:0, h:intarr(4), g:intarr(2), $
                pt:intarr(4, entfi.nval/4)}
     '2': bFI={ c:0, nof:0, h:intarr(4), g:intarr(3), nul0:0, $
                pt:intarr(4,entfi.nval/4), $
                nul1:intarr(entFI.lg/2-entFI.nval-entfi.lgtet)}
     '3': bFI={ c:0, nul2:intarr(2), nof:0, h:intarr(4), g:intarr(2), $
                pt:intarr(4,entfi.nval/4), $
                nul1:intarr(entFI.lg/2-entFI.nval-entfi.lgtet)}
     '4': bFI={ c:0, nof:0, h:intarr(4), g:intarr(2), $
                pt:intarr(4,entfi.nval/4)}
  ENDCASE              

  IF NOT KEYWORD_SET(MONO) THEN bFI = replicate(bFI, entFI.nf)
     ; definir entfi.hdeb et entfi.hfin?

    print,'rh_open_fits : ',entfi.dat, entfi.hdeb, entfi.hfin  
stop     
 ; Init Malax pour le calcul d'image
  IF KEYWORD_SET(MALAX) THEN rh_init_initmalax
  ERR : RETURN,status

END
end
