pro IRIS_MAKE_QUAT_DATABASE, date, $
	datarr, timegrid, $
	outpath = outpath, win = win, rms = rms, pstop = pstop, short = short, $
	printmnems = printmnems, fname = fname, data = data, $
	flagwin = flagwin
	
;+
; 
; Generates a text file giving the quaternions from the IRIS
; housekeeping as a function of time.
;
; INPUT:
;	date	-	The day for which to generate the file
;
; KEYWORDS:
;	outpath=	-	The path for the text file that is produced (the 
;					filename format is YYYYMMDD_iris_temp.txt)
;
;	win=	-	Size of the boxcar smoothing window, in seconds. Defaults to 
;				60; if set to 0, no smoothing is done
;
;-

; cache of timeline roll commands for the last 3 days; used if stale roll data is found
common IRIS_TIMELINE_ROLL_CB, timeline_roll_data

nullval = -9999d
mnem_map = [['SECONDARY_MIRROR_HOUSING_HOZ4_CONTROL_TS02', 'IT02SMIR'], $
	['CCD4_SJI_OPERATING', 'ITSJCCD4']]

if KEYWORD_SET(pstop) then STOP
if N_ELEMENTS(win) eq 0 then win = 10
if N_ELEMENTS(flagwin) eq 0 then flagwin = 300
if N_ELEMENTS(date) eq 0 then date = '2013-jul-17'
if N_ELEMENTS(outpath) eq 0 then outpath = '/sanhome/boerner/public_html/iris/magnetometer'

t0 = STRMID(ANYTIM2UTC(/ccsds, date), 0, 10)
data = IRIS_TIME2QUATS(/all, t0+'T00:00:00Z', t0+'T23:59:59.99Z')
tname = TIME2FILE(date, /date)

if win eq 0 then begin
	PRINT, 'Currently option to run without smoothing is disabled'
	RETURN
endif
numtimes = 86400/win
timegrid = DINDGEN(numtimes) * win + win/2. + ANYTIM2TAI(t0)

quat = data.quats
quat_tai = ANYTIM2TAI(quat.date_obs)
quat_names = TAG_NAMES(quat)
numquat = N_ELEMENTS(quat_names) - 1
quat_tags = STRARR(numquat)
if KEYWORD_SET(short) then for i = 1, numquat do $
	quat_tags[i-1] = mnem_map[1,WHERE(mnem_map[0,*] eq quat_names[i])] $
	else quat_tags = quat_names[1:*]

pos = data.pos
pos_tai = ANYTIM2TAI(pos.date_obs)
pos_names = TAG_NAMES(pos)
numpos = N_ELEMENTS(pos_names) - 1
pos_tags = STRARR(numpos)
if KEYWORD_SET(short) then for i = 1, numpos do $
	pos_tags[i-1] = mnem_map[1,WHERE(mnem_map[0,*] eq pos_names[i])] $
	else pos_tags = pos_names[1:*]
rolltagind = WHERE(pos_tags eq 'A_EULERBR_Z') + numquat

cmd = data.cmd
cmd_tai = ANYTIM2TAI(cmd.date_obs)
cmd_names = TAG_NAMES(cmd)
numcmd = N_ELEMENTS(cmd_names) - 1
cmd_tags = STRARR(numcmd)
if KEYWORD_SET(short) then for i = 1, numcmd do $
	cmd_tags[i-1] = mnem_map[1,WHERE(mnem_map[0,*] eq cmd_names[i])] $
	else cmd_tags = cmd_names[1:*]

if KEYWORD_SET(pstop) then STOP

;if KEYWORD_SET(short) then 
w = '12' 
ww = '17'
fname = tname + '_iris_pointing.txt'
outfile = CONCAT_DIR(outpath, fname)
OPENW, lun, /get_lun, outfile
ncol = numquat + numpos + numcmd + 1
PRINTF, lun, 'DATE_OBS', '', 'TFLAG', 'TIME_QBI', quat_tags, $
	'TIME_POS_VEL', pos_tags, 'OPHASE', 'TIME_CG_ROLL', cmd_tags, $
	form = '(a8,a11,a8,a25,' + STRTRIM(numquat, 2) + 'a' + ww + $
	',a25,' + STRTRIM(numpos+1, 2) + 'a' + ww + $
	',a25,' + STRTRIM(numcmd, 2) + 'a' + ww + ')'
datarr = DBLARR(numquat + numpos + numcmd + 1, numtimes) + nullval

; Fit a sine wave to A_EP_POS_J2000_Z to determine orbital phase
parinfo = REPLICATE({name:'amplitude', value:6871907.3d, fixed:0, limited:[0,0], limits:[0d,0d]}, 4)
parinfo[1].name = 'frequency'
parinfo[1].value = (2 * !pi) / 5856.
parinfo[2].name = 'phase'
parinfo[2].value = !pi/2.
parinfo[3].name = 'offset'
parinfo[3].value = 0.
tsineparams = MPFITFUN('IRIS_MP_SINECHISQ', pos_tai, pos.A_EP_POS_J2000_Z, $
	parinfo = parinfo, yfit = sinefit, /quiet)
if tsineparams[0] lt 0 then tsineparams[2] = tsineparams[2] + !pi
ophase = (tsineparams[1] * timegrid + tsineparams[2])/(2 * !pi) mod 1.0

if win ne 0 then for i = 0l, numtimes - 1 do begin
	qtdiff = ABS(quat_tai - timegrid[i])
	qmindiff = MIN(qtdiff)
	quat_in = WHERE(qtdiff eq qmindiff)
	for j = 0l, numquat - 1 do begin
		datarr[j,i] = quat[quat_in[0]].(j+1)
	endfor
	ptdiff = ABS(pos_tai - timegrid[i])
	pmindiff = MIN(ptdiff)
	pos_in = WHERE(ptdiff eq pmindiff)
	for j = 0l, numpos - 1 do begin
		datarr[j+numquat,i] = pos[pos_in[0]].(j+1)
	endfor
	datarr[numquat+numpos,i] = ophase[i]
	ctdiff = ABS(cmd_tai - timegrid[i])
	cmindiff = MIN(ctdiff)
	cmd_in = WHERE(ctdiff eq cmindiff)
	for j = 0l, numcmd - 1 do begin
		datarr[j+numquat+numpos+1,i] = cmd[cmd_in[0]].(j+1)
	endfor
	tflag = (qmindiff gt flagwin/2.) + 2 * (pmindiff gt flagwin/2.) + 4. * (cmindiff gt flagwin/2.)

	; If the roll data is stale, pick it up from the timeline
	if (qmindiff gt flagwin / 2.) then begin
		tflag = tflag + 8.
		roll_tstart = TAI2UTC(ANYTIM2TAI(t0) - (86400d*3.), /ccsds)
		if N_ELEMENTS(timeline_roll_data) ne 0 then begin
			if timeline_roll_data.tstart ne roll_tstart then begin
				refresh_timeline_roll = 1
			endif else refresh_timeline_roll = 0
		endif else begin
			refresh_timeline_roll = 1
		endelse
		if refresh_timeline_roll then begin
			default_tlrs = CREATE_STRUCT('ROLL_START', roll_tstart, 'DEGREES', 0., 'RADIANS', 0., $
				'DURATION', 0., 'ROLL_END', roll_tstart)
			timeline_roll_str = IRIS_TIME2TIMELINE(roll_tstart, t0+'T23:59:59.99Z', /roll)
			if N_TAGS(timeline_roll_str) eq 0 then timeline_roll_str = default_tlrs
			timeline_roll_data = CREATE_STRUCT('tstart', roll_tstart, 'data', timeline_roll_str)		
		endif
		tlrstai = ANYTIM2TAI(timeline_roll_data.data.roll_start)
		time_index = WHERE(timegrid[i] ge tlrstai, numpost)
		if numpost gt 0 then begin
			datarr[rolltagind,i] = timeline_roll_data.data[time_index[-1]].degrees
		endif else begin
			tflag = tflag + 16
		endelse
	endif
	
	PRINTF, lun, STRMID(ANYTIM2UTC(/ccsds, timegrid[i]), 0, 19), tflag, $
		TAI2UTC(/ccsds, [quat_tai[quat_in[0]]]), datarr[0:numquat-1,i], $
		TAI2UTC(/ccsds, [pos_tai[pos_in[0]]]), datarr[numquat:numquat+numpos,i], $
		TAI2UTC(/ccsds, [cmd_tai[cmd_in[0]]]), datarr[numquat+numpos+1:ncol-1,i], $
		form = '(a19,i8,a25,' + STRTRIM(numquat, 2) + 'f' + ww + $
		'.6,a25,6f' + ww + '.3,4f' + ww + $
		'.6,a25,' + STRTRIM(numcmd, 2) + 'f' + ww + '.6)'
endfor

FREE_LUN, lun
if KEYWORD_SET(rms) then FREE_LUN, lunrms

end




