pro mk_evn, outfil, week=week, outdir=outdir, run_time=run_time
;
;+
;NAME:
;	mk_evn
;PURPOSE:
;	To reduce the observing log information into a summary
;	of events.
;KEYWORD INPUT:
;       week    - a string with the year/week if the format
;                 91_49 where 91 is the year, 49 is the week
;                 This is required input.
;OUTPUT:
;	outfil	- The output file name
;OPTIONAL KEYWORD INPUT:
;	outdir	- The output directory for the output file.
;		  If undefined, write it to $DIR_GEN_EVN.
;HISTORY:
;	Written 1-May-92 by M.Morrison
;Ver 1.01 26-May-92 (MDM) - Changed to write a temporary file and then
;                           move it to on-line after finished generating it
;Ver 1.02 26-May-92 (MDM) - Expanded the EVN structure to have the maximum
;			    counting rate for the different instruments and
;			    the SXT FOV location
;          8-Jul-92 (MDM) - Added "outfil"
;Ver 1.03 28-Aug-92 (MDM) - Made a correction caused by BCS not giving the 
;			    proper DP mode
;Ver 1.04 28-Aug-92 (MDM) - Further correction for BCS DP mode
;Ver 1.05 11-Sep-92 (MDM) - Corrected mistake from 1.03/1.04 modification - it
;			    was recording the incorrect DP mode.
;         16-Oct-92 (MDM) - Modified to make the use of input "week" scalar
;			  - Added runtime print statement
;Ver 1.06  9-Mar-93 (MDM) - Modified to take the raw FOV_CENTER value instead
;			    of the GT_FOV_CENTER value since it has processing
;			    done to it
;			    **************************************************
;Ver 1.20 14-May-93 (MDM) - Modified to use the new OBS files (one per instrument)
;Ver 1.21 15-Nov-93 (MDM) - Modified logic so that if one instrument is missing
;			    it would work ok.
;Ver 1.22 19-Nov-93 (MDM) - Modified to avoide SQRT(neg num).  (converted to
;			    reals because integer^2 was negative.
;-
;
start_time = systime(1)
run_time = 0.
;
qdebug = 1
;
progVerNo = 1.220*1000
progName = 'MK_EVN.PRO'
;
if (n_elements(outdir) eq 0) then outdir = '$DIR_GEN_EVN'
;
week = week(0)
weekid = string(week, fix(progverno/1000), format="(a, 'a.', i2.2)")
outfil       = concat_dir('$DIR_REFORMAT_SC', 'evn'+weekid)
outfil_final = concat_dir(outdir, 'evn'+weekid)
;
weekn = fix(strmid(week, 3, 2))
yearn = fix(strmid(week, 0, 2))
tarr = week2ex( yearn, weekn )
rd_fem, anytim2ints(tarr, off=-24*60.*60), anytim2ints(tarr, off=8*24.*60.*60), fem
ss = where( (fem.week eq weekn) and (fem.year eq yearn) )
n = n_elements(ss)
sttim = fem(ss(0))
entim = fem(ss(n-1)+1)  ;go forward one orbit
;
rd_obs, sttim, entim, bcs, sxtf, sxtp, w_h
timarr = anytim2ints(!stime)
maparr = 0

nnbcs = 0
nnsxtf = 0
nnsxtp = 0
nnw_h = 0
if (get_nbytes(bcs) gt 10) then  begin & nnbcs = n_elements(bcs)   & timarr = [timarr, anytim2ints(bcs)]  & maparr = [maparr, lonarr(nnbcs)+18] & end 
if (get_nbytes(sxtf) gt 10) then begin & nnsxtf = n_elements(sxtf) & timarr = [timarr, anytim2ints(sxtf)] & maparr = [maparr, lonarr(nnsxtf)+15] & end 
if (get_nbytes(sxtp) gt 10) then begin & nnsxtp = n_elements(sxtp) & timarr = [timarr, anytim2ints(sxtp)] & maparr = [maparr, lonarr(nnsxtp)+16] & end 
if (get_nbytes(w_h) gt 10) then  begin & nnw_h = n_elements(w_h)   & timarr = [timarr, anytim2ints(w_h)]  & maparr = [maparr, lonarr(nnw_h)+17] & end 
if (n_elements(timarr) eq 1) then begin
    print, 'MK_EVN: Returnning - no obs data for any instrument'
    return
end
timarr = timarr(1:*)
maparr = maparr(1:*)
;
ss_arr = sort(int2secarr(timarr))
;
infil = concat_dir('$DIR_GEN_OWH', 'owh'+week+'a.01')
openr, lun, infil, /block, /get_lun
rd_pointer, lun, pointer, recsize
rd_fheader, lun, fheader_in, ndset
;
lunout = 2      ;output log
gen_struct, file_header=fhead
evn_struct, evn_version=evn_version, evn_summary=out_ref
obs_struct
ref_struct, ref
fhead.refverno = fheader_in.refverno
fhead.ref2verno = fheader_in.ref2verno
;
rsiz = ref.EVN_Fil_Rec_Siz
open_da_file, lunout, '', '', outfil, rsiz, bytout, fpoint, /nolower
;
ndatasets = 0
qnew = 1
qfirst = 1
dp_mode = -1
for iss=0L,n_elements(ss_arr)-1 do begin
    ii = ss_arr(iss)
    entry_type = maparr(ii)
    case entry_type of
	15: struct = sxtf( ii - nnbcs )
	16: struct = sxtp( ii - nnbcs - nnsxtf )
	17: struct = w_h(  ii - nnbcs - nnsxtf - nnsxtp )
	18: struct = bcs(  ii )
    endcase 

    if (entry_type eq 0) then goto, skip
    if ((entry_type ge 15) and (entry_type le 17)) then dp_mode = gt_dp_mode(struct) ;don't look at bcs for mode

    if (not qfirst) then begin
	event = 0
	if (dp_mode ne last_dp_mode) then event = 1
	if (iss eq n_elements(ss_arr)-1) then event = 2
	if (int2secarr(struct, last_struct) gt 120) then event = 2
	if (event ne 0) then begin
	    outrec = out_ref
	    outrec.time		= first_struct.time
	    outrec.day		= first_struct.day
	    outrec.dp_mode	= dp_mode_out
	    outrec.duration	= int2secarr(last_struct, first_struct)
	    outrec.event	= event
	    outrec.nsxt_pfi	= nsxt_pfi
	    outrec.nsxt_ffi	= nsxt_ffi
	    outrec.nbcs		= nbcs
	    outrec.nmf		= nmf

	    outrec.HXT_sum_L    = HXT_sum_L
	    outrec.HXT_sum_M1   = HXT_sum_M1      
	    outrec.HXT_sum_M2   = HXT_sum_M2      
	    outrec.HXT_sum_H    = HXT_sum_H       

	    outrec.WBS_sxs1     = WBS_sxs1        
	    outrec.WBS_sxs2     = WBS_sxs2        
	    outrec.WBS_hxs      = WBS_hxs         
	    outrec.WBS_grs1     = WBS_grs1        
	    outrec.WBS_grs2     = WBS_grs2        
	    outrec.WBS_rbmsc    = WBS_rbmsc       
	    outrec.WBS_rbmsd    = WBS_rbmsd       

	    outrec.total_cps	= total_cps	
	    outrec.All_cps	= All_cps		
	    outrec.Acc_cps	= Acc_cps		

	    outrec.fov_center	= fov_center	
	    outrec.fov_change	= fov_change	

	    rdwrt, 'W', lunout, bytout, rsiz, outrec, 1

	    if (qdebug) then print, fmt_tim(first_struct), '  ', event, outrec.duration, ' sec' , $
		string(nsxt_pfi, nsxt_ffi, nbcs, nmf, format="(' SXTP=', i3, ' SXTF=', i3, ' BCS=', i3, ' MF=', i3)"), $
		'  ', gt_dp_mode(outrec.dp_mode, /str)

	    ndatasets = ndatasets + 1
	    qnew = 1
	end
    end

    if (qnew) then begin
	qfirst = 0
	first_struct	= struct
	last_struct	= struct	;because will not update "last_struct" with bcs entries
	dp_mode_out = gt_dp_mode(first_struct)
	nsxt_pfi	= 0
	nsxt_ffi	= 0
	nbcs		= 0
	nmf		= 0

	HXT_sum_L       = 0
	HXT_sum_M1      = 0
	HXT_sum_M2      = 0
	HXT_sum_H       = 0

	WBS_sxs1        = 0
	WBS_sxs2        = 0
	WBS_hxs         = 0
	WBS_grs1        = 0
	WBS_grs2        = 0
	WBS_rbmsc       = 0
	WBS_rbmsd       = 0

	total_cps	= intarr(4)
	All_cps		= bytarr(4)
	Acc_cps		= bytarr(4)

	fov_center	= [0,0]
	fov_change	= 255
	qfirst_fov	= 1

	qnew = 0
    end

    case entry_type of
	31:		;continuation mark
	 0: 		;file ID mark
	15: begin	;sxt FFI rec
		nsxt_ffi = nsxt_ffi + 1
		dp_mode_out = gt_dp_mode(struct)	;over-ride earlier value since if it was from BCS, it is probably wrong
	    end
	16: begin	;sxt PFI rec
		nsxt_pfi = nsxt_pfi + 1
		dp_mode_out = gt_dp_mode(struct)	;over-ride earlier value since if it was from BCS, it is probably wrong

		if (qfirst_fov) then begin
		    ;;fov_center = gt_fov_center(struct)*60	;convert back to arcsec
		    fov_center = struct.fov_center*60.		;convert back to arcsec
		    fov_change = 0
		    qfirst_fov = 0
		end else begin
		    ;;fov_center2 = gt_fov_center(struct)*60	;convert back to arcsec
		    fov_center2 = struct.fov_center*60.		;convert back to arcsec
		    del = sqrt( total( (fov_center-fov_center2)^2 ))
		    fov_change = (del/30)<250
		end
	    end
	17: begin	;wbs/hxt rec
		dp_mode_out = gt_dp_mode(struct)	;over-ride earlier value since if it was from BCS, it is probably wrong
		nmf = nmf + 2

		HXT_sum_L       = max([HXT_sum_l,  struct.hxt_sum_l])
		HXT_sum_M1      = max([HXT_sum_m1, struct.hxt_sum_m1])
		HXT_sum_M2      = max([HXT_sum_m2, struct.hxt_sum_m2])
		HXT_sum_H       = max([HXT_sum_h,  struct.hxt_sum_h])

		WBS_sxs1        = max([WBS_sxs1,  struct.wbs_sxs1])
		WBS_sxs2        = max([WBS_sxs2,  struct.wbs_sxs2])
		WBS_hxs         = max([WBS_hxs,   struct.wbs_hxs])
		WBS_grs1        = max([WBS_grs1,  struct.wbs_grs1])
		WBS_grs2        = max([WBS_grs2,  struct.wbs_grs2])
		WBS_rbmsc       = max([WBS_rbmsc, struct.wbs_rbmsc])
		WBS_rbmsd       = max([WBS_rbmsd, struct.wbs_rbmsd])
	    end
	18: begin	;bcs rec
		nbcs = nbcs + 1

		for i=0,3 do begin
		    total_cps(i) = max([total_cps(i), gt_total_cnts(struct,i+1)])
		end
		if (struct.acc_interval ne 0) then for i=0,3 do begin
		    v = sqrt(fix(struct.all_cnts(i))^2 / struct.acc_interval)
		    all_cps(i)   = max([all_cps(i), v])
		    v = sqrt(fix(struct.acc_cnts(i))^2 / struct.acc_interval)
		    acc_cps(i)   = max([acc_cps(i), v])
		end
	    end
	else:		;do nothing
    endcase

    last_dp_mode = dp_mode
    if ((entry_type ge 15) and (entry_type le 17)) then last_struct = struct

    skip:
end
;
;-------------------- Write out pointer and file header

maxsamps = get_nbytes(outrec)
totbytes = bytout

fpoint.TotBytes         = totbytes

;fhead.first_Time        = first_time
;fhead.first_Day         = first_day
;fhead.last_Time         = last_time
;fhead.last_Day          = last_day

fhead.nDataSets         = nDataSets
fhead.maxSamps          = maxSamps

fpoint.data_version     = evn_version.data
file_id = weekid
wrt1p_fh, lunout, fpoint, fhead, rsiz, progName, progVerNo, file_id, 'EVN', 'EVN'
;
free_lun, lun
close, lunout
;
if (n_elements(outfil_final) ne 0) then begin
    cmd = 'rm -f ' + outfil_final               ;remove any copy of the file that might already exist
    spawn, cmd
    cmd = 'mv ' + outfil + ' ' + outfil_final
    spawn, cmd
    outfil = outfil_final
end

end_time = systime(1)
run_time = (end_time-start_time)/60.
print, 'MK_EVN took ', run_time, ' minutes to run'
;
end
