;FUTURE:
;	* check file name length
;	* implement the sub-version numbering for load number
;
;	* pass on the vector number when using replace on .ips programs 
;	* assign an ipvector number automatically for all .ips labels starting with QPROG
;	* Put the "set ipvector address" instructions into the code load file
;
;RULES:
;	File name length limitations:
;		20 characters in total without the extension
;		12 characters pre-frozen (allows for "q_" and "_v01_1")
;		 8 characters pre-class (allows for "obs_" and "cam_")
;	Observation vector address is
;		(4086 - address) / 2	= observation #
;		4086 - obs*2		= vector address
;+
;NAME:
;	opsdb
;PURPOSE:
;	Manage the IP queue and DEP memory resources
;OPTIONS:
;	copy	- will rcp the files from mdisim
;	prep	- will use the prep directory & database
;	unfreeze- will pull the online file from the flight directory (instead of "copy" from
;		  mdisim).  Uses prep directory too.
;HISTORY:
;	Written Oct to Dec-95 by M.Morrison
;	 5-Dec-95 (MDM) - Implemented ID assignments for campaigns and
;			  observations.
;	 7-Dec-95 (MDM) - Incorporated new capabilities for "obstran" (the routine
;			  which converts from .obs files to .src).  Capbilities
;			  were to allow the call to specify the address and slot.
;			- Multiple changes to .CAM format
;	 8-Dec-95 (MDM) - Changed the SIMP_CAM labels for prime30 label
;			  from OBS_PRIME30 to OBS_STD_STR30
;			- Modification to GET_ADDR to ignore the heritage load
;			  replacement addresses when finding the next available
;			  slot
;			- Corrected error to GET_ADDR for OBS and CAM case
;	11-Dec-95 (MDM) - Added PRIME keyword option on MK_SIMP_CAM
;			- Added translation capability going from .uobs to obs
;			  to specify the ticks and choose the closes table entry
;			- Added EXPOSURE.TAB processing capability
;			- Added REPLACE option onf MK_OBS_SRC and MK_CAM_SRC
;	12-Dec-95 (MDM) - Modified to allow .ips exensions on the input file
;			  name into mk_ips_src and mk_ipvec_src
;			- Made the src output file of the .ips files have an extra
;			  _1 for load number after the _v03 if OPSDB_LOAD_VER is
;			  set to "yes"
;	13-Dec-95 (MDM) - Corrected the /replace option for the MK_OBS_SRC routine
;			- Made the src output file of the .ips files have an extra
;			  _1 for load number after the _v03 if OPSDB_LOAD_VER is
;			  set to "yes" for OBS and CAM load generation.
;			- added new style to OPSDB_PRINT to list the campaigns and
;			  observtion IDs
;			- Corrected error where uobs description was not being
;			  recorded into the database.
;			- Wrote dummy write routine to save all info as ASCII
;			  for when IDL writting breaks
;			- Wrote fixup routine to make sure there are no blanks for
;			  the critical text fields.
;			- Made MK_SIMP_CAM have 1024 as the default number of repeats
;			- Created LATEST_VER to get the latest file version filename
;			- Force uobs translation to stop when IP name results in a
;			  vector = 0
;	17-Jan-96 (MDM) - Patched LATEST_VER to work with unversioned files
;			- Corrected GET_ID to only look for active observations
;			  when the /INDEX option is used
;			- Trap when don't recognize the observation in the header
;			  of the campaign list (don't default to anything)
;	18-Jan-96 (MDM) - Added logic to pass the index foward when using /REPLACE
;			  on processing .ips files.
;			- Make the LATEST_VER routine stop if the result is a null
;			  file name
;			- Added the capability to override the IP program by
;			  specifying in the campaign list.
;			- Added /ID option to GET_INFO
;			- Patched MK_OBS_SRC to get the ID if not passed a UOBS
;			  (the ID should have already been assigned)
;	24-Jan-96 (MDM) - Modified to use macl instead of cmd 0x91 for setting vector
;			  address.
;			- Wrote opsdb_proc_lst to simplify the load making
;	25-Jan-96 (MDM) - Added neting option to the mk_cam_src routine
;			- Added DELETE_OBS and DELETE_CAM options in the proc_lst routine
;			- Added title to the standard listing output
;			- Added sort options to the listing routine
;	29-Jan-96 (MDM) - Patched print routine to not do a title for IP_Symbols.dat output option
;			- Modified mk_ips_src to output macls
;			- Changed to have .reg be the file extension for the register table (used to be .tab)
;			- Removed all test subroutines
;			- Wrote opsdb_mk_reload and opsdb_test_lst
;	30-Jan-96 (MDM) - Corrected error in mk_reload (wasn't getting the
;			  correct items where multiple items reside as the same
;			  address (ie obs_std_str60)
;			- Nested loop in campaign, # obs to nest should be N-1
;			- Made mk_cam_src repeat count passed in be N, not N-1
;	 8-Feb-96 (MDM) - Changed the logic on how the nested loop repeats were
;			  calculated.
;			- Corrected the nesting loop count (it was off by 1)
;	11-Feb-96 (MDM) - Correced overall obs count when using nested loop.
;			  (the count is for how many "obs/nests" not how many obs)
;	12-Feb-96 (MDM) - Made proc_lst have pad=16 as the default for call to mk_ips_src
;			- Fixed number of observations in NEST to be N-1 in the load
;	27-Feb-96 (MDM) - Added /RESET option to proc_lst
;	 1-Mar-96 (MDM) - Made the set_ipvec use mbipcmd instead of mbipmacl (reverting back to the old way)
;	 4-Mar-96 (MDM) - Changed format statement for campaign address from i4 to i5
;	 5-Mar-96 (MDM) - Added LOAD_CMD option to proc_lst
;	 5-Mar-96 (MDM) - Modified proc_lst to ask if the certify instruction should be issued
;	 8-Mar-96 (MDM) - Allowed "NREP" option for alt count for campaigns
;	21-Mar-96 (MDM) - Made the OPSDB_PRINT title display the UT time when it was run
;	 1-Apr-96 (MDM) - Modified MK_SIMP_CAM to take the description of the observation
;	 4-Apr-96 (MDM) - Corrected to write out the IP symobls in upper case 
;			  for the 'ipl' (linker) input
;	 4-Apr-96 (MDM) - Made the labels be stored as lower case
;	19-Apr-96 (MDM) - Added /FORCE option for the freeze (switch to proc_lst)
;	25-Apr-96 (MDM) - Added new print option for RDB file with cam and obs information
;	25-Apr-96 (MDM) - Added option to REG_IPS_SRC to allow labels in the definition
;	30-Apr-96 (MDM) - Changed the pad to be 8 words between modules
;	20-May-96 (MDM) - Changed MK_RELOAD to make 3 files (IP/DEP/Oth)
;	 3-Jun-96 (MDM) - Added disabling the queue at the top of the "reload_ip" command file
;	 3-Jun-96 (MDM) - Corrected the way that set_ipvec list is generated by mk_reload (did proper time ordering)
;	 4-Jun-96 (MDM) - Corrected cam_reg list generated by mk_reload
;	 5-Jun-96 (MDM) - Merged in the off-line changes to opsdb_print to allow html output
;	 8-Jul-96 (MDM) - Added ROUND to the UOBS2OBS for the time calculation
;			- Added workaround which made the SOURCE Line of the ips files have the path
;	10-Jul-96 (MDM) - Fix SOURCE line for CAM and OBS generation
;	22-Jul-96 (MDM) - Various patches/improvements
;			- Modified IP reg to .src file to break mbipldin commands to be no longer than
;			  a setreg of 8
;	25-Jul-96 (MDM) - Patched making of load file for the /prep case
;	25-Jul-96 (MDM) - Change to do two repeats of the DMA (uobs2obs) instead of one pair plus 2 of the same page
;	 1-Aug-96 (MDM) - Added '-force' to the freeze call
;	 6-Aug-96 (MDM) - Protected mk_ipv_src from unrecognized labels
;	14-Nov-96 (MDM) - Changed "mdibbs" to "mdisim" for rcp (/copy option)
;	19-Nov-96 (MDM) - Modified to use CFL_UTIL for EGSE >= 5.2
;	 9-Dec-96 (MDM) - Put 19-Nov-96 mod online
;			- Added option for printing delta between addresses
;	 7-Jan-97 (MDM) - Moved a "cd" command in proc_lst
;	 8-Jan-97 (MDM) - Removed the "cd" commands that were put into the load file
;		  	- Write the opsdb.lst file to the home directory
;	 4-Mar-97 (MDM) - Modified to have "dev2/src" output always go to "dev/src"
;	11-Mar-97 (MDM) - Added creating load.lst file for all active frames
;	 2-Apr-97 (MDM) - Make IPVEC use FILE_MOVE
;			- Code 3 with /delta option cleaned up in opsdb_print
;			- Fixed nested loop load building error
;	 7-Apr-97 (MDM) - Added forcing a database read within opsdb_proc_list
;			- Patch up "cam_p30c_fd_c1" problem
;	27-May-97 (MDM) - Removed 'cd c "flight"' from the reload cfl files
;	27-Oct-97 (MDM) - Slight tweak to opsdb_new_tuning
;	 3-Nov-97 (MDM) - Modified opsdb_cfl_util
;	10-Dec-97 (MDM) - Changed to look/write to FLIGHT not PREP cfl dir 
;			  (because of freeze change)
;	17-Dec-97 (MDM) - Changed default action of OPSDB_NEW_TUNING output
;			  file-wise
;	17-Dec-97 (MDM) - Changed creation of load file to be not done in
;			  the final output file location
;	17-Dec-97 (MDM) - Removed restriction that the mdi_uobs file had to
;			  be tab delimited
;	 4-Jan-98 (MDM) - Added /FREEZE_ONLY option (works on mdisas only)
;	16-Apr-98 (MDM) - Re-removed "certify" option (did on 17-Dec too)
;			- Added "unfreeze" option
;	21-Apr-98 (MDM) - (16-Apr mods were not put online yet)
;			- Added trapping for freeze errors
;	23-Apr-98 (MDM) - Get the load file back from the temp area when
;			  running with /prep
;     26-Jan-2000 (RIB) - Fixed Y2K problem in selection of uobs file
;
;NOTES:
;	* The repeat number for the campaign list is N+1 (a value of 1
;	  gives you two repeats)
;-----------------------------------------------------------------
function opsdb_init_src_fil, file, qwrite=qwrite
;
;
;
out = ['# File: ' + file, $
		'#', $
		'program "%Z% MODULE: %M% RELEASE: %R%.%L% CREATED: %G% %U%"', $
		'#=======================================================', $
		'source "' + file +'"', $
		'descr "UNKNOWN"', $
		'#', $
		'#']
if (keyword_set(qwrite)) then begin
    ssw_file_delete, file
    file_append, file, out
end
;
return, out
end
;-----------------------------------------------------------------
function opsdb_get_struct
;
;
;
out = {opsdb_ver10, type: '---', label: '---', id: 0L, descr: '---', $
	index: 0L, addr: 0L, nwords: 0L, forv: '---', $
	created: 0D, validated: 0D, loaded: 0D, removed: 0D, $
	last_used: 0D, $
	descr2: '---', descr3: '---'}
;
return, out
end
;-----------------------------------------------------------------
pro opsdb_patchup_info, info0
;
;
;for i=0,n-1 do for j=0,n_elements(tag_names(info))-1 do if (data_type(info.(j)) eq 7) then if (strtrim(info(i).(j),2) eq '') then info(i).(j) = '---'
;
tags = tag_names(info0)
for j=0,n_elements(tag_names(info0))-1 do if (data_type(info0.(j)) eq 7) then begin		;MDM added 11-Dec-95
    ss = where(strtrim(info0.(j),2) eq '', nss)
    if (nss ne 0) then begin
	;;info0(ss).(j) = '---'
	info2 = info0(ss)
	info2.(j) = '---'
	info0(ss) = info2
	print, tags(j), ' tag is blank for label: ' + info0(ss).label
    end
    info0.(j) = strtrim(info0.(j),2)
end
;
end
;-----------------------------------------------------------------
pro opsdb_fix_prob1
;
;	7-Apr-97 patch to Dnyanesh running opsdb_proc_lst on "dev" and then "prep" on mdisas
;
common opsdb_blk, dir, filnam, info
setenv, 'MDI_OPSDB_TYPE=PREP'
opsdb_rd_wrt, /qread
;
ss=where(info.label eq 'cam_p30c_fd_c1', nss) 
info(ss(nss-1)).removed = info(ss(nss-1)).loaded	;mark the last one as removed
info(ss(nss-2)).removed = 0
info(ss(nss-2)).forv    = 'cam_p30c_fd_c1_v01.cam'
;
ss=where((info.label eq 'cam_test') and (info.id eq 'f6'x), nss) 	;wrong file name
info(ss).forv = 'cam_test_v04.cam'
ss=where((info.label eq 'cam_test') and (info.id eq 'f8'x), nss) 	;bogus ID, never happened
info(ss).removed = info(ss).loaded
;
opsdb_rd_wrt, /qwrite
opsdb_rd_wrt, /qbackup
end
;-----------------------------------------------------------------
pro opsdb_fix_prob2
;
;	7-Apr-97 patch to Dnyanesh running opsdb_proc_lst on "dev" and then "prep" on mdisas (more fixes)
;
common opsdb_blk, dir, filnam, info
setenv, 'MDI_OPSDB_TYPE=PREP'
opsdb_rd_wrt, /qread
;
ss = where(info.loaded ge int2secarr('3-Mar-97','1-jan-58'))
;opsdb_print,info(ss),20  
;
ss=where((info.label eq 'obs_new_hr_mag') and (info.id eq '137'x), nss)		;dev, not prep
info(ss).forv = 'obs_new_hr_mag_v01.uobs'
info(ss).id = '136'x		;correct ID
;
ss=where((info.label eq 'obs_new_fd_mag') and (info.id eq '136'x), nss)		;dev, not prep
info(ss).forv = 'obs_new_fd_mag_v03.uobs'
info(ss).id = '137'x		;correct ID

opsdb_print, /obs, /active

;
opsdb_rd_wrt, /qwrite
opsdb_rd_wrt, /qbackup
end
;-----------------------------------------------------------------
pro opsdb_problem_wrt, file, out, qread=qread
;
common opsdb_blk, dir, filnam, info
;
if (n_elements(file) eq 0) then file = 'opsdb_problem_wrt' + ex2fid(anytim2ex(!stime))
fmt = '(a30, a30, i10, a50,   3i10, a30,   5f14.2,   a50, a50)'
fmt = '(a30, 1x, a30, 1x, i10, 1x, a50,   1x, i10,1x,i10,1x,i10,1x, a30,   1x, 5f14.2,   1x, a50, 1x, a50)'
;
if (not keyword_set(qread)) then begin
    openw, lun, file, /get_lun
    printf, lun, 'Problems with IDL save.  Writing it out as ascii'
    printf, lun, info, format=fmt
end else begin
    openr, lun, file, /get_lun
    spawn, ['wc', '-l', file], result, /noshell
    n = 0
    reads, result(0), n
    out = replicate(opsdb_get_struct(), n-1)
    lin = ' '
    readf, lun, lin
    ;readf, lun, out, format=fmt
    for i=0,n-2 do begin
	readf, lun, lin
	out0 = out(i)
	if (strlen(lin) ne 360) then print, 'Line ', i, ' is not 360 characters long'
	while (strlen(lin) lt 360) do lin = lin+' '
	if (i ge 341) then print, lin
	reads, lin, out0, format=fmt
	out(i) = out0
    end
end

free_lun, lun
end
;-----------------------------------------------------------------
function fmt_duration, sec
;
;
;
if (sec lt 0) then return, '    Still Present'
;
temp = sec
days = fix(temp/86400)		& temp = temp - days*86400
hrs  = fix(temp/60/60)		& temp = temp - hrs*60*60
min  = fix(temp/60)		& temp = temp - min*60
sec  = fix(temp)
out = string(days, hrs, min, sec, format='(i3," days ", i2.2, ":", i2.2, ":", i2.2)')
return, out
end
;-----------------------------------------------------------------
pro opsdb_rd_wrt, qread=qread, qwrite=qwrite, init=init, qbackup=qbackup
;
;+
;METHOD:
;	environment variable OPSDB_TYPE needs to be defined and the
;	filename is derived as follows
;		MDI_OPSDB_TYPE		Filename
;		----------		--------
;		DEV			opsdb_dev
;		SIM			opsdb_sim (needed?)
;		PREP			opsdb_prep
;		FLIGHT			opsdb_flt
;
;
;
common opsdb_blk, dir, filnam, info
;
case getenv('MDI_OPSDB_TYPE') of
    '': begin
	    print, 'MDI_OPSDB_TYPE is not defined.  Stopping.
	    stop
	end
    'DEV': filnam0 = 'opsdb_dev'
    'SIM': filnam0 = 'opsdb_sim'
    'PREP': filnam0 = 'opsdb_prep'
    'FLIGHT': filnam0 = 'opsdb_flight'
    else: begin
	    print, 'MDI_OPSDB_TYPE not recognized.  Stopping...
	    stop
	end
endcase
;
dir = getenv('MDI_OPS_IP_DEP')
filnam = concat_dir( dir, filnam0)
filnam2 = filnam + '.genx'
;
if (keyword_set(init)) then begin
    info = opsdb_get_struct()
    return
end
;
if (keyword_set(qwrite)) then begin
    if (data_type(info) ne 8) then begin
	message, 'Write requested with no data defined', /info
	return
    end
    ;
    ssw_file_delete, filnam2
    savegen, info, file=filnam
end
;
if (keyword_set(qbackup)) then begin
    if (data_type(info) ne 8) then begin
	message, 'Write requested with no data defined', /info
	return
    end
    ;
    fid = ex2fid(anytim2ex(!stime))
    filnam2 = concat_dir(dir, filnam0 + fid)
    ssw_file_delete, filnam2
    savegen, info, file=filnam2
end
;
if (n_elements(info) eq 0) then qread = 1
if (keyword_set(qread)) then begin
    if (not file_exist(filnam2)) then begin
	message, 'Input file does not exist: ' + filnam, /info
	return
    end
    ;
    print, 'Restoring: ' + filnam
    restgen, info0, file=filnam
    n = n_elements(info0)
    info = replicate(opsdb_get_struct(), n)
    info = str_copy(info, info0)
end
;
end
;-----------------------------------------------------------------
function opsdb_get_info, list, active=active, all=all, type=type, label=label, $
			nostr=nostr, nmatch=nmatch, index=index, id=id, addr=addr
;
;
;
common opsdb_blk, dir, filnam, info
opsdb_rd_wrt				;make sure stuff has been read
;
out = -1
;
if (data_type(info) ne 8) then begin
    message, 'No information defined
    return, out
end
;
sea_str = ''
if (keyword_set(type)) then   sea_str = [sea_str, '(strupcase(info.type) eq "' + strupcase(type) + '")']
;if (keyword_set(label)) then  sea_str = [sea_str, '(strupcase(info.label) eq "' + strupcase(label) + '")']
if (keyword_set(label)) then  sea_str = [sea_str, "(strupcase(info.label) eq '" + strupcase(label) + "')"]
if (keyword_set(active)) then sea_str = [sea_str, '(info.removed eq 0)']
if (keyword_set(all)) then    sea_str = [sea_str, '(info.label ne "")']
if (n_elements(sea_str) eq 1) then begin
    print, 'OPSDB_GET_INFO: No search criteria specified'
    return, out
end
sea_str = arr2str(sea_str(1:*), delim=' and ')
sea_str = 'out = where( ' + sea_str + ', nmatch)'
;;print, 'GET_INFO Sea_str: ', sea_str

stat = execute(sea_str)

if (keyword_set(nostr)) then return, out
if (out(0) ne -1) then out = info(out)
;
if (keyword_set(index)) then begin
    if (data_type(out) eq 8) then out = out.index $
				else out = -1
end
if (keyword_set(id)) then begin
    if (data_type(out) eq 8) then out = out.id $
				else out = -1
end
if (keyword_set(addr)) then begin
    if (data_type(out) eq 8) then out = out.addr $
				else out = -1
end
;
return, out
end
;-----------------------------------------------------------------
pro opsdb_rm_entry, label, all=all, obs=obs, cam=cam
;
;
;	opsdb_rm_entry, label
;	opsdb_rm_entry, /all
;	opsdb_rm_entry, /obs
;	opsdb_rm_entry, /cam
;
;
common opsdb_blk, dir, filnam, info
opsdb_rd_wrt				;make sure stuff has been read
;
if (keyword_set(all)) then begin
    info2 = opsdb_get_info(/active)
    if (data_type(info2) ne 8) then return		;nothing to remove
    label = info2.label
end
;
if (keyword_set(obs)) then begin
    info2 = opsdb_get_info(type='OBS', /active)
    if (data_type(info2) ne 8) then return		;nothing to remove
    label = info2.label
end
;
if (keyword_set(cam)) then begin
    info2 = opsdb_get_info(type='CAM', /active)
    if (data_type(info2) ne 8) then return		;nothing to remove
    label = info2.label
end
;
n = n_elements(label)
for i=0,n-1 do begin
    list2 = opsdb_get_info(label=label(i), /active, /nostr)
    if (list2(0) ge 0) then begin
	info(list2).removed = int2secarr(!stime, '1-Jan-58')
	print, 'Previous entry ' + label(i) + ' is being updated as removed'
    end
end
;
end
;-----------------------------------------------------------------
pro opsdb_add_entry, info0, remove_old=remove_old, noindex=noindex
;
;
common opsdb_blk, dir, filnam, info
opsdb_rd_wrt				;make sure stuff has been read
;
;
ss = where(strtrim(info0.label,2) eq '', nss)
if (nss gt 0) then begin
    print, 'OPSDB_ADD_ENTRY: Sorry, there is a blank label in the requested update.
    print, 'OPSDB_ADD_ENTRY: No updates being made
    stop
    return
end
;
n = n_elements(info0)
if (keyword_set(remove_old)) then opsdb_rm_entry, info0.label
;
for j=0,n_elements(tag_names(info0))-1 do if (data_type(info0.(j)) eq 7) then begin		;MDM added 11-Dec-95
    ss = where(strtrim(info0.(j),2) eq '', nss)
    if (nss ne 0) then info0(ss).(j) = '---'
end
;
info0.label = strlowcase(info0.label)		;MDM added 4-Apr-96
info0.type  = strupcase(info0.type)		;MDM added 4-Apr-96
time = int2secarr(!stime, '1-Jan-58')
info0.created   = time
info0.validated = time
info0.loaded    = time
info = [info, info0]
;
end
;-----------------------------------------------------------------
pro opsdb_print, info, code, outfil=outfil, qstop=qstop, all=all, noheader=noheader, $
		active=active, quiet=quiet, cam=cam, obs=obs, qadr=qadr, ipreg=ipreg, $
		sort_id=sort_id, sort_addr=sort_addr, sort_lab=sort_lab, $
                httpdir=httpdir, delta=delta
;
;
;	opsdb_print, /cam
;	opsdb_print, /obs, /active
;	opsdb_print,xx,20,/obs
;
if (keyword_set(all)) then info = opsdb_get_info(/all, active=active)
if (keyword_set(qadr)) then begin
    info = opsdb_get_info(type='QADR', active=active)
    if (n_elements(code) eq 0) then code = 3
end
if (keyword_set(ipreg)) then begin
    info = opsdb_get_info(type='IPRL', active=active)
    if (n_elements(code) eq 0) then code = 3
end
if (keyword_set(cam)) then begin
    info = opsdb_get_info(type='CAM', active=active)
    if (n_elements(code) eq 0) then code = 5
end
if (keyword_set(obs)) then begin
    info = opsdb_get_info(type='OBS', active=active)
    if (n_elements(code) eq 0) then code = 5
end
;
if (keyword_set(outfil)) then begin
    ssw_file_delete, outfil
    openw, lun, outfil, /get_lun
    if (not keyword_set(noheader)) then begin
	printf, lun, 'OPSDB_PRINT Run ' + ut_time() + ' UT'
	printf, lun, ' '
    end
end
if (n_elements(code) eq 0) then code = 0
n = n_elements(info)
if (data_type(info) ne 8) then begin
    print, 'OPSDB_PRINT: Input must be a structure'
    return
end
;
if (keyword_set(sort_id)) then info = info( sort(info.id) )
if (keyword_set(sort_addr)) then info = info( sort(info.addr) )
if (keyword_set(sort_lab)) then info = info( sort(info.label) )
;
case code of
    0:    tit = 'label/type/id  addr/nwords
    1:    tit = 'Description and when loaded
    2:    tit = 'When loaded/remove and duration
    3:    tit = '   Label                Type     ID  Index Addr Size (Addr Hex)
		;QPROG_STR_60            QADR   0000   0    256    0 (0100-00FF)
    5:	  tit = '   Label                Type     ID  Index Addr  Size (Addr Hex)             Description
		; obs_hr_vel60            OBS    0051  12  14532  252 (38C4-39BF)  60 second observation to take HR velocity with PRIME00
    20:	  tit = ['NAME	ID	FILE', $
		'----------------	----	--------------------']
    99:   tit = ''
    500:  tit = '   Label           ID  Index Size (Addr Hex)             Description
                ; cam_std_alt30    002E   88   44 (1138-1163)  Test campaign to run the ALT
    501:  tit = '   Label                 ID  Index Size (Addr Hex)             Description
                ; obs_foc5_str60   (obs) 006F    0  252 (3F0C-4007)  Out of focus obs (FOC5)
    else: begin
	    Print, 'OPSDB_PRINT: Code ', code, ' not recognized'
	    if (keyword_set(lun)) then free_lun, lun
	    return
	end
endcase
prstr, tit
if (keyword_set(lun) and keyword_set(tit)) then prstr, tit, lun
;
for i=0,n-1 do begin
    info0 = info(i)
    for j=0,n_elements(tag_names(info0))-1 do if (data_type(info0.(j)) eq 7) then $
		info0.(j) = info0.(j) + '                                                             '
    str1 = string( info0.label, info0.type, info0.id, format = '(1x, a24, a6, 1x, Z4.4)')
    str1b= string( info0.index, format='(i5)')
    str2 = string( info0.descr, format = '(1x, a60)')
    str3 = string( info0.addr, info0.nwords, format = '(1x, i6, i5)')
    str3b= string( info0.addr, info0.addr + info0.nwords-1, format = '(1x, "(", Z4.4, "-", Z4.4, ")")')
    str5 = strtrim( info0.descr, 2 ) + '                                                                   '
    str5 = strmid(str5, 0, 60) + ' '
    if (code eq 1) or (code eq 2) then begin		;done for speed reasons
	str4a= ' ' + fmt_tim(anytim2ints('1-jan-58', off=info0.created))
	str4c= ' ' + fmt_tim(anytim2ints('1-jan-58', off=info0.loaded))
	str4d= ' ' + fmt_tim(anytim2ints('1-jan-58', off=info0.removed))
    end
    str99= string( strupcase(info0.label), info0.descr2, info0.addr, info0.type, info0.nwords, format='(a24, a12, i8, 2x, a12, i6)')
    case code of
	 0: str = str1 + str3
	 1: str = str1 + str2 + str4a
	 2: str = str1 + str4c + ' -->' + str4d + fmt_duration( info0.removed - info0.loaded )
	 3: str = str1 + str1b + str3 + str3b
	 5: str = str1 + str1b + str3 + str3b + '  ' + str5
	20: str = string(info0.label, info0.id, info0.forv, format='(a24, "	", Z4.4, "	", a30)')
	99: str = str99
        500: begin
                httpfile = concat_dir(httpdir, strtrim(info0.forv,2)+'.html')
                str000 = str2html(httpfile, link = string(info0.label+'               ', format='(a16)'))
                ;str000 = str000(1)
                ;;str000 = str_replace(str000, '<B>', '<B><pre>')
                ;;str000 = str_replace(str000, '</B>', '</pre></B>')
                str = string( str000, info0.id, info0.index, info0.nwords, str3b, str5, $
                                        format = '(1x, a, 1x, Z4.4, i5, i5, a, 2x, a)')
             end
        501: begin
                uobs_fil = strtrim(info0.forv,2)
                link = string(info0.label+'               ', format='(a16)')
                ;
                uobs_fil2 = uobs_fil + '.html'
                uobs_fil2 = str_replace(uobs_fil2, '.obs', '.uobs')
                strrep2 = str2html(concat_dir(httpdir, uobs_fil2), link = link)
                ;strrep2 = strrep2(1)
                ;
                uobs_fil3 = str_replace(uobs_fil2, '.uobs', '.obs')
                strrep3 = str2html(concat_dir(httpdir, uobs_fil3), link = '(obs)')
                ;strrep3 = strrep3(1)

                str = string( strrep2+' '+strrep3, info0.id, info0.index, info0.nwords, str3b, str5, $
                                        format = '(1x, a, 1x, Z4.4, i5, i5, a, 2x, a)')
             end
    endcase
    if (keyword_set(delta) and (i ne n-1)) then str = str + string(info(i+1).addr - (info(i).addr+info(i).nwords), $
											format='(i5)')
    if (not keyword_set(quiet)) then print, str
    if (keyword_set(lun)) then printf, lun, str
end
;
if (keyword_set(lun)) then free_lun, lun
if (keyword_set(qstop)) then stop
end
;-----------------------------------------------------------------
function opsdb_get_id, type, index=index
;
;
;	id = opsdb_get_id('OBS')
;	index = opsdb_get_id('OBS', /index)
;
;HISTORY:
;	Written 5-Dec-95 by M.Morrison
;	 7-Dec-95 (MDM) - Added /INDEX option
;	10-Dec-96 (MDM) - Added check on obs index
;
common opsdb_blk, dir, filnam, info
opsdb_rd_wrt				;make sure stuff has been read
;
list2 = opsdb_get_info(type=type, active=keyword_set(index))
if (data_type(list2) eq 8) then begin
    id_arr = list2.id
    if (keyword_set(index)) then id_arr = list2.index
    out = max(id_arr)+1
end else begin
    out = 8
end
;
if (keyword_set(index) and (type eq 'OBS')) then if (out ge 64) then begin
    stop, 'OBS index cannot be greater than 63'
end
;
return, out
end
;-----------------------------------------------------------------
function opsdb_get_addr, info00, queue=queue, ipregister=ipregister, pad=pad, $
			cam=cam, obs=obs
;
;
;
;HISTORY:
;	Written Aug-95 by M.Morrison
;	13-Sep-95 (MDM) - Added PAD option
;	 5-Dec-95 (MDM) - Added CAM and OBS option to get those addresses
;
common opsdb_blk, dir, filnam, info
opsdb_rd_wrt				;make sure stuff has been read
;
if (data_type(info00) ne 8) then begin		;TODO - sloppy funny way to do this....
    info00 = opsdb_get_struct()
    info00.addr  = -99
    if (keyword_set(queue))      then info00.type  = 'QADR'
    if (keyword_set(ipregister)) then info00.type  = 'IPRL'
    if (keyword_set(obs))        then info00.type  = 'OBS'
    if (keyword_set(cam))        then info00.type  = 'CAM'
end
;
n = n_elements(info00)
out = lonarr(n)
;
for i=0,n-1 do begin
    info0 = info00(i)
    addr = info0.addr
    if (addr le 0) then begin	;has not been assigned yet
	list2 = opsdb_get_info(type= info0.type, /active)
	addr_arr = -1
	if (data_type(list2) eq 8) then begin
	    addr_arr = list2.addr
	    nwords_arr = list2.nwords
	    if ((info0.type eq 'IPRL') or (info0.type eq 'QADR')) then begin
		;ss33 = where(addr_arr lt '1f00'x, nss33)	;MDM added 8-Dec-95 to avoid the heritage load replacement
		ss33 = where(addr_arr lt '1e38'x, nss33)	;MDM added 12-Dec-95 to avoid DMPMEM
		if (nss33 eq 0) then begin
		    addr_arr = -1
	        end else begin
		    addr_arr = addr_arr(ss33)
		    nwords_arr = nwords_arr(ss33)
		end
	    end
	end
	if (max(addr_arr) le 0) then begin	;none of that type done yet
	    case info0.type of
		'IPRL': addr = 4096
		'QADR': addr = '1000'x
		'CAM':  addr = '1088'x
		'OBS':  addr = '3AEC'x		;'4000'x - other portion for dynamics,str50,str30,mag30,hdr15,tail15
		else:   addr = -1000
	    endcase
	end else begin
	    ;;dummy = max(addr_arr, imax)
	    ;;addr = addr_arr(imax) + nwords_arr(imax)		;move to the next available location
	    addr = max(addr_arr + nwords_arr, imax)
	    if (info0.type eq 'OBS') then addr = min(addr_arr)	;opposite direction filling up
	    if (info0.addr eq -1) then addr = addr > 4096	;A1 area starts at 4096
	    ;--- TODO - implement areas of register space??
	    ;--- TODO - check for out of bounds (gone too far)
	    ;
	    if (keyword_set(pad)) then addr = addr + pad	;give some buffer space for expansion of code space
	    if (addr ge '1f00'x) and ((info0.type eq 'IPRL') or (info0.type eq 'QADR')) then begin
		message, 'Address is beyond 0x1f00.   Stopping....'
	    end
	end
	;
	info0.addr = addr
	info0.loaded  = int2secarr(!stime, '1-Jan-58')
	;;print, 'INFO0.LABEL = ', info0.label
	if (strtrim(info0.label,2) ne '') then begin
	    ;;print, 'Updating database.  Addr,loaded=',info0.addr, info0.loaded
	    list2 = opsdb_get_info(label=info0.label, /active, /nostr, nmatch=n2)
	    case n2 of
		0: 	;not even possible?
		1: begin
			info(list2).addr = info0.addr		;because of IDL funny 
			info(list2).loaded = info0.loaded
		    end
		else: begin
			print, '>>> Multiple label entries: ' + info0.label
			info(list2).addr = lonarr(n2)+info0.addr
			info(list2).loaded = dblarr(n2)+info0.loaded
		    end
	    endcase
	end
    end

    out(i) = addr
    info00(i) = info0	;update the input array
end
;
return, out
end
;-----------------------------------------------------------------
pro opsdb_mk_ipvec_src, infil, cfl_dir, do_load_file=do_load_file
;
;
;
common opsdb_blk, dir, filnam, info
;
break_file, infil, dsk_log, dir, infil0, ext
if (dir eq '') then dir = curdir()
outdir = str_replace(dir, '/ip', '/src')
;
outfil = concat_dir(outdir, infil0+'.src')

opsdb_move_file, infil0 + '.src', xxx, outfil, /name_only
;
mat = rd_tfile(infil, 2, delim=string(9b), nocomm='#')
ss = where(mat(0,*) ne '', nss)
if (nss eq 0) then begin
    tbeep, 3
    message, 'No information in ' + infil
    return
end
mat = mat(*,ss)
;
out = opsdb_init_src_fil(outfil)
;
n = n_elements(mat(0,*))
for i=0,n-1 do begin
    info_temp = opsdb_get_info(label=mat(1,i),/active)
    if (data_type(info_temp) ne 8) then begin
	print, 'MK_IPVEC_SRC: Label not recognized: ' + mat(1,i)
	stop
    end
    addr = opsdb_get_addr(info_temp)
    out0 = 'tcblock mbipcmd 0x91 ' + mat(0,i) + string(addr, format='(3x, "0x", z4.4)') + '      ## ' + mat(1,i)
    ;out0 = 'tcblock mbipmacl '    + mat(0,i) + string(addr, format='(3x, "0x", z4.4)') + '      ## ' + mat(1,i)
    out = [out, out0]
    ;
    ss = opsdb_get_info(label=mat(1,i),/active,/nostr)
    if (ss(0) ne -1) then info(ss(0)).index = fix(mat(0,i))		;set the index		-- MDM added 9-Nov-95
end
ssw_file_delete, outfil
prstr, out, file=outfil

if (getenv('EGSE_VER') ge '5.2') then opsdb_cfl_util, outfil, cfl_dir

if (keyword_set(do_load_file)) then file_append, do_load_file, 'perf ' + infil0

end
;-----------------------------------------------------------------
pro opsdb_move_file, infil, outfilsrc, full_outfil, name_only=name_only
;
;	opsdb_move_file, 'xyz.src'		;moves to ../src/. and puts full path into SOURCE line
;
;
if (n_elements(outfilsrc) eq 0) then outfilsrc = infil
dirarr = str2arr(curdir(), delim='/')
outdir = '/mdisw/cfl/' + dirarr(n_elements(dirarr)-2) + '/src'
outfil = concat_dir(outdir, outfilsrc)
if (keyword_set(name_only)) then begin
    full_outfil = outfil
    return
end
;
if (getenv('EGSE_VER') lt '5.2') then begin
    matfile = rd_tfile(infil)
    ssss = where(strmid(matfile, 0, 6) eq 'source', nssss)
    if (nssss ne 0) then matfile(ssss) = 'source "' + concat_dir(outdir, outfilsrc) + '"'
    ssw_file_delete, outfil
    prstr, matfile, file=outfil
    ssw_file_delete, infil
end else begin
    break_file, outfilsrc, dsk_log, dir000, filnam
    cfl_outdir = str_replace(outdir, '/src', '')
    p = strlen(cfl_outdir)-1
    if (strmid(cfl_outdir, p, 1) eq '/') then cfl_outdir = strmid(cfl_outdir,0,p)
    cfl_outdir = str_replace(cfl_outdir, 'dev2', 'dev')		;MDM 4-Mar-97
    cmd = [concat_dir(getenv('MDI_TASK_DIR'), 'cfl_util'), '-r', '-c', cfl_outdir, $
			'-p', filnam]
    print, cmd
    spawn, cmd, /noshell
    ssw_file_delete, infil
end
;
end
;-----------------------------------------------------------------
pro opsdb_mk_ips_src, infil00, addr, direct_load=direct_load, $
		do_load_file=do_load_file, init_do_load=init_do_load, $
		pad=pad, replace=replace
;
;
;HISTORY:
;	Written Aug-95 by M.Morrison
;	13-Sep-95 (MDM) - Added PAD and REPLACE options
;
break_file, infil00, dsk_log, dir, infil, ext

nlab = -1
index = 0
spawn, ['egrep', '-i', '::', infil +'.ips'], result, /noshell
if (result(0) ne '') then begin		;remove labels from database if running them again
    labels = strtrim(result, 2)
    nlab = n_elements(labels)
    for i=0,nlab-1 do labels(i) = (str2arr(labels(i), '::'))(0)	;remove :: and onward
    temp = opsdb_get_addr(opsdb_get_info(label=labels(0),/active))
    if (temp(0) gt 0) then begin
	if (keyword_set(replace) and (not keyword_set(addr))) then addr = temp(0)
	index = intarr(nlab)
	for i=0,nlab-1 do index(i) = opsdb_get_info(label=labels(i),/active,/index)
    end
    opsdb_rm_entry, labels
end
;
cmd = concat_dir(getenv('MDI_EXE_DIR'), 'ipl')
if (keyword_set(direct_load)) then begin
    opsdb_mk_reg_ips, infil+'.reg', replace=replace
    cmd = [cmd, '-l', infil]
end else begin
    if (not keyword_set(addr)) then addr = opsdb_get_addr(/queue, pad=pad)
    cmd = [cmd, '-a', strtrim(addr,2), '-m', infil]
end
;
opsdb_mk_ipl_in
;
outfilsrc = infil+'.src'
ssw_file_delete, outfilsrc				;added 29-Jan-96
ssw_file_delete, 'IP_Symbols.new'
print, '>>>>>>>>>>>>>>>>>>> ' + arr2str(cmd, delim=' ')
spawn, cmd, result, /noshell
;
if (not file_exist('IP_Symbols.new')) then begin	;linker did not run successfully
    print, '************ Error during IP linker execution ********************
    prstr, result, /nomore
    print, '******************************************************************
    print, 'Stopping......'
    stop
    ;return
end
;
;spawn, ['mv', infil+'.src', '../src/.'], /noshell	;move the .src file into the proper directory
if (getenv('OPSDB_LOAD_VER') eq "yes") then outfilsrc = infil+'_1.src'
;;spawn, ['mv', infil+'.src', '../src/'+outfilsrc], /noshell	;move the .src file into the proper directory
;
opsdb_move_file, infil+'.src', outfilsrc
;
opsdb_rd_addr_file, 'IP_Symbols.new', info
nn = n_elements(info)
if (nn gt 2) then begin
    if (info(2).addr ne info(0).addr) then begin
	print, 'OPSDB_MK_IPS_SRC: First label in IPS file is not at the top of the file
	stop
    end
    ;info(2).nwords = info(0).nwords
    ;info(2:*).nwords = info(1).addr - info(2:*).addr + 1
    info = [info, info(1)]	;put a copy of the stop address at the end
    info(nn).addr = info(nn).addr + 1	;next available address
    info(2:nn-1).nwords = info(3:*).addr - info(2:nn-1).addr
    info.forv = infil
    for i=0,nlab-1 do begin
	ss22 = where(info.label eq labels(i), nss22)
	if (nss22 ne 0) then info(ss22(0)).index = index(i)
    end
    opsdb_add_entry, info(2:nn-1), /remove_old		;don't log start/end address
							;/remove_old needed for /replace option to work properly
end
;
if (keyword_set(do_load_file)) then begin
    if (keyword_set(init_do_load)) then junk = opsdb_init_src_fil(do_load_file, /qwrite)
    file_append, do_load_file, 'perf ' + infil
end
;
end
;-----------------------------------------------------------------
pro opsdb_fmt_reg_ips, lun, addr, varr, nvalues, label, info0
;
;OUTPUT:
;	nvalues
;
;
;
	ss = where(strmid(varr,0,1) eq '$', nss)
	for iii=0,nss-1 do varr(ss(iii)) = string(opsdb_get_info(label=strmid(varr(ss(iii)),1,99), /addr, /active))
	values = arr2str(varr, delim='  ')
	;
	nvalues = n_elements(varr)
	;;ss = where(byte(info0.forv) eq (byte(','))(0), nss)		& nvalues = nss + 1
	for iii=0,n_elements(varr)-1 do if (strmid(varr(iii), strlen(varr(iii))-1, 1) eq 'L') then nvalues = nvalues + 1
	ss = where(byte(values) eq (byte(':'))(0), nss)			& nvalues = nvalues + nss
	if (data_type(info0) eq 8) then if (nvalues ne info0.nwords) then begin
	    print, 'Problem with:           ', info0.label
	    print, 'Values String:          ', info0.forv
	    print, 'Expected # of values:   ', info0.nwords
	    print, 'Determined # of values: ', nvalues
	    stop
	end
	;
	;if (info0.nwords eq 1) then begin
	if (nvalues eq 1) then begin
	    str = string('SETREG',  addr, values, format='(a, 1x, "R",i4.4, 1x, a)')
	end else begin
	    str = string('SETREGS', addr, nvalues, values, format='(a, 1x, "R",i4.4, 1x, i3, 1x, a)')
	end
	print, ';'
	print, ';' + label
	print, str
	if (nvalues gt 8) then begin
	    print, '******* Too many registers to set.... breaking it up'
	end else begin
	    printf, lun, ';'
	    printf, lun, ';' + label
	    printf, lun, str
	end
end
;-----------------------------------------------------------------
pro opsdb_mk_reg_ips, infil, outfil, replace=replace
;
;	opsdb_mk_reg_ips, 'images_reg.reg'
;
;
opsdb_rd_addr_file, infil, info
if (data_type(info) ne 8) then return
if (keyword_set(replace)) then for i=0,n_elements(info)-1 do info(i).addr = opsdb_get_info(label=info(i).label, /addr, /active)
opsdb_add_entry, info, /remove_old
;
if (n_elements(outfil) eq 0) then outfil = str_replace(infil, '.reg', '.ips')
ssw_file_delete, outfil
openw, lun, outfil, /get_lun
printf, lun, '; OPSDB_MK_REG_IPS Program Run: ' + !stime
printf, lun, '; Input File: ' + infil
printf, lun, ';
;
n = n_elements(info)
;
for i=0,n-1 do begin
    info0 = info(i)
    addr = opsdb_get_addr(info0)
    if (strtrim(info0.forv,2) eq "") or (strtrim(info0.forv,2) eq "---") then begin
	print, 'No values for label ' + info0.label
	print, 'No SETREG instruction generated
    end else begin
	;;values = str_replace(info0.forv, ',', '  ')
	;
	varr = str2arr(info0.forv)
	opsdb_fmt_reg_ips, lun, addr, varr, nvalues, info0.label, info0
	;
	if (nvalues gt 8) then begin
	    ii = n_elements(varr)/2
	    opsdb_fmt_reg_ips, lun, addr,         varr(0:ii-1), nvalues, info0.label + ' (first half)'
	    opsdb_fmt_reg_ips, lun, addr+nvalues, varr(ii:*), nvalues, info0.label + ' (second half)'
	end
    end
end
;
free_lun, lun
end
;-----------------------------------------------------------------
pro opsdb_rd_addr_file, infil, info, update=update
;
;
;
info = 0b
mat = rd_tfile(infil, nocomment=';')
remtab, mat, mat
mat = strtrim(mat, 2)
ss = where(mat ne '')
if (ss(0) eq -1) then mat = '' else mat = mat(ss)
n = n_elements(mat)
if (mat(0) eq '') then begin
    print, 'OPSDB_RD_IPL_OUT: Error reading ' + infil
    return
end
;
info = replicate(opsdb_get_struct(), n)
for i=0,n-1 do begin
    lin = strtrim(strcompress(mat(i)), 2)
    arr = str2arr(lin, delim=' ')
    narr = n_elements(arr)
    if (narr lt 5) then begin
	print, 'OPSDB_RD_ADDR_FILE: Problem with reading an address file
	print, '>>>>>>>>>>>>>>>> ' + lin
	tbeep
    end else begin
	case strmid(arr(2), 0, 1) of
	    'A': arr(2) = '-' + strmid(arr(2), 1, 99)	;make it a negative number
	    'R': arr(2) = strmid(arr(2), 1, 99)
	    else: if (strmid(arr(2), 0, 2) eq '0x') then begin
	    		temp = 0L
			reads, strmid(arr(2), 2, 99), temp, format='(z)'
			arr(2) = temp
		  end
	end
	info(i).label		= arr(0)
	info(i).descr2		= arr(1)	;instruction
	info(i).addr		= arr(2)
	info(i).type		= arr(3)
	info(i).nwords		= long(arr(4))
	if (narr ge 6) then begin
	    values = arr2str(arr(5:*))
	    info(i).forv = values
	    if (strlen(values) gt 40) then begin
		print, 'Problem with ', info(i).label
		print, 'Values string is too long.  # characters = ', strlen(values)
		print, 'String == ' + values
		tbeep, 4
		;;stop
	    end
	end
    end
end
;
if (keyword_set(update)) then opsdb_add_entry, info, /remove_old
end
;-----------------------------------------------------------------
pro opsdb_mk_ipl_in
;
;
;
outfil = 'IP_Symbols.dat'
ssw_file_delete, outfil
;
info = opsdb_get_info(/active)
type = strupcase(strtrim(info.type,2))
ss = where( (strmid(type,0,2) eq 'IP') or (strmid(type,0,1) eq 'Q'), nss)
if (nss eq 0) then info = opsdb_get_struct() $
		else info = info(ss)
n = n_elements(info)
;for i=0,n-1 do for j=0,n_elements(tag_names(info))-1 do if (data_type(info.(j)) eq 7) then if (strtrim(info(i).(j),2) eq '') then info(i).(j) = '---'
opsdb_print, info, 99, outfil=outfil, /noheader, /quiet

end
;-----------------------------------------------------------------
pro opsdb_check_code, files
;
;	opsdb_check_code, findfile('*.ips')
;
for ifil=0,n_elements(files)-1 do begin
    infil = files(ifil)
    print, '---------------- Checking ' + infil
    ;
    mat = rd_tfile(infil, nocomment=';')
    remtab, mat, mat
    mat = strupcase(strcompress(strtrim(mat, 2)))
    ;
    ss = wc_where(mat, '*COPYR?2?*', nss)
    ss = wc_where(mat, '*COPYR*', nss)
    print, '                 # of COPYR* commands == ', nss 
    for i=0,nss-1 do begin
	arr = str2arr(mat(ss(i)), delim=' ')
	if (arr(0) ne 'COPYREG') then if (fix(arr(3)) le 2) then print, mat(ss(i))
    end
end
;
end
;-----------------------------------------------------------------
pro opsdb_mk_tab_src, infil, addr, do_load_file=do_load_file, init_do_load=init_do_load
;
;	opsdb_mk_tab_src, 'offset.tab'
;
;	if address is not specified, then first characters must be "offset" or "exposure"
;
if (not file_exist(infil)) then begin
    print, 'Input file: ' + infil + ' does not exist
    return
end
;
break_file, infil, dsk_log, dir00, filnam00
;;outfil = '../src/' + infil
;;outfil = str_replace(outfil, '.tab', '.src')
opsdb_move_file, str_replace(infil, '.tab', '.src'), xxx, outfil, /name_only
;
mat = rd_tfile(infil, 4, nocomment='#', delim=string(9b))
mat = mat(*,2:*)	;drop header and ---- lines
;
if (n_elements(addr) eq 0) then begin
    addr = 0
    if (strmid(filnam00, 0, 6) eq 'offset') then addr = '4098'x
    if (strmid(filnam00, 0, 8) eq 'exposure') then addr = '4498'x
    if (addr eq 0) then stop	;what to do
end
;
n = n_elements(mat(0,*))
;
out = opsdb_init_src_fil(outfil)
;
;
for i=0,n-1 do begin
    value = long(mat(1,i))
    case strmid(filnam00,0,6) of
	'offset': begin
		    fmt = '("tcb mbdpml 0x1000 ", 3(" 0x", Z4.4),  6x, 3(a,1x))'
		    addr2 = addr + mat(0,i)*4		;4 bytes per entry
		    low8 = value mod 2L^16
		    hi8  = value /   2L^16
		    out = [out, string(addr2, low8, hi8, "## "+mat(1,i), mat(3,i), format=fmt)]
		  end
	'exposu': begin
		    fmt = '("tcb mbdpml 0x1000 ", 2(" 0x", Z4.4),  6x, 3(a,1x))'
		    addr2 = addr + mat(0,i)*2
		    out = [out, string(addr2, value, "## "+mat(0,i), mat(1,i), mat(2,i), format=fmt)]
		  end
	else: stop
    endcase
end
;
out = strmid(out, 0, 78)		;trim it down to make sure no compile problems
out = [out, ' ', 'return']
;
prstr, out, /nomore
ssw_file_delete, outfil
prstr, out, file=outfil
;
if (keyword_set(do_load_file)) then begin
    if (keyword_set(init_do_load)) then junk = opsdb_init_src_fil(do_load_file, /qwrite)
    file_append, do_load_file, 'perf ' + filnam00
end

end
;-----------------------------------------------------------------
pro opsdb_mk_obs_src, infil, addr, do_load_file=do_load_file, init_do_load=init_do_load, index=index, replace=replace
;
;	opsdb_mk_obs_src, 'obs_focus_1.uobs'
;
print, 'Now processing: ' + infil
if (not file_exist(infil)) then begin
    print, 'Input file: ' + infil + ' does not exist
    return
end
;
infil0 = infil
break_file, infil, dsk_log, dir, filnam, ext
;
spawn, ['grep', '-i', 'Name:', infil0], result, /noshell
p = strpos(result(0), ':')
name = strtrim(strmid(result(0), p+1, 99),2) + ' '
name = strmid(name, 0, strpos(name, ' '))
;
spawn, ['grep', '-i', 'Description:', infil0], result, /noshell
p = strpos(result(0), ':')
descr = strtrim(strmid(result(0), p+1, 99),2)
;
id = -1
if (ext eq '.uobs') then begin
    id = opsdb_get_id('OBS')
    print, 'OPSDB_MK_OBS_SRC: ID = ' + strtrim(id,2)
    opsdb_uobs2obs, infil, id=id			;convert from uobs to obs
    infil = str_replace(infil, '.uobs', '.obs')
end else begin
    id = opsdb_get_info(label=name,/id)
    id = id(n_elements(id)-1)		;get last one since they should be time ordered
end
;
if (not file_exist(infil)) then begin
    print, 'Input file: ' + infil + ' does not exist
    return
end

if (keyword_set(replace)) then begin
    temp = opsdb_get_info(label=name, /active)
    if (data_type(temp) eq 8) then begin
	addr = opsdb_get_addr(temp(0))
	index = temp(0).index
    end
end

mat = rd_tfile(infil)
load_size = (n_elements(mat)-6) * 12
if (n_elements(addr) eq 0) then begin
    addr = opsdb_get_addr(/obs)
    addr = addr - load_size
    print, 'OPSDB_MK_OBS_SRC: Address = ' + strtrim(addr,2)
end
addr = addr(0)
;
if (n_elements(index) eq 0) then index = opsdb_get_id('OBS', /index)
;
cmd = concat_dir(getenv('MDI_EXE_DIR'), 'obstran')
cmd = [cmd, '-a', strtrim(addr-'1088'x, 2), '-s', strtrim(index,2), str_replace(infil, '.obs', '')]
;cmd = [cmd, str_replace(infil, '.obs', '')]
print, arr2str(cmd, delim=' ')
spawn, cmd, result, /noshell
if (result(0) ne '') then begin
    print, 'Trouble with obstran'
    prstr, result
    stop
end
;
src_fil = str_replace(infil, '.obs', '.src')
outsrc_fil = src_fil
if (getenv('OPSDB_LOAD_VER') eq "yes") then outsrc_fil = str_replace(outsrc_fil, '.src', '_1.src')
;;spawn, ['mv', src_fil, '../src/'+outsrc_fil], /noshell	;move the .src file into the proper directory

opsdb_move_file, src_fil, outsrc_fil

info = opsdb_get_struct()
info.label = name
info.index = index
info.id = id
info.addr = addr
info.nwords = load_size
info.descr = descr
info.forv = infil0
info.type = 'OBS'
opsdb_add_entry, info, /remove_old
;
if (keyword_set(do_load_file)) then begin
    if (keyword_set(init_do_load)) then junk = opsdb_init_src_fil(do_load_file, /qwrite)
    file_append, do_load_file, 'perf ' + filnam
end
;
end
;-----------------------------------------------------------------
pro opsdb_mk_cam_src, infil, addr, do_load_file=do_load_file, init_do_load=init_do_load, replace=replace
;
;	opsdb_mk_cam_src, 'cam_dt19_cal.cam'
;
print, 'Now processing: ' + infil
if (not file_exist(infil)) then begin
    print, 'Input file: ' + infil + ' does not exist
    return
end
;
spawn, ['grep', '-i', 'Name:', infil], result, /noshell
p = strpos(result(0), ':')
name = strtrim(strmid(result(0), p+1, 99),2) + ' '
name = strmid(name, 0, strpos(name, ' '))
;
spawn, ['grep', '-i', 'Description:', infil], result, /noshell
p = strpos(result(0), ':')
descr = strtrim(strmid(result(0), p+1, 99),2)
;
break_file, infil, dsk_log, dir00, filnam00
;;outfil = '../src/' + infil
;;outfil = str_replace(outfil, '.cam', '.src')
;;opsdb_move_file, str_replace(infil, '.cam', '.src'), xxx, outfil, /name_only
outfil = str_replace(infil, '.cam', '.src')
;
if (getenv('OPSDB_LOAD_VER') eq "yes") then outfil = str_replace(outfil, '.src', '_1.src')
;
mat = rd_tfile(infil, nocomment='#')
remtab, mat, mat
;
mat0 = mat
mat0 = mat0( where(strtrim(mat0,2) ne '') )
;
mat = strtrim(strcompress(mat),2)
ss = where(mat ne '')
mat = mat(ss)
mat2 = rd_tfile(infil, 2, nocomment='#')
if (n_elements(mat2(0,*)) lt 7) then begin
    message, 'bad cam file: ' + infil, /info
    return
end
;
;ihead  = opsdb_get_info(label=mat2(1,2),/index,/active)		& if (ihead eq -1)  then ihead  = 4	;not in database yet
;itail  = opsdb_get_info(label=mat2(1,3),/index,/active)		& if (itail eq -1)  then itail  = 5	;not in database yet
;iprime = opsdb_get_info(label=mat2(1,4),/index,/active)		& if (iprime eq -1) then iprime = 2	;not in database yet
;ialt30 = opsdb_get_info(label=mat2(1,5),/index,/active)		& if (ialt30 eq -1) then ialt30 = 3	;not in database yet
ihead  = opsdb_get_info(label=mat2(1,2),/index,/active)		& if (ihead eq -1)  then  stop,'Dont know: ' + mat2(1,2)
itail  = opsdb_get_info(label=mat2(1,3),/index,/active)		& if (itail eq -1)  then  stop,'Dont know: ' + mat2(1,3)
iprime = opsdb_get_info(label=mat2(1,4),/index,/active)		& if (iprime eq -1) then  stop,'Dont know: ' + mat2(1,4)
ialt30 = opsdb_get_info(label=mat2(1,5),/index,/active)		& if (ialt30 eq -1) then  stop,'Dont know: ' + mat2(1,5)

;
if (keyword_set(replace)) then begin
    ;;temp = opsdb_get_addr( opsdb_get_info(label=filnam, /active) )
    ;;if (temp(0) gt 0) then addr = temp(0)
    temp = opsdb_get_info(label=name, /active)
    if (data_type(temp) eq 8) then addr = opsdb_get_addr(temp(0))
end

if (n_elements(addr) eq 0) then addr = opsdb_get_addr(/cam)
addr = addr(0)
id = opsdb_get_id('CAM')
n = n_elements(mat)-6
dummy = where(strmid(mat0(6:*), 0, 2) ne '  ', nhead)	;MDM added 11-feb-96 (nhead used to be n)
;
out = opsdb_init_src_fil(outfil)
;
arr = str2arr(mat(5), delim=' ')
if (n_elements(arr) le 2) then nrep_alt = -1 $		;use the default
			else nrep_alt = fix(arr(2))
if (nrep_alt lt 0) then nrep_alt = nrep_alt + 2L^16
;
fmt0= '("tcb mbdpml 0x1000 ", 3(" 0x", Z4.4), 20x, a)'
fmt = '("tcb mbdpml 0x1000 ", 5(" 0x", Z4.4),  6x, a)'
out = [out, string(addr, id, nhead, "## ID, N", format=fmt0)]
out = [out, string(addr+4+8*0, ihead, 1, '7fff'x, 0, "## Head", format=fmt)]
out = [out, string(addr+4+8*1, itail, 1, '7fff'x, 0, "## Tail", format=fmt)]
out = [out, string(addr+4+8*2, iprime, 1, '7fff'x, 0, "## Prime30", format=fmt)]
out = [out, string(addr+4+8*3, ialt30, nrep_alt, '7fff'x, 0, "## Alt30", format=fmt)]
;
for i=0,n-1 do begin
    arr = str2arr(mat(i+6), delim=' ')
    if (arr(0) eq 'NEST_LOOP') then begin
	if (i eq 0) then begin
	    ;;print, 'NEST_LOOP cannot be the first item in the campaign list'
	    ;;stop
	end
	;
	;;iend = where(strmid(mat(i+6+1:*), 0, 9) eq 'NEST_LOOP', niend)
	iend = where(strmid(mat0(i+6+1:*), 0, 2) ne '  ', niend)
	;if (niend eq 0) then iend = n-1
	if (niend eq 0) then iend = n-1 else iend = iend+i	;MDM added else 2-Apr-97
	nobsnest = (iend(0)+6+1) - (i+6) -1 -1	;-1 added 30-Jan-96	second -1 added 13-Feb-96
	irep = (fix(arr(1))-1) > 1	;two repeats of nested loop minimum!!
	irep = 2L^16 - 	irep 		;make it a negative short word
	out = [out, string(addr+4+8*(i+4), nobsnest, irep, 'ffff'x, 'ffff'x, "## nested repeat", format=fmt)]
    end else begin
        info = opsdb_get_info(label = arr(0), type='OBS', /active)
        if (data_type(info) ne 8) then begin
	    print, 'Cannot find observation: ' + arr(0) + ' in the database'
	    print, '************* Aborting'
	    stop
        end
        iobs = info(0).index
        ;
        irep = (fix(arr(1))-1) > 0		;MDM added -1 30-Jan-96
        ipprog = '7fff'x
        if (strupcase(arr(2)) ne 'DEFAULT') then begin
	    ipprog = opsdb_get_info(label = 'QPROG_' + arr(2), type='QADR', /active, /index)
	    if (ipprog eq -1) then begin
	        print, infil, ' campaign points to an unknown IP program'
	        print, 'IP program pointed to is: ', arr(2)
	        stop
	    end
        end
        offset = fix(arr(3))
        out = [out, string(addr+4+8*(i+4), iobs, irep, ipprog, offset, "## "+arr(0), format=fmt)]
    end
end
;
out = [out, ' ', 'return']
;
prstr, out, /nomore
ssw_file_delete, outfil
prstr, out, file=outfil
opsdb_move_file, outfil
;
info = opsdb_get_struct()
info.label = name
info.id = id
info.addr = addr
info.nwords = 4 + (4+n)*8
info.descr = descr
info.index = (addr-'1088'x)/2
info.forv = infil
info.type = 'CAM'
opsdb_add_entry, info, /remove_old
;
if (keyword_set(do_load_file)) then begin
    if (keyword_set(init_do_load)) then junk = opsdb_init_src_fil(do_load_file, /qwrite)
    file_append, do_load_file, 'perf ' + filnam00
end
;
end
;-----------------------------------------------------------------
pro opsdb_mk_simp_cam, filnam, ipprog, descr, prime=prime, offset=offset
;
;
;	opsdb_mk_simp_cam, 'obs_focus_1', prime='OBS_PRIME08'
;	opsdb_mk_simp_cam, 'obs_std_fd_mag', 'FD_M1_V1', 'Make and downlink cropped FD magnetogram and velocity
;
;outlab = 'cam_' + strmid(filnam,4,99)
outlab = 'cam_' + strlowcase(ipprog)
outfil = outlab + '.cam'
print, 'Now making: ' + outfil
;
if (n_elements(prime) eq 0) then prime = 'OBS_STD_STR30'
;
if (n_elements(offset) eq 0) then begin
    spawn, ['grep', '-i', 'OFFSET:', filnam+'.uobs'], result, /noshell
    p = strpos(result(0), ':')
    if (p eq -1) then offset = '0' $
	else offset = strtrim(strmid(result(0), p+1, 99),2)
end
offset = strtrim(offset,2)
;
if (n_elements(descr) eq 0) then begin
    spawn, ['grep', '-i', 'Description:', filnam+'.uobs'], result, /noshell
    p = strpos(result(0), ':')
    descr = strtrim(strmid(result(0), p+1, 99),2)
end
;
if (n_elements(ipprog) eq 0) then ipprog = 'DEFAULT'
;
out = ['#', $
	'# FILE:', $
	'#       ' + outfil, $
	'# HISTORY:', $
	'#       Auto Created by OPSDB_MK_SIMP_CAM ' + !stime, $
	'#', $
	'Campaign_Name: ' + outlab, $
	'Campaign_Description: ' + descr, $
	' ', $
	'HEAD    OBS_STD_HEAD', $
	'TAIL    OBS_STD_TAIL', $
	'PRIME30 '+prime, $
;;	'ALT30   OBS_STD_ALT30', $
	'ALT30   OBS_STD_FD_MAG   1', $
	' ', $
	'# ObsName       Repeats         IP_Prog         Offset',$
	filnam + '      1024         ' + ipprog + '       '+offset]

;;if (file_exist(outfil)) then stop
prstr, out, file=outfil

end
;-----------------------------------------------------------------
function decode_trans_obs, value, lab, item, qinteger, err
;
;
;
value0 = value
p1 = strpos(value, '+')		& if (p1 ne -1) then value0 = strmid(value, 0, p1)
p2 = strpos(value, '-')		& if (p2 ne -1) then value0 = strmid(value, 0, p2)
ss = where((lab(0,*) eq item) and (lab(1,*) eq value0), nss)
if (nss ne 0) then begin
    out = lab(2, ss(0))
    if (p1 ne -1) then out = fix(out) + fix(strmid(value, p1+1, 99))
    if (p2 ne -1) then out = fix(out) - fix(strmid(value, p2+1, 99))
    if (qinteger) then out = fix(out)
    return, out
end
;
if (strmid(value, 0, 1) eq 'T') then begin	;exposure tick marks
    vin = long(strmid(value, 1, 99))
    ss = where((lab(0,*) eq item) and (strmid(lab(1,*),0,1) eq 'T') and (lab(1,*) ne 'TWICE'))
    varr = long(strmid(lab(1,ss),1,99))
    dummy = min(abs(varr-vin), imin)
    out = lab(2,ss(imin))
    return, out
end
;
if (strmid(value, 0, 3) eq 'ABS') then begin
    v = strmid(value, 3, 99)
    arr = str2arr(v)
    out = fix(arr(0))
    if (n_elements(arr) eq 2) and (strmid(item, 3, 1) eq '2') then out = fix(arr(1))
    return, out
end
;
if (item eq 'DMA') then begin
    arr = str2arr(value)		;comma separated
    out = strarr(4) + arr(n_elements(arr)-1)
    out(0) = arr
    if (n_elements(arr) eq 2) then out(2) = arr		;MDM 25-Jul-96 (do pair twice)
    return, out
end
;
message, 'Cannot decode the value. Value ='+value + ' Item: ' + item, /info
err = err + 1
stop
end
;----------------------------------------------------------
pro opsdb_uobs2obs, infil, outfil, id=id, lab_fil=lab_fil, flight=flight, sim=sim, qstop=qstop
;
;+
;NAME:
;	opsdb_uobs2obs
;PURPOSE:
;	To translate the user's obs frame list to a pre-load format file.
;SAMPLE CALLING SEQUENCE:
;	opsdb_uobs2obs, 'dt5x5_cal.uobs', /sim
;	ff = findfile('/mdisw/cfl/comm/dep/*.uobs')
;	for i=0,n_elements(ff)-1 do opsdb_uobs2obs, ff(i), /sim
;HISTORY:
;	Written 9-Nov-95 by M.Morrison
;	 5-Dec-95 (MDM) - Renamed from MDI_TRANS_UOBS to OPSDB_UOBS2OBS
;			- Added ID keyword input
;-
;
if (n_elements(lab_fil) eq 0) then begin
    qflight = 1		;the default is to assume it is for the flight system
    if (keyword_set(sim)) then qflight = 0
    ;
    ipdir = getenv('MDI_OPS_IP_DEP')
    if (qflight) then begin
	ff0 = file_list(ipdir, 'mdi_uobs.9*')
	ff1 = file_list(ipdir, 'mdi_uobs.0*')
	ff = [ff0, ff1]
    end else begin
	ff0 = file_list(ipdir, 'sim_uobs.9*')
	ff1 = file_list(ipdir, 'sim_uobs.0*')
	ff = [ff0, ff1]
    end
    if (ff(0) eq '') then begin
	print, 'No UOBS files found in $MDI_OPS_IP_DEP'
	return
    end
    lab_fil = ff(n_elements(ff)-1)	;take the last one by default
    print, 'Using label file: ' + lab_fil
end
;
;
if (n_elements(outfil) eq 0) then outfil = str_replace(infil, '.uobs', '.obs')
if (infil eq outfil) then stop, 'Output equals input file -- would overwrite'
;
if (not file_exist(infil)) then begin
    message, 'Input file does not exist: ' + infil, /info
    return
end
if (not file_exist(lab_fil)) then begin
    message, 'Label input file does not exist: ' + lab_fil, /info
    return
end
;
mat = rd_tfile(infil, nocomment='#')
remtab, mat, mat		;remove tabs
mat = strtrim(strcompress(mat),2)
ss = where(mat ne '', nss)
if (nss eq 0) then begin
    message, 'Input file is empty: ' + infil, /info
    return
end
mat = mat(ss)
;
;TODO - check that there is no extra junk - only 3 lines of header
;
;------------------------------
;
;;lab = rd_tfile(lab_fil, 3, delim=string(9b), nocomment='#')
lab = strtrim(rd_tfile(lab_fil, 3, nocomment='#'),2)
if (n_elements(lab(0,*)) le 2) then begin
    message, 'Label input file is empty: ' + lab_fil, /info
    return
end
lab = lab(*, 2:*)		;drop the header and dash lines
;
;------------------------------
;
head = {name: ' ', descr: ' ', n: 0, id: 0, ip_prog: ' ', ip_addr: 0}
image0 = {time: 0, mtm1: 0, mtm2: 0, cal1: 0, cal2: 0, paw: 0, itype: 'x', exp: 0, $
	ofp: 0, dma: strarr(4)}
;
p = strpos(mat(0), ':')		& head.name = strtrim(strmid(mat(0), p+1, 999),2)
p = strpos(mat(1), ':')		& head.descr = strtrim(strmid(mat(1), p+1, 999),2)
p = strpos(mat(2), ':')		& head.ip_prog = strtrim(strmid(mat(2), p+1, 999),2)
if (keyword_set(id)) then head.id = id
;
n = n_elements(mat)-3		;other than the 3 lines of header, the rest are images
head.n = n
ip_info = opsdb_get_info(label='QPROG_' + head.ip_prog, /active)
if (data_type(ip_info) ne 8) then begin
    print, '*********** IP Queue Program Name Not Recognized.  
    print, 'User input is: ' + head.ip_prog
    ip_info = opsdb_get_info(type='QADR')
    if (data_type(ip_info) eq 8) then begin
	ss = where(strmid(ip_info.label, 0, 5) eq 'QPROG', nss)
	if (nss ne 0) then print, 'Possible program names are: ', strmid(ip_info(ss).label, 6, 99)
    end
    print, '************ Aborting
    stop
end else begin
    if (ip_info(0).index le 0) then begin
	print, 'ERROR: Index Information for the IP Program is Null for ' + ip_info(0).label
	stop
    end else begin
	head.ip_addr = ip_info(0).index
	print, 'Index Information for the IP Program is ' + strtrim(head.ip_addr,2) + ' for ' + ip_info(0).label
    end
end
;
image = replicate(image0, n)
;
err = 0
for i=0,n-1 do begin
    arr = str2arr(mat(i+3), delim=' ')
    v1 = round(float(arr(1))*16)
    if (i eq 0) then image0.time = v1 else image0.time = image(i-1).time + v1
    image0.mtm1  = decode_trans_obs(arr(2), lab, 'MTM1',  1, err)
    image0.mtm2  = decode_trans_obs(arr(3), lab, 'MTM2',  1, err)
    image0.cal1  = decode_trans_obs(arr(4), lab, 'CAL1',  1, err)
    image0.cal2  = decode_trans_obs(arr(4), lab, 'CAL2',  1, err)
    image0.paw   = decode_trans_obs(arr(5), lab, 'PAW',   1, err)
    image0.itype = decode_trans_obs(arr(6), lab, 'ITYPE', 0, err)
    image0.exp   = decode_trans_obs(arr(7), lab, 'EXP',   1, err)
    image0.dma   = decode_trans_obs(arr(8), lab, 'DMA',   0, err)
    ;
    if (image0.mtm1 lt 0) or (image0.mtm1 gt 179) then begin
	print, 'MTM1 Value is out of range.  Needs to be from 0 to 179.
	print, 'User value = ' + arr(2) + ' which decodes to ' + strtrim(image0.mtm1,2)
	print, 'Aborting...'
	return
    end
    if (image0.mtm2 lt 0) or (image0.mtm2 gt 179) then begin
	print, 'MTM2 Value is out of range.  Needs to be from 0 to 179.
	print, 'User value = ' + arr(2) + ' which decodes to ' + strtrim(image0.mtm2,2)
	print, 'Aborting...'
	return
    end
    ;
    image(i) = image0
end
;
print, '-------------- Summary of Results for ' + infil + ' -------------
print, 'Start time of last image is: ', image0.time/16., ' seconds'
print, 'Number of images:            ', head.n
print, ' '
;
if (((image0.time/16.) mod 60) gt 57.5) then begin	;MDM added 30-Jan-96
    tbeep, 4
    print, 'Frame list has timing such that the last frame is going to
    print, 'conflict with PRIME08.  Warning...
end
;
;------------------------------ Write it out

;;junk = ['CW', '  1',  'CCW', '  2', ' CW', '  3',  '  -', '  -']		;shouldn't be needed....
junk = strarr(8)+'-'

fmt1 = '(i3, ",", Z4.3, ",", i3, ",", 8(a4, ","), i4)
fmt2 = '(i5,",", 5(i4, ","), a4, ",", i4, ",", i4, 4(",", a4))'
ssw_file_delete, outfil		;MDM added 16-Jul-96
openw, lun, outfil, /get_lun
printf, lun, 'Name: ' + head.name + '  --  ' + head.descr
printf, lun, '         Time    CAL1     CAL2       PAW      Dir       IP
printf, lun, ' N   ID   Fr1  Dir  Pos  Dir  Pos  Dir  Pos  M1  M2    Addr
printf, lun, head.n, head.id, 80, junk, head.ip_addr, format=fmt1
printf, lun, ' '
printf, lun, '     MTM1 MTM2 CAL1 CAL2 PAW                          DMA
printf, lun, ' Time  Pos  Pos  Pos  Pos Pos  IType  Exp  OFP    0   1   2   3
for i=0,n-1 do printf, lun, image(i), format=fmt2
free_lun, lun

if (keyword_set(qstop)) then stop
end
;----------------------------------------------------------------
pro opsdb_fudge_obs
;
;
;
;
;--- Since using DEP ROM versions of the HEAD and TAIL framelists
;
info0 = opsdb_get_struct()
info0.label = 'OBS_STD_HEAD'
info0.type = 'OBS'
info0.index = 4
info0.id = 0
info0.addr = '3c54'x
opsdb_add_entry, info0, /remove_old
;
info0 = opsdb_get_struct()
info0.label = 'OBS_STD_TAIL'
info0.type = 'OBS'
info0.index = 5
info0.id = 0
info0.addr = '3c0c'x
opsdb_add_entry, info0, /remove_old
;
end
;-----------------------------------------------------------------
pro check_files_ok
;
;
;
ff = file_list('/mdisw/cfl/prep/src','*.src', file=files)
n = n_elements(ff)
for i=0,n-1 do begin
    spawn, ['egrep', '^program', ff(i)], result, /noshell
    if (result(0) eq '') then print, ff(i), '		has no program'
    spawn, ['egrep', '^source', ff(i)], result, /noshell
    if (result(0) eq '') then print, ff(i), '		has no source'
    spawn, ['egrep', '^descr', ff(i)], result, /noshell
    if (result(0) eq '') then print, ff(i), '		has no descr'
end

break_file, files, dsk_log, dir, filnam, ext
print, strlen(filnam)
print, 'MAX:', max(strlen(filnam))
;
;max allowed is 20 without the extension
ss = where(strlen(filnam) gt 20, nss)
if (nss ne 0) then prstr, 'PROBLEM WITH ' + filnam(ss)
end
;-----------------------------------------------------------------
function opsdb_latest_ver, infil, dir=dir, noext=noext
;
;	filnam = opsdb_latest_ver('obs_prime08.uobs')
;
break_file, infil, dsk_log, dir, filnam, ext
ff = file_list(dir, filnam+'_v*'+ext)
if (ff(0) eq '') then begin
    ff = file_list(dir, filnam+ext)
    if (ff(0) eq '') then begin
        ff = file_list(dir, filnam+'*'+ext)	;non-versioned file
        out = ff(0)
    end else begin
	out = ff(0)
    end
end else begin
    nn = n_elements(ff)
    out = ff(nn-1)
end
;
if (out eq '') then message, 'Cant find the file: ' + infil
if (keyword_set(noext)) then begin
    break_file, out, dsk_log, dir000, out2, ext
    out = out2
    ;out = str_replace(out, ext, '')
end
return, out
end
;-----------------------------------------------------------------
pro opsdb_conf_chk, code, map
;
;
;
info = opsdb_get_info(/active)
;
case code of
    0: ss = where(strmid(info.type, 0, 1) eq 'Q', nss)
    1: ss = where((info.type eq 'OBS') or (info.type eq 'CAM'), nss)
    2: ss = where(strmid(info.type, 0, 2) eq 'IP', nss)
end
case code of
    0: print, '=========== Conflict Check for QUEUE Address Space ==================='
    1: print, '=========== Conflict Check for DEP OBS/CAM Address Space ==================='
    2: print, '=========== Conflict Check for IP Register Address Space ==================='
end
if (nss eq 0) then return
info2 = info(ss)
;
map = bytarr(33000)
for i=0,nss-1 do begin
    info0 = info(ss(i))
    ist = info0.addr
    ien = ist + info0.nwords-1
    if (ien lt ist) then begin
	print, 'Label: ' + info0.label + ' has a bad size'
    end else begin
        map( ist:ien ) = map( ist:ien ) + 1
    end
end
;
case code of
    0: begin
	    print, 'Masking out the known overlap for QSR_CB_DONE_ADDR'
	    map(4095) = map(4095)-1
	end
    1: begin
	    print, 'Masking out the known overlap for VC2 CAM'
	    map('1088'x:'10c3'x) = 0
	    print, 'Masking out the known overlap for PRIME60 OBS'
	    map('3f0c'x:'4077'x) = 0
	end
    2: begin
	    print, 'Masking out the known overlap in IP reg space'
	    map(3576:3581) = 0
	end
end
;
ss = where(map gt 1, nss)
if (nss ne 0) then begin
    tbeep, 5
    for i=0,nss-1 do print, 'Conflict at: ' + string(ss(i), format='(z)')
    opsdb_print, info2, 3, /sort_addr
    print, '<<<<<<<<<<<<<<<<<< Conflict FOUND >>>>>>>>>>>>>>>>>>>>>>>
    tbeep, 5
end
;
end
;-----------------------------------------------------------------
pro opsdb_mk_reload, outfil1=outfil1, outfil2=outfil2, outfil3=outfil3, indir=indir
;
;
if (n_elements(outfil1) eq 0) then outfil1 = '/mdisw/cfl/dev/src/reload_dep.src'
if (n_elements(outfil2) eq 0) then outfil2 = '/mdisw/cfl/dev/src/reload_ip.src'
if (n_elements(outfil3) eq 0) then outfil3 = '/mdisw/cfl/dev/src/reload_oth.src'
if (n_elements(indir) eq 0) then indir = '/mdisw/cfl/flight/src'
;
junk = opsdb_init_src_fil(outfil1, /qwrite)
junk = opsdb_init_src_fil(outfil2, /qwrite)
junk = opsdb_init_src_fil(outfil3, /qwrite)
;
;;file_append, outfil1, 'cd c "flight"'
;;file_append, outfil2, 'cd c "flight"'
;;file_append, outfil3, 'cd c "flight"'
;
file_append, outfil2, 'tcb mbipldin 0x154	## --- DISable the queue'
;
cd, indir
;
;---- "OTHER" file
;
man_list = ['loi_v_7005', 'loi_c_7006', 'dep_mos+10e', 'init_ipvec', 'scitbls']
nss = n_elements(man_list)
for i=0,nss-1 do file_append, outfil3, 'perf ' + opsdb_latest_ver(man_list(i), /noext)
;
;---- IP file
;
info2 = opsdb_get_info(type='QADR', /active)
files = info2.forv
ufiles = files( uniq(files, sort(files)))
ss1 = where(strpos(ufiles, '_v') ne -1, nss1)
ss2 = where(strpos(ufiles, '_v') eq -1, nss2)
;
for i=0,nss1-1 do file_append, outfil2, 'perf ' + opsdb_latest_ver(ufiles(ss1(i)), /noext)
prstr, 'Not putting the following routines in: ' + ufiles(ss2)
;
;
ff = file_list('', 'cam_reg*', /bydate)
for i=0,n_elements(ff)-1 do ff(i) = strmid(ff(i), 0, strpos(ff(i), '_v0'))
for i=0,n_elements(ff)-1 do ff(i) = opsdb_latest_ver(ff(i)+'.src', /noext)
;uff = ff(uniq(ff, sort(ff)))
uff = ff(uniq(ff))
nuff = n_elements(uff)
for i=0,nuff-1 do file_append, outfil2, 'perf ' + uff(i)
;for i=0,nuff-1 do file_append, outfil2, 'perf ' + opsdb_latest_ver(uff(i)+'.src', /noext)
;
ff = file_list('', 'set_ipvec*', /bydate)
for i=0,n_elements(ff)-1 do ff(i) = strmid(ff(i), 0, strpos(ff(i), '_v0'))
for i=0,n_elements(ff)-1 do ff(i) = opsdb_latest_ver(ff(i)+'.src', /noext)
;uff = ff(uniq(ff, sort(ff)))
uff = ff(uniq(ff))
nuff = n_elements(uff)
;;;uff = [uff(nuff-1), uff(0:nuff-2)]	;make "set_ipvectors" first
for i=0,nuff-1 do file_append, outfil2, 'perf ' + uff(i)
;for i=0,nuff-1 do file_append, outfil2, 'perf ' + opsdb_latest_ver(uff(i)+'.src', /noext)
;
;---- DEP file
;
for ii=0,1 do begin
    if (ii eq 0) then info2 = opsdb_get_info(type='OBS', /active) $
		else info2 = opsdb_get_info(type='CAM', /active)
    break_file, info2.forv, dsk_log, dir000, files
    addr = info2.addr
    uaddr = addr(uniq(addr, sort(addr)))
    for i=0,n_elements(uaddr)-1 do begin
        ss = where(addr eq uaddr(i), nss)
	if (nss gt 1) then begin
	    ss22 = where(info2(ss).label eq 'obs_std_str60')	&  if (max(ss22) gt -1) then begin & ss = ss(ss22) & nss = 1 & end
	    ss22 = where(info2(ss).label eq 'cam_vc2_obs')	&  if (max(ss22) gt -1) then begin & ss = ss(ss22) & nss = 1 & end
	end
        if (nss eq 1) then begin
	    out = files(ss(0)) 
        end else begin
	    iout = wmenu_sel(files(ss), /one)
	    out = files(ss(iout))
        end
        file_append, outfil1, 'perf ' + opsdb_latest_ver(out+'.src', /noext)
    end
end

ff = file_list('', ['exposure*', 'offset*'], /bydate)
for i=0,n_elements(ff)-1 do ff(i) = strmid(ff(i), 0, strpos(ff(i), '_v'))
for i=0,n_elements(ff)-1 do ff(i) = opsdb_latest_ver(ff(i)+'.src', /noext)
;uff = ff(uniq(ff, sort(ff)))
uff = ff(uniq(ff))
nuff = n_elements(uff)
for i=0,nuff-1 do file_append, outfil1, 'perf ' + uff(i)
;for i=0,nuff-1 do file_append, outfil1, 'perf ' + opsdb_latest_ver(uff(i)+'.src', /noext)



end
;-----------------------------------------------------------------
pro opsdb_test_lst, outfil, start_cam, nmin
;
;
;	opsdb_test_lst, '/mdisw/cfl/comm/src/test_comm_blk3c.src', 'cam_legff_fd', 40
;
;
info2 = opsdb_get_info(type='CAM', /active)
addr = opsdb_get_info(label=start_cam, /addr, /active)
ss = where(info2.addr ge addr, nss)
junk = opsdb_init_src_fil(outfil, /qwrite)
for i=0,nss-1 do file_append, outfil, $
                                ['## ---- About to test ' + info2(ss(i)).label, $
                                'set !GI9 = ' + strtrim(info2(ss(i)).index,2) + '               ## set capaign addr', $
                                'perf test1comm         ## stop and start structure/campaign', $
                                string('wait time ',40*60,'     ## let run for NN minutes', format='(a,i6,a)'), $
                                ' ']


;
end
;-----------------------------------------------------------------
pro opsdb_cfl_util, infil, cfl_dir

    break_file, infil, dsk_log, cfl_outdir, filnam000, ext000
    ;;cfl_outdir = str_replace(cfl_outdir, '/src/', '')
    cfl_outdir = cfl_dir
    tmp_fil = concat_dir(getenv('MDI_TEMP_DIR'), filnam000+ext000)
    if (infil ne tmp_fil) then begin
        ssw_file_delete, tmp_fil
        spawn, ['cp', infil, tmp_fil], /noshell
        ssw_file_delete, infil
    end
    cd, getenv('MDI_TEMP_DIR')
    cmd = [concat_dir(getenv('MDI_TASK_DIR'), 'cfl_util'), '-r', '-c', cfl_outdir, $
				'-p', filnam000]
    print, '>>>>>>>>>>>>>> ', cmd
    spawn, cmd, /noshell
    ssw_file_delete, tmp_fil

end
;-----------------------------------------------------------------
pro opsdb_proc_lst, lstname, prep=prep, load_ver=load_ver, copy=copy, $
	nosave=nosave, reset=reset, inmat=inmat, force=force, freeze_only=freeze_only, $
	unfreeze=unfreeze
;
;	opsdb_proc_lst, 'load8.lst'
;	opsdb_proc_lst, 'load8.lst', /prep, /copy
;	opsdb_proc_lst, 'load30.lst', /prep, /copy, /force
;
common opsdb_blk, dbdir, dbfilnam, dbinfo
;
if (not keyword_set(inmat)) then if (not file_exist(lstname)) then begin
    print, 'Cannot find: ' + lstname
    return
end
;
workdir = curdir()
;
if (keyword_set(prep)) then begin
    setenv, 'MDI_OPSDB_TYPE=PREP'
    ;;cfl_dir = '/mdisw/cfl/prep
    ;;base_dir = '/mdisw/cfl/prep'
    cfl_dir = '/mdisw/cfl/flight
    base_dir = '/mdisw/cfl/flight'
end else begin
    setenv, 'MDI_OPSDB_TYPE=DEV'
    cfl_dir = '/mdisw/cfl/dev
end
setenv, 'OPSDB_LOAD_VER='
if (keyword_set(load_ver)) then setenv, 'OPSDB_LOAD_VER=yes'
;
if (keyword_set(reset)) then begin
    ipdir = getenv('MDI_OPS_IP_DEP')
    ssw_file_delete, concat_dir(ipdir, 'opsdb_dev.genx')
    cmd = 'cp  ' + concat_dir(ipdir, 'opsdb_prep.genx') + ' ' + concat_dir(ipdir, 'opsdb_dev.genx')
    print, cmd
    spawn, cmd
    opsdb_rd_wrt, /qread
end else begin
    opsdb_rd_wrt, /qread		;MDM added 7-Apr-97
end
;
if (keyword_set(inmat)) then mat = inmat $
		else mat = rd_tfile(lstname, nocomment='#')
remtab, mat, mat
mat = strtrim(mat,2)
ss = where(mat ne '')
mat = mat(ss)
;
ss = where(strmid(mat, 0, 2) eq '>>', nss)
for i=0,nss-1 do begin
    arr = str2arr(strcompress(mat(ss(i))), delim=' ')
    case arr(1) of
	;; 'LOAD_FILE:': if (not keyword_set(prep)) then ld_file = arr(2)
	'LOAD_FILE:': ld_file = arr(2)
	'DELETE_OBS:': begin
		addr = opsdb_get_info(label=arr(2), /active, /addr)
		if (addr ne -1) then begin
		    info2 = opsdb_get_info(type='OBS', /active)
		    ss2 = where(info2.addr le addr)
		    opsdb_rm_entry, info2(ss2).label
		end
	    end
	'DELETE_CAM:': begin
		addr = opsdb_get_info(label=arr(2), /active, /addr)
		if (addr ne -1) then begin
		    info2 = opsdb_get_info(type='CAM', /active)
		    ss2 = where(info2.addr ge addr)
		    opsdb_rm_entry, info2(ss2).label
		end
	    end
	'EXECUTE_CMD:': begin
		cmd = arr2str(arr(2:*), delim=' ')
		stat = execute(cmd)
		if (stat ne 1) then message, 'Problem with EXECUTE_CMD from list file'
	    end
	'LOAD_CMD:': begin
		cmd = arr2str(arr(2:*), delim=' ')
		if (keyword_set(load_cmd) eq 0) then load_cmd = cmd else load_cmd = [load_cmd, cmd]
	    end
	else: message, 'Dont recognize keyword: ' + mat(ss(i))
    endcase
end
;
if (keyword_set(ld_file)) then begin
    break_file, ld_file, dsk_log, dir0000, ffff, eeee
    ld_file_tmp = concat_dir(getenv('GSE_TEMP_DIR'), ffff+eeee)
    if (keyword_set(prep)) then ld_file = concat_dir(workdir, ffff + eeee)	;drop the dir
end
;
cur_cfl_dir = 'xxx'
ss = where(strmid(mat, 0, 2) ne '>>', nss)
for i=0,nss-1 do begin
    arr = str2arr(strcompress(mat(ss(i))), delim=' ')
    infil = arr(0)
    print, 'PROC_LIST Now Processing: ' + infil
    break_file, infil, dsk_log, dir, filnam, ext
    break_file, strmid(dir, 0, strlen(dir)-1), dsk_log, base_dir0, sub_dir	;sub_dir = 'ip' or 'dep'
    ;
    if (keyword_set(copy)) then begin
	cd, workdir
	cmd = ['rcp', '-p', 'mdisim:'+infil, '.']
	print, cmd
	spawn, cmd, /noshell
	cmd = ['freeze', '-norecurse', '-force', filnam+ext]
	if (keyword_set(force)) then cmd = ['freeze', '-norecurse', '-force', filnam+ext]
	print, cmd
	spawn, cmd, result, /noshell
	qerr = (max(strpos(result, 'ERROR')) ge 0) or (max(strpos(result, 'WARNING')) ge 0)
	if (qerr) then stop, 'Error with freeze.  Stopping...'
    end
    ;
    if (keyword_set(freeze_only)) then begin
	cd, workdir
	cmd = ['freeze' , '-norecurse', '-force', '-host=mdisas', filnam+ext]
	print, cmd
	spawn, cmd, result, /noshell
	qerr = (max(strpos(result, 'ERROR')) ge 0) or (max(strpos(result, 'WARNING')) ge 0)
	if (qerr) then stop, 'Error with freeze.  Stopping...'
    end
    ;
    if (keyword_set(unfreeze)) then begin
	cd, workdir
	cmd = ['unfreeze', filnam+ext]
	spawn, cmd, /noshell
	cmd = ['freeze', '-norecurse', '-force', filnam+ext]
	if (keyword_set(force)) then cmd = ['freeze', '-norecurse', '-force', filnam+ext]
	print, cmd
	spawn, cmd, result, /noshell
	prstr, result, /nomore
	qerr = (max(strpos(result, 'ERROR')) ge 0) or (max(strpos(result, 'WARNING')) ge 0)
	if (qerr) then stop, 'Error with freeze.  Stopping...'
    end
    ;
    param = ''
    if (n_elements(arr) gt 1) then param = ',' + arr2str(arr(1:*), delim=' ')
    ;
    case ext of
	'.uobs': cmd = "opsdb_mk_obs_src, opsdb_latest_ver(filnam+ext)"
	'.obs':  cmd = "opsdb_mk_obs_src, opsdb_latest_ver(filnam+ext)"
	'.cam':  cmd = "opsdb_mk_cam_src, opsdb_latest_ver(filnam+ext)"
	'.tab':  cmd = "opsdb_mk_tab_src, opsdb_latest_ver(filnam+ext)"
	;
	'.ips':  cmd = "opsdb_mk_ips_src, opsdb_latest_ver(filnam+ext)"			;, pad=8"
	'.ipv':  cmd = "opsdb_mk_ipvec_src, opsdb_latest_ver(filnam+ext), cfl_dir"
	'.reg':  cmd = "opsdb_mk_ips_src, opsdb_latest_ver(filnam+ext), /direct_load"
	else: message, 'Dont recognize the file extension: ' + infil
    endcase
    ;
    if (keyword_set(base_dir)) then cd, concat_dir(base_dir, sub_dir) $
				else cd, concat_dir(base_dir0, sub_dir)
    print, 'Changing default dir to: ' + curdir()
    ;
    cmd = cmd + param
    if (ext eq '.ips') then if (strpos(cmd, 'pad=') eq -1) then cmd = cmd + ",pad=8"
    print, 'Issuing the following IDL command: ' + cmd
    stat = execute(cmd)
    if (stat ne 1) then message, 'Problem executing above command'
    ;
    if (keyword_set(ld_file)) then begin
	if (i eq 0) then junk = opsdb_init_src_fil(ld_file_tmp, /qwrite)
	if (not keyword_set(prep)) then begin
	    dir_arr = str2arr(dir, delim='/')
	    ;;;if (dir_arr(3) ne cur_cfl_dir) then file_append, ld_file_tmp, 'cd c "' + dir_arr(3) + '"'
	    cur_cfl_dir = dir_arr(3)
	end
	file_append, ld_file_tmp, 'perf ' + filnam
    end

;;    if (keyword_set(prep)) then begin
;;	spawn, 'latest ' + filnam+'.src', result
;;	if (i eq 0) then cer_cmd = 'certify '
;;	cer_cmd = cer_cmd + ' ' + result
;;	if (i eq 0) then cer_list = result(0) else cer_list = [cer_list, result(0)]
;;   end
end
;
if (keyword_set(ld_file) and keyword_set(load_cmd)) then file_append, ld_file_tmp, [' ', load_cmd]
;
if (keyword_set(ld_file) and (not keyword_set(prep)) and $
		(getenv('EGSE_VER') ge '5.2')) then opsdb_cfl_util, ld_file_tmp, cfl_dir $
				else spawn, ['mv', ld_file_tmp, ld_file], /noshell

if (not keyword_set(nosave)) then begin
    opsdb_print, /all, /active, outfil='$HOME/opsdb.list',xx,3
    opsdb_rd_wrt, /qwrite
    opsdb_rd_wrt, /qbackup
end
cd, workdir
;
for i=0,2 do opsdb_conf_chk, i
;
;;if (keyword_set(prep)) then begin
;;    print, 'Certify  ' + cer_cmd
;;    yesnox, 'Issue each of the certify commands?', ans, 'Yes'
;;    if (ans) then begin
;;	for i=0,n_elements(cer_list)-1 do begin
;;	    print, 'Certifying ' + cer_list(i) + '  ..........................'
;;	    spawn, ['certify', cer_list(i)], /noshell
;;	end
;;    end
;;end
;
end
;-----------------------------------------------------------------
pro go_mk_simp_cam
;
cd,'/mdisw/cfl/dev/dep'
opsdb_mk_simp_cam, 'obs_std_fd_mag', 'FD_M1_V1', 'Make and downlink cropped FD magnetogram and velocity


opsdb_mk_simp_cam, 'obs_std_hr_vel', 'P30C_HR_F1', 'Continuum from PRIME30 and HR filtergram'
opsdb_mk_simp_cam, 'obs_std_fd_vel', 'P30V_FD_V1', 'Two FD dopplergrams with smaller crop radius
opsdb_mk_simp_cam, 'obs_std_hr_vel', 'P30V_HR_FE', 'FD PRIME30 cropped velocity and HR 1024x800 filtergram', offset=1
opsdb_mk_simp_cam, 'obs_std_hr_mag', 'P30V_HR_ME', 'FD PRIME30 cropped velocity and HR 1024x640 magnetogram', offset=2
opsdb_mk_simp_cam, 'obs_std_hr_vel', 'P30V_HR_V2', 'FD PRIME30 cropped velocity and HR 2x2 binned velocity'
opsdb_mk_simp_cam, 'obs_std_hr_vel', 'P30V_HR_VE', 'FD PRIME30 cropped velocity and HR 1024x800 velocity', offset=3
opsdb_mk_simp_cam, 'obs_std_fd_vel', 'FD_F1_C1',   'FD filtergram and continuum observable cropped'
opsdb_mk_simp_cam, 'obs_std_fd_mag', 'FD_ME_VE',   'FD magnetogram and velocity 1024x800'
opsdb_mk_simp_cam, 'obs_std_fd_mag', 'FD_M1_V2',   'FD magnetogram cropped and velocity binned 2x2'
opsdb_mk_simp_cam, 'obs_std_fd_vel', 'FD_V1_L1',   'FD velocity and line-depth cropped'
;opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_M1_V2',   'HR magnetogram and 2x2 binned velocity'
;opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_V1_M2',   'HR velocity and 2x2 binned magnetogram'
;opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_VE_FE_M2','HR velocity and filtergram 1024x600, 2x2 bin mag', offset=4
;opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_F1_V2_M2','HR filtergram and 2x2 bin mag and velocity
opsdb_mk_simp_cam, 'obs_std_hr_vel', 'HR_FE_CE',   'HR filtergram and continuum observable 1024x800', offset=5
opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_FE_ME_V2','HR filtergram and mag 1024x640 and 2x2 bin velocity', offset=6
opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_M1_IPREG','HR magnetogram and IP registers'
opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_ME_FE',   'HR magnetogram and filtergram 1024x850', offset=7
opsdb_mk_simp_cam, 'obs_std_hr_vel', 'HR_V1_L2_F2','HR velocity and 2x2 bin line-depth and filtergram'
opsdb_mk_simp_cam, 'obs_std_hr_mag', 'HR_VE_FE_ME','HR velocity, filtergram and magnetogram 1024x500', offset=8
;
end
;-----------------------------------------------------------------
pro opsdb_new_tuning
;
;
;
opsdb_print, info, 3, /active, /obs
ss = sort(info.loaded)
info = info(ss)
;;out = info.forv
;;for i=1,20 do out = str_replace(out, '_v'+string(i,format='(i2.2)')+'.uobs', '.uobs')
out = info.label + '.uobs'	;label is always the file name
out = '/mdisw/cfl/dev/dep/' + out + '     /replace'
;
p2 = where_arr(info.label, ['obs_std_str30', 'obs_std_head', 'obs_std_tail', 'obs_std_fd_mag'])
p1 = rem_elem( indgen(n_elements(out)), p2)
;
out1 = ['>> LOAD_FILE:   /mdisw/cfl/dev/src/ld_newtune_part1.src', ' ', out(p1)]
prstr, out1, /nomore
prstr, out1, file='ld_newtune_part1.lst'
;
out2 = ['>> LOAD_FILE:   /mdisw/cfl/dev/src/ld_newtune_part2.src', ' ', out(p2)]
prstr, out2, /nomore
prstr, out2, file='ld_newtune_part2.lst'

end
