;
; hkplot.pro - state of the art IDL program for displaying
;            HK plot data from read_hist utility
;
; To access history files in another directory:
;  1) Abort this program
;  2) exit IDL
;  3) Type: setenv MDI_HISTORY_DIR <dir>
;     where <dir> is the new history file directory
;  4) start IDL
;  5) Run this program
;
; NOTE: In order for this program to remove the temporary files generated
; by read_hist in the temporary files directory, the directory must be
; writable by the user. Currently anyone in the mdi group can access
; MDI data because a 'chmod g+w $MDI_TEMP_DIR' was done.
;
;**************************************************
; line_ok - function returns 1 if first characters on line ==
;   'end', 'oplot', or 'plot', else returns 0
;**************************************************
function line_ok,line_arg

x = strpos(line_arg,'end')
if x eq 0 then begin
  return,1			; found end
end else begin			; if not end
  x = strpos(line_arg,'oplot')
  if x eq 0 then begin		; if oplot
    return,1
  end else begin
    x = strpos(line_arg,'plot')
    if x eq 0 then begin	; if plot
      return,1
    end else begin		; if not end,oplot, or plot
      x = strpos(line_arg,'plotave')
      if x eq 0 then begin
        return,1
      end else begin
        return,0
      endelse
    endelse
  endelse
endelse
end	; end of line_ok
;************************************************************************
; check_date - validates the user input date in format: dd-mmm-yy
;************************************************************************

function check_date,date_str

tmp_str = ''
num = 0
found = 0
months = 'janfebmaraprmayjunjulaugsepoctnovdec'

tmp_str = strmid(date_str,0,2)
num = fix(tmp_str)
if num lt 1 OR num gt 31 then return,0	; day out of range
tmp_str = strmid(date_str,2,1)
if tmp_str ne '-' then return,0	; missing 1st -
tmp_str = strmid(date_str,3,3)
for i = 1,12 do begin
  if strlowcase(tmp_str) eq strmid(months,(i-1)*3,3) then begin
    found = 1
  endif
endfor
if found ne 1 then return,0	; bad month
tmp_str = strmid(date_str,6,1)
if tmp_str ne '-' then return,0	; missing 2nd -
tmp_str = strmid(date_str,7,2)
num = fix(tmp_str)
if num lt 92 then return,0	; year out of range
return,1
end
;************************************************************************
; check_time - validates the user input time in format: hh:mm or hh:mm:ss
;************************************************************************

function check_time,time_str

tmp_str = ''
num = 0
found = 0

tmp_str = strmid(time_str,0,2)
num = fix(tmp_str)
if num lt 0 OR num gt 24 then return,0	; hour out of range
tmp_str = strmid(time_str,2,1)
if tmp_str ne ':' then return,0	; missing 1st :
tmp_str = strmid(time_str,3,2)
num = fix(tmp_str)
if num lt 0 OR num gt 59 then return,0	; minutes out of range
if strlen(time_str) gt 5 then begin
  tmp_str = strmid(time_str,5,1)
  if tmp_str ne ':' then return,0	; missing 2nd :
  tmp_str = strmid(time_str,6,2)	; get optional seconds
  num = fix(tmp_str)
  if num lt 0 OR num gt 59 then return,0	; seconds out of range
endif
return,1
end


;***********************************************************************
; dur2sec - converts a time duration specified as hh:mm:ss to seconds
;***********************************************************************
function dur2sec,time_str

tmp_str = ''
num = 0
found = 0

tmp_str = strmid(time_str,0,2)
dur_hr = fix(tmp_str)
tmp_str = strmid(time_str,3,2)
dur_min = fix(tmp_str)
if strlen(time_str) gt 5 then begin
  tmp_str = strmid(time_str,6,2)	; get optional seconds
  dur_sec = fix(tmp_str)
endif else begin
  dur_sec = 0
endelse

dur = dur_hr * 3600 + dur_min * 60 + dur_sec

return, dur
end

;***********************************************************************
;Update Time
;***********************************************************************
function update_time, date_str, time_str, dur_str

months = 'janfebmaraprmayjunjulaugsepoctnovdec'
numdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

print, date_str
day_str = strmid(date_str,0,2)
day = fix(day_str)
print,day_str, day
;if day lt 1 OR day gt 31 then return,0	; day out of range
tmp_str = strmid(date_str,2,1)
;if tmp_str ne '-' then return,0	; missing 1st -
mon_str = strmid(date_str,3,3)
mon = 1
print,'1: ',mon_str, mon 
while ( strlowcase(mon_str) ne strmid(months,(mon-1)*3,3) ) do begin
  mon = mon + 1
  print, mon
endwhile
print,'2: ',mon_str, mon 

tmp_str = strmid(date_str,6,1)
if tmp_str ne '-' then return,0	; missing 2nd -
yr_str = strmid(date_str,7,2)
yr = fix(yr_str)
print, yr_str, yr
if yr lt 92 then return,0	; year out of range

hr_str = strmid(time_str,0,2)
hr = fix(hr_str)
if hr lt 0 OR hr gt 24 then return,0	; hour out of range
tmp_str = strmid(time_str,2,1)
if tmp_str ne ':' then return,0	; missing 1st :
min_str = strmid(time_str,3,2)
min = fix(min_str)
if min lt 0 OR min gt 59 then return,0	; minutes out of range
if strlen(time_str) gt 5 then begin
  tmp_str = strmid(time_str,5,1)
  if tmp_str ne ':' then return,0	; missing 2nd :
  sec_str = strmid(time_str,6,2)	; get optional seconds
  sec = fix(sec_str)
  if sec lt 0 OR sec gt 59 then return,0	; seconds out of range
endif else begin
  sec = 0
endelse

print, dur_str
dur_hr_str = strmid (dur_str, 0, 2)
dur_hr = fix (dur_hr_str)
print, dur_hr_str, dur_hr
dur_min_str = strmid (dur_str, 3, 2)
dur_min = fix (dur_min_str)
print, dur_min_str, dur_min
dur_sec_str = strmid (dur_str, 6, 2)
dur_sec = fix (dur_sec_str)
print, dur_sec_str, dur_sec

sec = sec + dur_sec
if (sec ge 60) then begin
    sec = sec - 60
    min = min + 1
endif

min = min + dur_min
if (min ge 60) then begin
    min = min - 60
    hr = hr + 1
endif

hr = hr + dur_hr
if (hr ge 24) then begin
    hr = hr - 24
    day = day + 1
endif

daylim = numdays(mon)
if ( (mon eq 2) and ((yr mod 400) ne 0) and ((yr mod 4) eq 0) ) then daylim = 29
if (day ge numdays(mon)) then begin
    day = day - numdays(mon)
    mon = mon + 1
endif

if (mon ge 12) then begin
    mon = mon - 12
    yr = yr + 1
endif

mon_str = strmid(months,(mon-1)*3,3)  
date_str = string (format = "(I2.2, '-', A3, '-', I2.2)", day, mon_str, yr)
time_str = string (format = "(I2.2, ':', I2.2, ':', I2.2)", hr, min, sec)
return, 1
end
;************************************************************************
; check_duration - validates the user input duration in format: hh:mm or
;    hh:mm:ss or with local time specifier: hh:mmL or hh:mm:ssL
;************************************************************************

function check_duration,duration_str

tmp_str = ''
num = 0
found = 0

tmp_str = strmid(duration_str,0,2)
num = fix(tmp_str)
if num lt 0 OR num gt 24 then return,0	; hour out of range
tmp_str = strmid(duration_str,2,1)
if tmp_str ne ':' then return,0	        ; missing 1st :
tmp_str = strmid(duration_str,3,2)
num = fix(tmp_str)
if num lt 0 OR num gt 59 then return,0	; minutes out of range
if strlen(duration_str) gt 5 then begin
  tmp_str = strmid(duration_str,5,1)
  if tmp_str ne ':' then begin		; not optional seconds
    if tmp_str ne 'L' AND tmp_str ne 'l' then begin
      return,0				; not optional local time specifier
    end else begin
      return,2
    endelse
  end else begin
    tmp_str = strmid(duration_str,6,2)	; get optional seconds
    num = fix(tmp_str)
    if num lt 0 OR num gt 59 then return,0	; seconds out of range
    if strlen(duration_str) gt 8 then begin
      tmp_str = strmid(duration_str,8,1)	; get optional local time spec
      if tmp_str ne 'L' AND tmp_str ne 'l' then begin
        return,0			; not optional local time specifier
      end else begin
        return,2
      endelse
    endif
  endelse
endif
return,1
end
;************************************************************************
; get_input - prompts user for:
;		starting date of plot
;		starting time of plot
;		duration of plot
;		filename containing mnemonics to plot
;		  else accepts plot commands
;		  then asks for filename for writing the input plot commands
; ARGUMENTS:
;   file_parms: (structure) 
;     input:
;       max_mnemos: max # input mnemonics and therefore max # of input lines
;       max_args  : max args on input line
;     output:
;       n_mnemos  : # mnemos actually input
;   input_line: (structure) output: str array set to input lines
;************************************************************************
pro get_input,file_parms,input_line,auto=auto

tmp_date = ''	; contains user input date
tmp_time = ''	; contains user input time
tmp_duration = ''; contains user input time length of plot
in_fn = ''	; input filename of file containing mnemonics to plot
out_fn = ''	; output filename of file containing mnemonics to plot
line1 = ''
line2 = ''
tmp_line = ''
tmp_str = ''
day = 0
rt_plot = 1     ; real time plots
 
done = 0
if keyword_set(auto) eq 1 then goto,do_auto
if (rt_plot ne 1) then begin
repeat begin
  if file_parms.date eq '' then begin
    print,FORMAT='($,"Enter date (DD-MMM-YY i.e. 01-oct-93) ")'
    read,tmp_date
    if tmp_date ne '' then begin	; if user input
      if check_date(tmp_date) ne 1 then begin
        print,"Invalid date"
      end else begin
        file_parms.date = tmp_date
        done = 1
      endelse
    end else begin
      print,"Invalid date"
    endelse
  end else begin
    print,file_parms.date,FORMAT='($,"Enter date (<CR>=",A,") ")'
    read,tmp_date
    if tmp_date ne '' then begin	; if user input
      if check_date(tmp_date) ne 1 then begin
        print,"Invalid date"
      end else begin
        file_parms.date = tmp_date
      endelse
    endif
    done = 1
  endelse
endrep until done

done = 0
repeat begin
  if file_parms.time eq '' then begin
    print,FORMAT='($,"Enter time (HH:MM:SS | HH:MM)")'
    read,tmp_time
    if tmp_time ne '' then begin	; if user input
      if check_time(tmp_time) ne 1 then begin
        print,"Invalid time"
      end else begin
        file_parms.time = tmp_time
        done = 1
      endelse
    end else begin
      print,"Invalid time"
    endelse
  end else begin
    print,file_parms.time,FORMAT='($,"Enter time (<CR>=",A,") ")'
    read,tmp_time
    if tmp_time ne '' then begin	; if user input
      if check_time(tmp_time) ne 1 then begin
        print,"Invalid time"
      end else begin
        file_parms.time = tmp_time
      endelse
    endif
    done = 1
  endelse
endrep until done

done = 0
file_parms.local_time = 0
endif

repeat begin
  if file_parms.duration eq '' then begin
   print,FORMAT='($,"Enter duration (HH:MM:SS[L] | HH:MM[L] L for local time)")'
    read,tmp_duration
    if tmp_duration ne '' then begin	; if user input
      ret = check_duration(tmp_duration)
      case ret of
        '0': begin 			; invalid
              print,"Invalid duration"
             end
        '1': begin 			; valid, no local time spec
              file_parms.duration = tmp_duration
              done = 1
             end
        '2': begin 			; valid, local time spec
              file_parms.duration = tmp_duration
              file_parms.local_time = 1
              done = 1
             end
         else:
       endcase
    end else begin
      print,"Invalid duration"
    endelse
  end else begin
    print,file_parms.duration,FORMAT='($,"Enter duration (<CR>=",A,") ")'
    read,tmp_duration
    if tmp_duration ne '' then begin	; if user input
      ret = check_duration(tmp_duration)
      case ret of
        '0': begin 			; invalid
              print,"Invalid duration"
             end
        '1': begin 			; valid, no local time spec
              file_parms.duration = tmp_duration
              done = 1
             end
        '2': begin 			; valid, local time spec
              file_parms.duration = tmp_duration
              file_parms.local_time = 1
              done = 1
             end
        else:
        endcase
      end else begin
        done = 1
      endelse
  endelse
endrep until done

if (rt_plot eq 1) then begin
    print, FORMAT='($,"Enter Update Interval in seconds: ")'
    read, tmp_upd_int
    file_parms.update_int = tmp_upd_int
endif

do_auto:
if keyword_set(auto) eq 1 then in_fn = file_parms.fn_arg
again = ''
if file_parms.n_mnemos ge 1 then begin
  print,FORMAT='($,"Use last mnemonics again? (<CR>=YES,y=YES,n=NO)")'
  read,again
  if again eq '' OR again eq 'y' then goto,skip_input
endif
done = 0
repeat begin
  if file_parms.fn_arg eq '' then begin
    print,"Enter input file name or hit return for interactive mode"
    read,in_fn
  endif
  n_mnemos = 0
  if in_fn eq '' then begin
    print,"Interactive Mode"
    print,"type 'plot <mnemonic> [y_low y_high | a]<CR>' for each mnemonic to plot"
    print,"type 'end' to terminate input mode"
    print,"Max of 4 mnemonics, Example:  plot m+5cm      (default to auto y scale)"
    print,"                              plot m+5ip a    ( use auto y scale )"
    print,"                              plot m+5ip 5 30 ( specify y scale )"
    print,"                              plot m+5ip p    ( use previous y scale )"
    print,"                              end"
    while tmp_line ne 'end' do begin
      read,tmp_line		; read a line from the tty
      line1 = strtrim(tmp_line,2)	; remove leading and trailing whitespace
      line2 = strcompress(line1)	; shrink whitespace to single blank
      if line_ok(line2) eq 1 then begin
        if line2 ne 'end' then begin
          input_line(n_mnemos).str = line2
          n_mnemos = n_mnemos + 1
        end else begin
          done = 1
        endelse
      end else begin
        print,"Invalid line: ",tmp_line
      endelse
    endwhile
    if n_mnemos lt 1 then begin
      print,"No data saved, exitting"
      exit
    end else begin
      print,"Enter output file name to save plot commands"
      print,"  output file will go to directory: ",getenv("MDI_TEMP_DIR")
      print,"  or just hit return if no save desired"
      read,out_fn
      if out_fn ne '' then begin
        path = string(format='((A),"/",(A))',getenv("MDI_TEMP_DIR"),out_fn)
        openw,unit,path,/GET_LUN
        for j=0,n_mnemos-1 do begin
          printf,unit,format='(a)',input_line(j).str
        endfor
        close,unit
        free_lun,unit
      endif
    endelse	; end of if saving interactive commands in file for user
  end else begin			; if plot specification is in a file
    path = string(format='((A),"/",(A))',getenv("MDI_TEMP_DIR"),in_fn)
    openr,unit,path,/GET_LUN
    tmp_line = ' '
    done = 0
    while eof(unit) eq 0 AND done eq 0 do begin
      readf,unit,tmp_line 	; read a line from the file
      line1 = strtrim(tmp_line,2)	; remove leading and trailing whitespace
      line2 = strcompress(line1)	; shrink whitespace to single blank
      if line_ok(line2) eq 1 then begin
        if line2 eq 'end' then begin
          done = 1
        end else begin
          input_line(n_mnemos).str = line2
          n_mnemos = n_mnemos + 1
        endelse
      end else begin
        print,"Invalid line: ",tmp_line
      endelse
    endwhile
    close,unit
    free_lun,unit
    if n_mnemos lt 1 then begin
      print,"No data found in file: ",path
      exit
    endif
  endelse
endrep until done
file_parms.n_mnemos = n_mnemos
skip_input:
return
end	; end of get_input
;**************************************************
; plot_it
;**************************************************
pro plot_it,hk,n_data_values,time_axis,data,date_str,start_hrs,start_min,start_sec,y_value,index,local_time

;openr,unit,path,/GET_LUN
;tmp_data = assoc(unit,fltarr(n_data_values));
;data = tmp_data(0)
;close,unit
;free_lun,unit

!x.margin=6
!y.margin=5
if local_time eq 1 then begin
  time_str = 'LOCAL'
end else begin
  time_str = 'T A I'
endelse
!x.title = '!c' + string(format='((A),"   t i m e  starting  ",(A))',$
	time_str,date_str)
units_title = hk.units
!y.title = units_title
print,"setting t_str..."
t_str = string(format='((A),4X,(A))',hk.mnemo,hk.descr)
;t_str = "junk"
x_min = min(time_axis)
x_max = max(time_axis)
y_min = min(data)
y_max = max(data)
n_x_ticks = 4
x_interval = x_max / (n_x_ticks-1)
print,"setting xtitle..."
xtitle = string(replicate(' ',n_x_ticks))
tmp_hrs = start_hrs
tmp_min = start_min
tmp_sec = start_sec
for i=0,n_x_ticks-1 do begin
print,"fooey..."
  xtitle(i) = string(format='((I2.2),":",(I2.2),":",(I2.2))',$
  tmp_hrs,tmp_min,tmp_sec)
  n_sec = tmp_sec + x_interval
  tmp_sec = n_sec mod 60
  carry_min = n_sec / 60
  n_min = tmp_min + carry_min
  tmp_min = n_min mod 60
  carry_hrs = n_min / 60
  n_hrs = tmp_hrs + carry_hrs
  tmp_hrs = n_hrs mod 24
endfor
y_low = y_min - 5
y_hi = y_max + 5
case y_value.y_scale of
  'x': begin 			; use arguments for the y scale 
         y_value.old_low = y_value.new_low
         y_value.old_high = y_value.new_high
         y_low = y_value.new_low
         y_hi = y_value.new_high
       end
  'p': begin 			; use previous y scale arguments
         y_value.new_low = y_low
         y_value.new_high = y_hi
         y_low = y_value.old_low
         y_hi = y_value.old_high
       end
  'a': begin 			; auto scaling
         if index eq 0 then begin	; if old and new vals not set
           y_value.old_low = y_low
           y_value.old_high = y_hi
         end else begin
           y_value.old_low = y_value.new_low
           y_value.old_high = y_value.new_high
         endelse
         y_value.new_low = y_low
         y_value.new_high = y_hi
       end
  else:
endcase
plot,time_axis,data,xrange =[x_min,x_max],$
yrange =[y_low,y_hi],xminor=-1,xticks=n_x_ticks-1,xtickname=xtitle,$
title=t_str,charsize=.8,xstyle=1

return
end	; end of plot_it
;**************************************************************************
; do_plot - 5 (optional) command line arguments
;
; ARGUMENTS:
;   file_parms: (structure) 
;     input:
;       max_mnemos: max # input mnemonics and therefore max # of input lines
;       max_args  : max args on input line
;     output:
;       n_mnemos  : # mnemos actually input
;**************************************************************************
pro do_plot,file_parms,input_line,auto=auto
xwp = [16,824,16,824]		; max of 4 windows
ywp = [704,704,16,16]		; max of 4 windows
str81 =  string(replicate(32b,80))
str9 =   string(replicate(32b,10))
str5 =   string(replicate(32b,6))
str32 =  string(replicate(32b,33))
line2 = ''
line3 = ''

y_value = { y_scale: ' ', old_low: 0, old_high: 0, new_low: 0, new_high: 0 }
y_scale = string(replicate('a',file_parms.max_mnemos ))
;
; get a unique pid extension for temp file
;
pid_ext = 0L
spawn,'echo > /dev/null',pid=pid_ext	
tmp_pid_str = string(format='(I)',pid_ext)
pid_str = strtrim(tmp_pid_str,2)	; remove leading and trailing whitespace
;
; get_input will set input_line array either from a user file or from
; keyboard input. file_parms.n_mnemos is also set
;
;get_input,file_parms,input_line,auto=auto
cmd =  replicate( { str: str81 }, file_parms.max_args )
i = 0

  n_tokens = 0
  start = 0
  stop = 0
  cur_len = 0
  last_len = strlen(input_line)	; init length of last token on line
  repeat begin
    stop = strpos(input_line,' ',start)
    if stop ne -1 then begin	; if found a blank
      cur_len = stop - start
      cmd(n_tokens).str = strmid(input_line,start,cur_len)
      n_tokens = n_tokens + 1
      last_len = last_len - cur_len
      start = stop + 1
    endif
  endrep until stop eq -1
  last_len = last_len - n_tokens
  cmd(n_tokens).str = strmid(input_line,start,last_len)
  n_tokens = n_tokens + 1
  if (n_tokens lt 2) OR (n_tokens gt 4) OR $
        (cmd(0).str ne 'plot' AND cmd(0).str ne 'oplot') then begin
    print,"Invalid entry at line: ",i + 1
    stop
  endif
  case n_tokens of
  4: begin 	;if optional y_low & y_high on line
;       print,"GOT YLOW = ",cmd(2).str
       y_scale(i) = 'x'
       y_value.new_low = fix(cmd(2).str)
;       print,"GOT YHIGH = ",cmd(3).str
       y_value.new_high = fix(cmd(3).str)
     end
  3: begin
       case cmd(2).str of
         'p': begin 	;if p for use previous values
                if i eq 0 then begin
                  print,"No previous values set, autoscaling..."
                  y_scale(i) = 'a'
                end else begin
                  y_scale(i) = 'p'
                endelse
              end
         'a': begin 	;if a for auto scaling
                y_scale(i) = 'a'
              end
         else: begin
                 print,$
		   format='("Invalid entry at line: ",(I)," in file: ",(A))',$
							line_no,mnemo_pn
               stop
               end
       endcase
     end
  2: begin 	;if only plot mnemo or oplot mnemo
       y_scale(i) = 'a'	; default to auto scaling
     end
  else: begin
	  print,"Invalid number of tokens on input line: ",n_tokens
	  stop
	end
  endcase
  i = i + 1

fn = file_parms.date + "," + file_parms.time + "-" + file_parms.duration
n_data_values = get_hk (cmd(1).str, fn, stime, hk, time_axis, data_arr)
n_hk_vals = 1

;task_pn = string(format='((A),"/read_hist")',getenv("MDI_TASK_DIR"))
;if file_parms.n_mnemos gt 1 then begin
;  spawn,[task_pn,'-b','-f',tmp_fn,fn],/noshell,pid=pid_ext
;end else begin
;  spawn,[task_pn,'-b','-m',cmd(1).str,fn],/noshell,pid=pid_ext
;endelse
;tmp_pid_str = string(format='(I)',pid_ext)
;pid_str = strtrim(tmp_pid_str,2)	; remove leading and trailing whitespace
;
;time_pn = string(format='((A),"/time.",(A))',getenv("MDI_TEMP_DIR"),pid_str)
;openr,unit,time_pn,/GET_LUN
;n_hk_vals = 0L
;n_data_values = 0L
;header_offset = 0L
;start_hrs = 0L
;start_min = 0L
;start_sec = 0L
;start_time = string(replicate(32b,8))
;readu,unit,n_hk_vals,n_data_values,header_offset,start_hrs,start_min,start_sec
;hk =  replicate( { mnemo: str9,$
;		   units: str5,$
;		   descr: str32}, n_hk_vals )
;readu,unit,hk
;tmp_time = assoc(unit,lonarr(n_data_values),header_offset);
;time_axis = tmp_time(0)
;close,unit
;free_lun,unit
path =  replicate( { str: str81 }, n_hk_vals )

set_plot,'X' 

if (cmd(0).str eq 'oplot') then begin
  oplot, time_axis, data_arr
endif else begin
  if !D.NAME eq 'X' then begin
    window,i,title=hk.mnemo,retain=2,xpos=xwp(i),ypos=ywp(i)
  endif
  t_mnemo = strtrim(hk.mnemo,2)
  path(0).str = string(format='((A),"/",(A),".",(A))',$
				getenv("MDI_TEMP_DIR"),t_mnemo,pid_str)
  y_value.y_scale = y_scale(0)
  start_hrs = stime(0)
  start_min = stime(1)
  start_sec = stime(2)
  plot_it,hk,n_data_values,time_axis,data_arr,file_parms.date,$
          start_hrs,start_min,start_sec,y_value,i,file_parms.local_time
endelse

get_hardcopy = ''
if keyword_set(auto) eq 0 then begin
  case file_parms.hcopy of
    0: begin
         print,FORMAT='($,"Do you want a hardcopy? (<CR>=NO,y=YES,n=NO)")'
         hcopy = 0
       end
    1: begin
         print,FORMAT='($,"Do you want a hardcopy? (<CR>=YES,y=YES,n=NO)")'
         hcopy = 1
       end
  else: print,"INVALID VALUE FOR file_parms.hcopy: ",fileparms.hcopy
  endcase
  read,get_hardcopy
end else begin
  hcopy = file_parms.hcopy
endelse
if (get_hardcopy eq 'y') OR ((get_hardcopy eq '') AND (hcopy eq 1)) then begin
  cmd = 'rm idl.ps'
  spawn,cmd
  set_plot,'PS' 
  for i=0,n_hk_vals-1 do begin
    if !D.NAME eq 'X' then begin
      window,i,title=hk(i).mnemo,retain=2,xpos=xwp(i),ypos=ywp(i)
    endif
    t_mnemo = strtrim(hk(i).mnemo,2)
    y_value.y_scale = y_scale(i)
    plot_it,hk(i),n_data_values,time_axis,file_parms.date,$
      start_hrs,start_min,start_sec,path(i).str,y_value,i,file_parms.local_time
  endfor
  device,bits_per_pixel=8,/close
  file = 'idl.' + STRLOWCASE(!D.NAME)
  cmd = 'lp ' + file
  spawn,cmd
  set_plot,'X' 
endif
;if file_parms.disp_msgs eq 1 then begin
;  print,"HKPLOT - Removing temporary files..."
;endif
; Clean up by removing temporary files
;if file_parms.n_mnemos gt 1 then begin
;  cmd = 'rm ' + plot_mnemos_pn
;  spawn,cmd
;endif
; remove the time axis file time.<pid_str>
;cmd = 'rm ' + time_pn
;spawn,cmd
; remove all the mnemonic files <mnemo>.<pid_str>
;for i=0,n_hk_vals-1 do begin
;  cmd = 'rm ' + path(i).str
;  spawn,cmd
;endfor
end	; end of do_plot
;
;**************************************************************************
; do_OPLOT
; Calls do_PLOT to overlay a plot
;**************************************************************************
pro do_OPLOT, file_parms, cmd_line, auto=auto

do_plot, file_parms, cmd_line, auto=auto
end
;
;**************************************************************************
; do_AVERAGE
; Parses an input line of the form AVE mn1 mn2 mn3... and reads data for
; mnemonics mn1 mn2 mn3 etc.
;
;**************************************************************************
pro do_plotave, file_parms, cmd_line, auto=auto

xwp = [16,824,16,824]		; max of 4 windows
ywp = [704,704,16,16]		; max of 4 windows
str81 =  string(replicate(32b,80))
str9 =   string(replicate(32b,10))
str5 =   string(replicate(32b,6))
str32 =  string(replicate(32b,33))
line2 = ''
line3 = ''
max_tokens = 10

y_value = { y_scale: ' ', old_low: 0, old_high: 0, new_low: 0, new_high: 0 }
cmd = replicate( { str: str81 }, max_tokens)

n_tokens = 0
start = 0
stop = 0
cur_len = 0
last_len = strlen(cmd_line)	; init length of last token on line
repeat begin
    stop = strpos(cmd_line, ' ',start)
    if stop ne -1 then begin	; if found a blank
        cur_len = stop - start
        cmd(n_tokens).str = strmid(cmd_line,start,cur_len)
        n_tokens = n_tokens + 1
        last_len = last_len - cur_len
        start = stop + 1
    endif
endrep until stop eq -1
last_len = last_len - n_tokens
cmd(n_tokens).str = strmid(cmd_line,start,last_len)
n_tokens = n_tokens + 1

;==> Each element of cmd now contains a token. The first token should be AVERAGE.
if ( strupcase (cmd(0).str) NE 'PLOTAVE') then begin
    stop
endif

;==> The 2nd token is the number of mnemonics
n_mnems = fix (cmd(1).str)

;==> If the number of tokens > 2 + n_mnems, y axis scaling has been specified
y_axis_tokens = n_tokens - (2 + n_mnems)
case y_axis_tokens of 
    1: y_scale = cmd(2+n_mnems).str
    2: begin
        y_scale = 'x'
        y_value.new_low  = fix ( cmd(2+n_mnems).str )
        y_value.new_high = fix ( cmd(3+n_mnems).str )
       end
    else: begin
            y_scale = 'a'
          end
endcase

;==> Now get data for each parameter identified by a mnemonic
for i = 1, n_mnems do begin
    fn = file_parms.date + "," + file_parms.time + "-" + file_parms.duration
  print, fn
    n_data_values = get_hk (cmd(i+1).str, fn, stime, hk, time_axis, data_arr)
    if (i EQ 1) then data = data_arr
    if (i GT 1) then data = data + data_arr
endfor

;==> Calculate average
data = data / n_tokens

n_hk_vals = 1

path =  replicate( { str: str81 }, n_hk_vals )

set_plot,'X' 
for i=0,n_hk_vals-1 do begin
    if !D.NAME eq 'X' then begin
        window,i,title=hk(i).mnemo,retain=2,xpos=xwp(i),ypos=ywp(i)
    endif
    t_mnemo = strtrim(hk(i).mnemo,2)
    ;path(i).str = string(format='((A),"/",(A),".",(A))',$
    ;			getenv("MDI_TEMP_DIR"),t_mnemo,pid_str)
    y_value.y_scale = y_scale(i)
    start_hrs = stime(0)
    start_min = stime(1)
    start_sec = stime(2)
    plot_it,hk,n_data_values,time_axis,data,file_parms.date,$
               start_hrs,start_min,start_sec,y_value,i,file_parms.local_time
endfor

get_hardcopy = ''
if keyword_set(auto) eq 0 then begin
  case file_parms.hcopy of
    0: begin
         print,FORMAT='($,"Do you want a hardcopy? (<CR>=NO,y=YES,n=NO)")'
         hcopy = 0
       end
    1: begin
         print,FORMAT='($,"Do you want a hardcopy? (<CR>=YES,y=YES,n=NO)")'
         hcopy = 1
       end
  else: print,"INVALID VALUE FOR file_parms.hcopy: ",fileparms.hcopy
  endcase
  read,get_hardcopy
end else begin
  hcopy = file_parms.hcopy
endelse
if (get_hardcopy eq 'y') OR ((get_hardcopy eq '') AND (hcopy eq 1)) then begin
  cmd = 'rm idl.ps'
  spawn,cmd
  set_plot,'PS' 
  for i=0,n_hk_vals-1 do begin
    if !D.NAME eq 'X' then begin
      window,i,title=hk(i).mnemo,retain=2,xpos=xwp(i),ypos=ywp(i)
    endif
    t_mnemo = strtrim(hk(i).mnemo,2)
    y_value.y_scale = y_scale(i)
    plot_it,hk(i),n_data_values,time_axis,file_parms.date,$
      start_hrs,start_min,start_sec,path(i).str,y_value,i,file_parms.local_time
  endfor
  device,bits_per_pixel=8,/close
  file = 'idl.' + STRLOWCASE(!D.NAME)
  cmd = 'lp ' + file
  spawn,cmd
  set_plot,'X' 
endif

end	; end of average

;**************************************************
; rtplot
; to use auto mode (no prompts) do a command line like:
; hkplot,'05-nov-93','00:00','12:00','frog',0,/auto
;**************************************************
pro rtplot,date,time,duration,mnemo_fn,hcopy,auto=auto
again = ''
file_parms = { date: '', time: '', duration: '', fn_arg: '', update_int: '',$
 n_mnemos: 0, max_mnemos: 4, max_args: 5, disp_msgs: 1, hcopy: 0,$
 local_time: 0 }

input_line = replicate( { str: string('', format='(a80)') }, file_parms.max_mnemos)

if n_params(0) ge 1 then begin		; If at least 1 command line argument
  file_parms.date = date
  if n_params(0) ge 2 then begin
    file_parms.time = time
  endif
  if n_params(0) ge 3 then begin
    file_parms.duration = duration
  endif
  if n_params(0) ge 4 then begin
    file_parms.fn_arg = mnemo_fn
  endif
  if n_params(0) ge 5 then begin
    file_parms.hcopy = hcopy
    if keyword_set(auto) then file_parms.disp_msgs = 0
  endif
endif

if file_parms.disp_msgs eq 1 then begin
  print,"HKPLOT - History files are assumed to be in directory: ",$
    getenv("MDI_HISTORY_DIR")
endif

get_input, file_parms, input_line, auto=auto

dur = 8 * 3600
dur = dur2sec (file_parms.duration)
print, dur

start_time = fmt_tim (anytim2ints (!stime, off = -dur))
;stime = '11-nov-93  08:36:00'
;start_time = fmt_tim (anytim2ints (stime, off = -dur))
print, start_time
file_parms.date = strmid (start_time, 0, 9)
file_parms.time = strmid (start_time, 11, 8)
print, file_parms.date, file_parms.time
interval = 30

while again eq '' do begin
  for i = 1, file_parms.n_mnemos do begin
      cmdline = input_line(i-1).str
      cmdstr = strmid (cmdline, 0, strpos(cmdline, ' ', 0))
      case cmdstr of
          'plot':     procname = 'DO_PLOT'
          'oplot':    procname = 'DO_PLOT'
          'plotave':  procname = 'DO_PLOTAVE'
          'oplotave': procname = 'DO_PLOTAVE'
          else:       procname = 'XX'
      endcase
      if (procname ne 'XX') then $
      call_procedure, procname, file_parms,cmdline,auto=auto
  endfor

;  while (kb_inp eq '') and (
;  for i = 1, file_parms.update_int
;      get_kbrd (0)
      

  wait, file_parms.update_int

  start_time = fmt_tim (anytim2ints (!stime, off = -dur))
; start_time = fmt_tim (anytim2ints (stime, off = -dur))
  file_parms.date = strmid (start_time, 0, 9)
  file_parms.time = strmid (start_time, 11, 8)
  print, start_time
  print, file_parms.date, ' / ', file_parms.time
  
endwhile

end	;end of rtplot
