pro decode_sci5k, rec, lun, irec, none_cnt, cnt_minutes, simple=simple, fill_cnt=fill_cnt
;
;INPUT:
;	rec	- the record to decode
;		  199 integer*2 array
;	lun	- The logical unit of the output file to print the ascii informat to
;	i	- counting the number of packets
;	none_cnt - Allowing the routine to count the number of packets in a row
;		   with no information
;	cnt_minutes - an ongoing counter for the number of ref-times
;HISTORY:
;	19-Dec-95 (MDM) - Renamed variable "i" to "irec"
;	24-Jan-96 (MDM) - Display more than just the first 6 arguments 
;			  on the command line echo
;	29-Jan-96 (MDM) - Patched 24-Jan-96 patch which gave b2 subscripts
;			  out of range errors on occasion
;	   Mar-96 (DM)  - Changed format
;	30-Apr-96 (MDM) - Added option to not write to output file
;	13-Jun-96 (MDM) - Added Tuncate flag to the display
;	1-Apr-99 (CED)  - Added support for roll monitoring files
;	10-May-99 (CED) - Updated roll monitoring to include ecliptic angle too.
;	24-May-99 (CED) - Fixed latest IDL screw -- v5.2 makes 'aa55'x a NEGATIVE, rather than unsigned,
;				 number.
;
common decode_sci5k_blk, last_reftime
;
;;print, unsign(rec(0:20), 16), format='(25z5)'
;;return
;
l_val = intarr(2)
if (n_elements(last_reftime) eq 0) then last_reftime = -1

    b2 = byte(rec, 0, 398)
    b = unsign(rec, 16)
    ;
    typ = b2(12)
    reftime = long(b2, 6)
    daytim = anytim2ints('1-Jan-58', off=reftime*1D)
    daytim_str = fmt_tim(daytim)
    ;
    if (keyword_set(qstop)) then stop
    ;;print, 'Packet Type = ', typ
    ;;print, b(0:19), format='(20(1x,z4.4))'
    case typ of
	'FD'x: begin	;DEP memory dump
		print,       '<<<<<<<<<<<<<<<< DEP Memory Dump at ' + daytim_str + ' >>>>>>>>>>>>>>>>'
		print,       b, format='(16(1x,z4.4))'
		if (lun ne 0) then printf, lun, '<<<<<<<<<<<<<<<< DEP Memory Dump at ' + daytim_str + ' >>>>>>>>>>>>>>>>'
		if (lun ne 0) then printf, lun, b, format='(16(1x,z4.4))'
		none_cnt = 0
	      end
	'FB'x: begin	;IP buffer dump
		print,       '<<<<<<<<<<<<<<<< IP Buffer Dump ' + daytim_str + '  >>>>>>>>>>>>>>>>'
		print,       b, format='(16(1x,z4.4))'
		if (lun ne 0) then printf, lun, '<<<<<<<<<<<<<<<< DEP Memory Dump at ' + daytim_str + ' >>>>>>>>>>>>>>>>'
		if (lun ne 0) then printf, lun, b, format='(16(1x,z4.4))'
		none_cnt = 0
	      end
	'F8'x: begin	;command echo
		if (n_elements(cmd_table) eq 0) then begin
		;print, '<<<<<<<<<<<<<<<< Command Echo >>>>>>>>>>>>>>>>'
		    table = rd_tfile('/mdisw/dbase/cal/info/cmd_echo.table')
		    ntable = n_elements(table)
		    cmd_table = replicate({cmd: ' ', nwords: 0L, mnem: ' ', descr: ' '}, n_elements(table))
		    for i=0,ntable-1 do begin
			arr = str2arr(strcompress(table(i)), delim=' ')
			cmd_table(i).cmd = str_replace(arr(0), '.', '*') + '*'
			cmd_table(i).nwords = fix(arr(1))
			cmd_table(i).mnem  = arr(2)
			cmd_table(i).descr = arr2str(arr(3:*), delim=' ')
		    end
		end
		if (keyword_set(simple)) then begin
		    print,      b, format='(16(1x,z4.4))'
		    if (lun ne 0) then print, lun, b, format='(16(1x,z4.4))'
		end else begin
		    qdone = 0
		    ist = 16
		    while (not qdone) do begin
		      cmd_check = mask(b2(ist), 2, 4)	;xx10 10xx
		      if (cmd_check eq 10) then begin
			full_cmd = string(b2(ist:ist+5), format='(6z2.2)')
			;if (qdebug) then print, b, format='(16(1x,z4.4))'
			;if (qdebug) then print, full_cmd
			;
			i=-1
			nss = 0
			while ((nss eq 0) and (i lt ntable-1)) do begin
			    i = i + 1
			    ss = wc_where(full_cmd, cmd_table(i).cmd, nss)
			end
			;;ss = wc_where(cmd_table.cmd, full_cmd, nss)
			if (nss ne 0) then begin
			    ;;prstr, cmd_table(i).mnem + ' == ' + cmd_table(i).descr
			    cmd_str = strmid(full_cmd, 0, strlen(cmd_table(i).cmd)-1) + '             '
			    narg = mask(b2(ist+1), 0, 5)
			    arg_str = ' '
			    if (narg gt 1) then arg_str = string(b2(ist+2:ist+2+(narg<6-2)*2+1), format='(5(2z2.2,1x))') + $
						'                                              '
			    fmt = '(a8, 2x, a10, a10, 1x, a25, a35)'
			    out = string(gt_time(daytim,/str), cmd_str, cmd_table(i).mnem+'       ', $
										arg_str, cmd_table(i).descr, format=fmt)
			    print, out
                            if (lun ne 0) then printf, lun, out
			    ;
			    for iargs=5,narg-2,5 do begin
				istarg = ist+2 + iargs*2
				ienarg = ist+2 + ( ((iargs+4)<(narg-2))*2+1)
				arg_str = string(b2(istarg:ienarg), format='(31x, 5(2z2.2,1x))')
			        print, arg_str
                                if (lun ne 0) then printf, lun, arg_str
			    end
			    ;
			    ist = ist + (narg-1)*2 + 4
			    none_cnt = 0
			end else begin
			    qdone = 1
			end
		      end else begin
			qdone = 1
		      end
		    end
		end
	      end
	else: begin	;science data
		ss  = where(b eq 'aa55'xl, nss)
		for ii=0,nss-1 do begin
		    if (keyword_set(simple)) then begin
			ist = ss(ii)
			ien = (ist + 20) < 198
			print,       irec, b(ist:ien), format = '(i6,3x, 36(1x,z4.4))'
			if (lun ne 0) then printf, lun, irec, b(ist:ien), format = '(i6,3x, 36(1x,z4.4))'
		    end else begin
		        pkid = b2(12)		;unsign(rec(6), 16)
		        qtrunc = mask(pkid, 6, 1)
			extra = ''
			if (ii eq 0) and (qtrunc) then extra = '^Truncated^'
			;
			ist = ss(ii)
			ien = (ist + 20) < 198
			hdr = intarr(40)-1
			hdr(0) = b(ist:ien)
			reftime_sci = long(hdr, 2)
			;
			qnew_reftime = (reftime_sci ne last_reftime)
			last_reftime = reftime_sci
			if (qnew_reftime) then cnt_minutes = cnt_minutes + 1
			;;if (qnew_reftime) then print, ' '
			tit = "   Frm    Minute  Date    Pkg Time  SegLen   NpixTotal  NpixImage  NpixSeg  Seg#  N K    DPC"
			      ;     10     1  18-SEP-95  23:52:51               7168      14509     3584     3   0 0  bfffffb0
                        tit = $
"  Frame Min     Date      Time    SegL  PixTot PixImg  PixSeg Seg#  N K   DPC"
;     36   1   6-JAN-96  13:25:43  xxxx   3628   14509   3628   4   14 5 03006001

			if (qnew_reftime) then print, tit
			print, irec, cnt_minutes, fmt_tim(daytim), format = '(1x, i6, i4, 2x, a, $)'
			if (lun ne 0) then printf,lun, irec, cnt_minutes, fmt_tim(daytim), format = '(1x, i6, i4, 2x, a, $)'
                        print,       hdr(4), format = '(i6, $)'              ; DP Seg Len
                        if (lun ne 0) then printf, lun, hdr(4), format = '(i6, $)'              ; DP Seg Len
			l_val(0) = hdr(6) &  l_val(1) = hdr(5)
			print,       long(l_val,0), format = '(i7, $)'       ; NpixTotal
			if (lun ne 0) then printf, lun, long(l_val,0), format = '(i7, $)'       ; NpixTotal
			l_val(0) = hdr(18) &  l_val(1) = hdr(17)
			print,       long(l_val,0), format = '(i8, $)'       ; NpixImage
		        if (lun ne 0) then printf,lun,  long(l_val,0), format = '(i8, $)'       ; NpixImage
			;
			print,       hdr(7), format = '(i7, $)'              ; NpixSegment
			print,       hdr(8), format = '(1x, i3, $)'              ; Segment Number
			print,       hdr(12), hdr(13), format = '(3x, 2i2, $)'   ; N, K
			print,       long(hdr,30), extra, format = '(1x, z8.8, 2x, a)'         ; DPC
			if (lun ne 0) then printf, lun, hdr(7), format = '(3x, i4, $)'              ; NpixSegment
	                if (lun ne 0) then printf, lun, hdr(8), format = '(1x, i3, $)'              ; Segment Number
			if (lun ne 0) then printf, lun, hdr(12), hdr(13), format = '(3x, 2i2, $)'   ; N, K
			if (lun ne 0) then printf, lun, long(hdr,30), extra, format = '(1x, z8.8, 2x, a)'         ; DPC
		    end
		    none_cnt = 0
		  end
	      end

    end

    if (lun ne 0) then flush, lun

end
;-------------------------------------------------------------
pro mon_sci5k, qstop=qstop, simple=simple, fill_cnt=fill_cnt, disp_loi=disp_loi, nofile=nofile, log=log, file=file, daily=daily
;
;+
;OPTIONAL KEYWORD INPUT:
;	simple	- If set, then simply display the first 21 words of the data segment
;	fill_cnt- How often to put a message out that there were fill packets
;		  in a row.  Default is 100
;	disp_loi - If set, then display the LOI images
;	nofile	- If set, then don't write an output file
;	log	- If set, then save summary information to log directory
;	file	- If set, then write an output file
;	daily   - If set, then reset the output files daily near midnight.
;HISTORY:
;	Written Sep-95 by M.Morrison
;	15-Sep-95 (MDM) - Renamed from PR_SCI5K_HEADS to MON_SCI5K
;			- Added command echo and memory dump modes
;			- Added changes from Mathur's off-line version
;	18-Sep-95 (MDM) - Added changes from Mathur's off-line version
;	21-Sep-95 (DM)  - Modifications to allow the results to be saved
;			  to a file in addition to coming to the screen
;	28-Sep-95 (MDM) - Modified how the NONE_CNT worked 
;			- Added keyword to say how often to mark when
;			  no non-fill sci5k packets are seen in a row
;	17-Nov-95 (MDM) - Broke the routine into two parts to allow the
;			  logic to be used on a readback basis from a
;			  sci5k file.
;			- Added a flush call for each packet
;	16-Jan-96 (MDM) - Changed output file name to be UT, not local
;	24-Jan-96 (MDM) - Added /DISP_LOI option
;	30-Apr-96 (MDM) - Added option to not write to output file
;	23-May-96 (MDM) - Added /LOG option
;	 6-Jun-96 (MDM) - Added /FILE option and made /nofile the default
;	25-Jun-96 (MDM) - Modified to work with EGSE 5.1
;	11-May-99 (CED) - Some roll-logging fixes; /daily flag added.
;-
;
;
common mon_sci5k_blk, u

;
; This outer while loop is for use by the "daily" switch, which reinitializes
; *everything* daily.  Normally you get in once and stay in the while at the
; end of the program forever. --CED
;
while(1) do begin  

if (n_elements(u) ne 0) then begin  ; close up from last time through
    close, u
    free_lun, u
end
;
if (n_elements(fill_cnt) eq 0) then fill_cnt = 100
;
task_pn = string(format='((A),"/mdi_sci")',getenv("MDI_TASK_DIR"))
cmd = [task_pn,'-p', '-s 1']
if (getenv('EGSE_VER') ge '5.1') then cmd = [task_pn, '-m','200','-p', 'sci5k']
print,cmd
spawn,cmd,unit=u,/noshell
b0 = bytarr(398*4)         ; 398 bytes 
;
qdebug = 1
reftime_sci = -1
none_cnt = 0
i=0L
cnt_minutes = 0L
tmbuf = intarr(7)
;tmbuf = timstr2ex(!stime)
tmbuf = timstr2ex(ut_time())
tmstr = string(format='(3i2.2,"_",3i2.2)',tmbuf(6),tmbuf(5),tmbuf(4),tmbuf(0),tmbuf(1),tmbuf(2))

mon_fname = string(format='((A),"/", (A), ".mon")', getenv("MDI_MON5K_DIR"), tmstr)
roll_fname = string(format='((A),"/",(A),".roll")', getenv("MDI_MON5K_DIR"), tmstr)

nofile = 1 - keyword_set(file)
if (keyword_set(nofile)) then begin
    lun = 0
    rlun = 0
    print, '********* No output file being created **************'
end else begin
    openw, lun, mon_fname, /get_lun
	if keyword_set(log) then begin
	    openw,rlun, roll_fname, /get_lun
	    print,'Opened '+roll_fname+' (rlun=',rlun,')'
	end
end

still_today = 1 ; This gets cleared when the clock rolls over a UT day, causing
		; us to leave the next while loop and restarting the logs...
yesterday = strmid(anytim(systime(1)-3600L*24*fix(365.25*9),/atime),0,9)

while (not keyword_set(daily)) or (still_today) do begin

    readu,u,b0
    b1 = fix(b0(indgen(398)*4+3), 0, 199)
    decode_sci5k, b1, lun, i, none_cnt, cnt_minutes, simple=simple, fill_cnt=fill_cnt
    if keyword_set(disp_loi) or keyword_set(log) then begin
	delvarx,roll
	
	disploi_mon5k, b1, log=log, roll=roll, tref=tref, rmethod=roll_method, ecliptic_roll=ecliptic_roll,nodisplay = (keyword_set(disp_loi) eq 0)
	
	if isvalid(roll) then begin
		if rlun ne 0 then print,'ROLL IS VALID; writing to file...' $
		else print,'ROLL IS VALID; doing nothing...'
		if(rlun ne 0) then begin
			printf,rlun,tref,'	',roll,'	',ecliptic_roll,'  ('+roll_method+')',format='(A,A,F7.2,A,F7.2,A)'
			flush,rlun
		end
	end 
    end

    none_cnt = none_cnt + 1
    if ((none_cnt mod fill_cnt+1) eq fill_cnt) then print, 'Still receiving data - no data segments for last ', none_cnt+1, ' packets'
    ;if ((none_cnt mod fill_cnt+1) eq fill_cnt) then printf, lun, 'Still receiving data - no data segments for last ', none_cnt+1, ' packets'
    if ((none_cnt mod fill_cnt+1) eq fill_cnt) and (lun ne 0) then printf, lun, 'Still receiving data - no data segments for last ', none_cnt+1, ' packets'
    i = i + 1

    today = strmid(anytim(systime(1)-3600L*24*fix(365.25*9),/atime),0,9)
    if(today ne yesterday) then still_today = 0
end
;
close, u
if(lun ne 0) then close,lun
if(rlun ne 0) then close,rlun
end ; of daily while

end



