;+
; Project     : SOHO - CDS     
;                   
; Name        : TLM_SCIENCE
;               
; Purpose     : To count the science packets in a telemetry file.
;               
; Explanation : Reads telemetry files, packet by packet and counts
;               every sciencepacket.  If no files are input, then searches
;               $CDS_CDROM_DATA. Saves the output in $CDS_ENG_DATA_W/xxxxx
;               where xxxx is made from the first tm file name
;               
; Use         : IDL> tlm_science [, filenames, /quiet]
;    
; Inputs      : None
;
; Opt. Inputs : filenames - the telemetry file names 
;               
; Outputs     : Writes to IDL save file, and prints on screen
;               
; Opt. Outputs: None
;               
; Keywords    : QUIET      - no screen output
;
; Calls       : None
;
; Common      : None
;               
; Restrictions: None
;               
; Side effects: None
;               
; Category    : Telemetry
;               
; Prev. Hist. : None
;
; Written     : C D Pike, RAL, 25-Jul-96
;               
; Modified    : 
;
; Version     : Version 1, 25-Jul-96
;-            

pro tlm_science, file, quiet=quiet 

;
;  Define general packet header structure
;
PacketHeader = {PacketHeaderDef,                $
                Msgid:               FIX(0),    $
		MsgLen:              FIX(0),    $
		MsgReqid:            FIX(0),    $    
		ap_id:               BYTARR(2), $
		counter:             FIX(0),    $
		length:              FIX(0),    $
		Time:                BYTARR(6), $
		ID:                  BYTE(0),   $
		StreamPacketCounter: BYTE(0)}


;
;  dummy data arrays
;
b286 = bytarr(286)

;
;  were files given?  If not search $CDS_CDROM_DATA
;
if n_elements(file) eq 0 then begin
   file = findfile(concat_dir('$CDS_CDROM_DATA','tm.*'),count=count)
   if count eq 0 then return
endif

;
;  allow loop through all files
;
nfile = n_elements(file)
percent = fltarr(nfile)

;
;  set up save file name
;
break_file, file(0), disk, dir, f, ext
sfile = concat_dir('$CDS_ENG_DATA_W','sci_pack'+ext)

for i=0,nfile-1 do begin
   tot_pack = 0L
   tot_sci = 0L
 


;
;  open input file 
;
   openr, unit, file(i), /get_lun



;
;  for incomplete files...
;
   on_ioerror, duff_file


;
;  begin reading file
;
   while not eof(unit) do begin
      readu, unit, PacketHeader
      readu,unit,b286
      tot_pack = tot_pack + 1

;
;  produce totals
;

      if packetheader.id eq '1'x or packetheader.id eq '2'x or $
        packetheader.id eq '11'x or packetheader.id eq '12'x or $
        packetheader.id eq '21'x or packetheader.id eq '22'x then $
         tot_sci = tot_sci + 1


   endwhile

;
;  jump to here if io error
;
   duff_file:


  
;
;  close files
;
   free_lun, unit 
   percent(i) = float(tot_sci)/float(tot_pack)
   if not keyword_set(quiet) then begin
      print,'Packs ',tot_pack,tot_sci,'  % science: ',percent(i)
   endif
   save,file,percent,file=sfile

endfor



end
   
