pro mk_orbit, infile=infile, outdir=outdir, wait=wait, mail=mail, $
	force_make=force_make, asca=asca, skip_orbit=skip_orbit, qstop=qstop
;
;+
;NAME:
;	mk_orbit
;PURPOSE:
;	Read the orbit solution file that is copied from the FACOM
;	computer and make the files used by DSNFIL with one orbit
;	solution per file.  Generate FEM files, aoslos files for op_first_guess
;	and the advance dsn predictions file.
;OPTIONAL INPUT:
;	infile	- The input file to use.  If not specified, it uses
;		  /ydb/orbit_sol/facom_orbit
;	wait	- The number of hours to wait before the FEM generation
;		  code is run (so that that code can run after midnight)
;	mail	- String vector of recipients of unix mail containing
;		  the dsn predictions.
;	force_make - Force the MK_ORBIT_FILES and MK_FEM routines to be
;		  called, even if there are no errors.
;	skip_orbit - Skip the MK_ORBIT_FILE calls
;OPTIONAL OUTPUT:
;	outdir	- Output directory (used for debugging purposes).  If not
;		  specified it writes to /ydb/orbit_sol.
;HISTORY:
;	Written 1-Mar-92 by M.Morrison
;	20-May-92 (MDM) Modified to run MK_FEM when a new orbit solution is
;			found.  It re-runs for for prior 2 weeks and runs
;			5 weeks ahead of the solution date
;	26-May-92 (MDM) changed to only do 1 week prior
;	 8-Jun-92 (MDM) added keyword wait so that when FEM files are made, 
;			it waits "wait" hours before running that portion
;	 8-sep-92 (JRL) Added mail keyword.  Added call to mk_orbit_files
;	22-sep-92 (JRL) Added auto purging of *ascii, *summ, dsn*txt files
;	15-Mar-93 (MDM) Added FORCE_MAKE option
;	 7-Apr-93 (MDM) Added /ASCA option to read the ASCA spacecraft
;			orbit predictions
;	15-Apr-93 (MDM) Modified to call MK_FEM even for ASCA
;	 4-may-93 (JRL) Implemented the DSN predictions for ASCA
;	19-May-93 (MDM) Fixed oversight - Added "asca=asca" switch to 
;			MK_ORBIT_FILES call for ASCA
;	20-May-93 (MDM) Added /SKIP_ORBIT option
;	 3-Aug-93 (MDM) Added TRAJ file check and mailing of the file
;			and renaming it
;	12-Aug-93 (MDM) Added "keep_ascii=4" to MK_ORBIT_FILES call for ASCA
;	10-May-94 (MDM) Added check for bad calculation
;	27-Jul-94 (MDM) Modified to check TRAJ files first, and if a TRAJ
;			file exists with no equivalent ORBIT file, create the
;			ORBIT file from the TRAJ file and kick off MK_FEM
;			and MK_ORBIT_FILES
;			File orbit_0173 was the last file created using
;			FACOM_ORBIT as the source.
;       26-oct-94 (SLF) fix file name problem 
;        4-nov-94 (SLF) handle format change in facom_orbit file 
;                       (call where_pattern)
;-
;
first_outfil = ''
;
asca=keyword_set(asca)			; slf, only 'ask' once

if asca then begin
    if (n_elements(outdir) eq 0) then outdir = getenv('DIR_ASCA_ORBIT_SOL')
    if (n_elements(infil) eq 0) then infil = '$DIR_ASCA_ORBIT_SOL/facom_orbit'
end else begin
    if (n_elements(outdir) eq 0) then outdir = getenv('DIR_GEN_ORBIT_SOL')
    if (n_elements(infil) eq 0) then infil = '$DIR_GEN_ORBIT_SOL/facom_orbit'
end
;
;---------------------------------------- Added TRAJ file check and mailing 3-Aug-93
;
ff = file_list(outdir, 'traj')
if (ff(0) ne '') then begin
    mail, users=mail, file=ff(0)
    spawn, 'grep "ELEMENT NO." ' + ff(0), result
    num = fix(strmid(result(0), 39, 4))
    outfil2 = concat_dir(outdir, 'traj_'+string(num, format='(i4.4)'))
    spawn, 'mv -f  ' + ff(0) + ' ' + outfil2
end
mail_old = ['morrison', 'lemen']	;only these guys get MK_DSN_PREDICT messages

;---------------------------------------- Check if TRAJ file exists with no comparable ORBIT file (MDM added 27-Jul-94)

ff = file_list(outdir, 'traj*')
for i=0,n_elements(ff)-1 do begin
    outfil = str_replace(ff(i), 'traj', 'orbit')
    if (not file_exist(outfil)) then begin
	ctraj2orbit, ff(i), asca=asca, /outfil
	if (first_outfil eq '') then first_outfil = outfil
    end
end
if (keyword_set(qstop)) then stop

;---------------------------------------- Check FACOM_ORBIT file (done after TRAJ file check)
;
;
barr=bytarr(file_stat(infil,/size))
openr, lun, infil, /get_lun
readu, lun, barr
free_lun, lun
;
; look for orbit solutions (SLF - 4/nov - handle format change)

pattern=(['SOLAR-A','ASTRO-D'])(asca)
solss=where_pattern(barr,pattern,nsol) - 17	  ; -17 is fixed offset between
					          ; search pattern and solution 
for i=0,nsol-1 do begin				  ; start
    solution=barr(solss(i):solss(i)+615)	  ; nbytes per solution
    solnum = string(solution(36:39))
    out = string(reform(solution(40:*), 16, 36))
    ;
    outfil = concat_dir(outdir, 'orbit_' + solnum)
    ;
    ff = findfile(outfil)
    if (ff(0) eq '') then begin
	qwrite = 1

	qfound_prev = 0
	iprev = fix(solnum) - 1
	while ((not qfound_prev) and (iprev ge 1)) do begin
	    outfil2 = concat_dir(outdir, 'orbit_' + string(iprev, format='(i4.4)'))
	    ff = findfile(outfil2)
	    if (ff(0) ne '') then qfound_prev = 1 else iprev = iprev - 1
	end
	if (qfound_prev) then begin
	    openr, lun, outfil2, /get_lun
	    test2 = ''
	    readf, lun, test2
	    free_lun, lun
	    test1 = ''
	    for j=0,4 do test1=test1 + out(j)
	    if (test1 eq test2) then begin
		qwrite = 0
		print, 'Previous solution file has the same data - NOT WRITTING'
	    end
	end
	
	if (qwrite) then begin
	    print, outfil, ' does not exist - making it now'
	    ;
	    openw, lun, outfil, /get_lun
	    printf, lun, string(out), format='(5a)'
	    free_lun, lun
	    if (first_outfil eq '') then first_outfil = outfil
	end
    end else begin
	print, outfil, ' exists - no action
    end
end
;
;
if (keyword_set(force_make)) then begin
    ff = file_list(outdir, 'orbit_*')
    first_outfil = ff(n_elements(ff)-1)
end
;
if (keyword_set(qstop)) then stop
;
if (first_outfil ne '') then begin
    if (not keyword_set(skip_orbit)) then begin
	; ---------------------------------------------------------------------
	; Generate aoslos *16s.ascii file for op_first_guess
	; Make the +4 to +8 week prediction for DSN contacts
	; ---------------------------------------------------------------------
	if not asca then begin
	    dsn_path = '$DIR_GEN_ORBIT'			; To write the dsn9*.txt file
	    mk_orbit_files,dsn_path=dsn_path,mail=mail_old,keep_ascii=4,keep_summ=4,keep_dsn=2
	endif else begin
	    dsn_path = '$DIR_ASCA_ORBIT'		; dsn9*.txt output path
	    mk_orbit_files,dsn_path=dsn_path,mail=mail_old,keep_ascii=4,keep_dsn=2,asca=asca
	endelse
	; ---------------------------------------------------------------------
    end

    if (keyword_set(wait)) then wait, wait*60.*60.

    openr, lun, first_outfil, /get_lun
    lin = ' '
    readf, lun, lin
    timarr = intarr(7)
    timarr(6) = strmid(lin,  0, 2)
    timarr(5) = strmid(lin,  2, 2)
    timarr(4) = strmid(lin,  4, 2)
    timarr(0) = strmid(lin,  6, 2)
    timarr(1) = strmid(lin,  8, 2)
    timarr(2) = strmid(lin, 10, 2)
    ex2int, timarr, time, day
    day = day - 7			;back up one week1
    int2ex, time, day, timarr
    sttim = fmt_tim(timarr)
    day = day + 6*7			;do 6 weeks worth
    int2ex, time, day, timarr
    entim = fmt_tim(timarr)
    weeks = week_loop(sttim, entim)
    print, 'Regenerating FEM files for week from ', sttim, ' to ', entim
    for i=0,n_elements(weeks)-1 do mk_fem, weeks(i).year, weeks(i).week, asca=asca
    ;
    ;----- MDM added check for bad data 10-May-94
    rd_fem,'1-sep-91', anytim2ints(!stime, off=28.*86400), fem
    dd = deriv_arr(int2secarr(fem))/60.
    ss = where(dd lt 40)
    if (ss(0) ne -1) then begin
	tim2orbit, fem(ss), wid=wid
	str = fmt_tim(fem(ss)) + '   == Week ' + wid
	message = ['MK_ORBIT: Bad FEM file generation', $
		'The time between orbits is not correct.  Bogus FEM entry', $
		'  ' + str, $
		'FEM files need to be deleted and re-made.  See Mons']
	mail, message, user='software@isass0', subj='MK_ORBIT Problem with Fem Files'
    end
end

end
