;+
;  $Id: read_tlm_jill.pro,v 1.2 2008/02/05 21:34:13 jredfern Exp $
;
;  $Source: /usr/lib/cvsroot/twins-idl/lib/util/read_tlm_jill.pro,v $
;  $Revision: 1.2 $
;  $Date: 2008/02/05 21:34:13 $
;
;
;Modified for jillian's usage

PRO read_tlm_jill, datafile, fm1cal=fm1cal, cal=cal

;
; PURPOSE:
;	read twins binary telemetry file and generate idl save sets for
;	housekeeping,test,image
;
;  Example:
;   read_tlm, '2002031',1
;  Notes:
;  See Also:
;
;  Author:  Dorothea DeLapp LANL 2007
;  Modification $Author: jredfern $
;-
;
; create file name from datestring
; 
; datafile=strcompress('/home/twins/data/local/telemetry/TW'+string(tw_id)+string(datestring)+'0000_R1.dat',/remove_all)
;
; open file and get file size from info
;
 openr,ilun,datafile+'.dat',/swap_if_little,/get_lun
print, datafile+'.dat'
; openr,ilun,datafile,/get_lun
 file_info = fstat(ilun)
 sz=file_info.size
;
; define array to store byte data
;
 bdata=bytarr(sz)
;
; read the data
;
 readu,ilun,bdata
 close,ilun
 free_lun,ilun
 
;
; now determing what data is housekeeping, image,test,dump
;
;  Frame Type
;	THPK - [84,72,75,80] - TWINS housekeeping
;	TDMP - [84,68,77,80] - TWINS dump data
;	TTST - [84,84,83,84] - TWINS test data
;	TIMG - [84,73,77,71] - TWINS image data
ftype_h = where(bdata[0:*] EQ 84 and bdata[1:*] EQ 72 and bdata[2:*] EQ 75 and bdata[3:*] EQ 80)
ftype_i = where(bdata[0:*] EQ 84 and bdata[1:*] EQ 73 and bdata[2:*] EQ 77 and bdata[3:*] EQ 71)
ftype_t = where(bdata[0:*] EQ 84 and bdata[1:*] EQ 84 and bdata[2:*] EQ 83 and bdata[3:*] EQ 84)
ftype_d = where(bdata[0:*] EQ 84 and bdata[1:*] EQ 68 and bdata[2:*] EQ 77 and bdata[3:*] EQ 80)
ftype_e = where(bdata[0:*] EQ 69 and bdata[1:*] EQ 72 and bdata[2:*] EQ 75 and bdata[3:*] EQ 80)


print, n_elements(ftype_h), n_elements(ftype_i),n_elements(ftype_t), n_elements(ftype_d)

 if n_elements(ftype_e) gt 1 then begin
 ;
 ; get TDU hsk hdr info
 ;
 tduhsk=get_hdr_info(ftype_e,bdata)
 endif

 save, tduhsk, filename=datafile+'_tduhsk.idl'


;
; check to see if data exists
;
if n_elements(ftype_h) gt 1 then begin
;
; get hsk hdr info
;
hsk=get_hdr_info(ftype_h,bdata)

;
; unpack Houskeeping
;
if keyword_set(fm1cal) then begin
  unpack_hsk_jill,datafile,bdata,ftype_h,hsk,fm1cal=fm1cal
endif else begin
  unpack_hsk_jill,datafile,bdata,ftype_h,hsk,fm1cal=0
endelse
endif
stop
;
; check to see if data exists
;
if n_elements(ftype_t) gt 1 then begin
;
; get tst hdr info
;
tst=get_hdr_info(ftype_t,bdata)

;
; unpack test
;
if keyword_set(cal) then begin
 unpack_tst_jill,datafile,bdata,ftype_t,tst, cal=cal
endif else begin
unpack_tst_jill,datafile,bdata,ftype_t,tst, cal=0
endelse
endif

;
; check to see if data exists
;
if n_elements(ftype_i) gt 1 then begin
;
; get img hdr info
;
img=get_hdr_info(ftype_i,bdata)

;
; unpack image
;
if keyword_set(cal) then begin
 unpack_img_jill,datafile,bdata,ftype_i,img, cal=cal
endif else begin
unpack_img_jill,datafile,bdata,ftype_i,img, cal=0
endelse
endif

the_end:

END