;+
; MDI_plots.pro 
;
; This file contains a collection of procedures to plot
; MDI housekeeping data. The routines are listed below;
;
;  1. line_ok         Checks if command is valid
;  2. check_date      validates user input date in format: dd-mmm-yy 
;  3. check_time      validates user input time in format: hh:mm or hh:mm:ss
;  4. check_duration  validates user input duration in format: hh:mm or hh:mm:ss
;                     or with local time specifier: hh:mmL or hh:mm:ssL
;  5. get_input       Gets plot times and items.
;  6. get_hk          Read in data for an item for a specified time period.
;  7. plot_it         plots data 
;  8. plot_hc         plots data to a postscript file for hardcopy
;  9. set_plotdata    Initializes variables in plotdata common block
; 10. do_plot         Obtains requested data and sets up plot parameters
; 11. do_oplot        Sets up overplot parameters
; 12. do_average      Plots averages of specified items
;
; (RTPLOT and HKPLOT programs make use of the above routines.)
;
; The MDI HK data is read using the read_hist utility. It assumes
; that the history files are in the directory MDI_HISTORY_DIR.
;
; To access history files from 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 rtplot or hkplot.
;
; 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 = long(tmp_str)
tmp_str = strmid(time_str,3,2)
dur_min = long(tmp_str)
if strlen(time_str) gt 5 then begin
  tmp_str = strmid(time_str,6,2)        ; get optional seconds
  dur_sec = long(tmp_str)
endif else begin
  dur_sec = 0
endelse

dur = dur_hr * 3600L + dur_min * 60L + dur_sec

return, dur
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

field_size = strpos (duration_str, ':')
;print,'field_size=',field_size
tmp_str = strmid(duration_str,0,field_size)
;print,'1: ', tmp_str
num = fix(tmp_str)
if num lt 0 then return,0	; hour out of range
tmp_str = strmid(duration_str,field_size,1)
;print,'2: ', tmp_str
if tmp_str ne ':' then return,0	        ; missing 1st :
tmp_str = strmid(duration_str,field_size+1,2)
;print,'2: ', tmp_str
num = fix(tmp_str)
if num lt 0 OR num gt 59 then return,0	; minutes out of range
;print,'len of str=', strlen(duration_str)
if strlen(duration_str) gt (field_size+3) then begin
  tmp_str = strmid(duration_str,field_size+3,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,field_size+4,2)	; get optional seconds
    ;print,'3: ', tmp_str
    num = fix(tmp_str)
    if num lt 0 OR num gt 59 then return,0	; seconds out of range
    if strlen(duration_str) gt field_size+6 then begin
      tmp_str = strmid(duration_str,field_size+6,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,hk_plot,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
tmp_upd_int = ''; contains user input update interval for real-time plots
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 (hk_plot eq 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 or HH:MM )")'
    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 (hk_plot eq 0) then begin
    if (file_parms.update_int eq 0) then file_parms.update_int = 300
    print, file_parms.update_int,FORMAT='($,"Enter Update Interval in seconds (<CR>=",I4,"): ")'
    read, tmp_upd_int
    if (tmp_upd_int ne '') then file_parms.update_int = fix(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
  print,'file name=',in_fn
  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:  "
    print,"    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,"    oplot mtsqopt4  ( overplot filter oven temperature )"
    print,"    plotave 2 mtopts4 mtopts5 20 30 ( plot ave oven temp)"
    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
        printf,unit,format='(a)','end'
        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)
    print,path
    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
;
;
;
;++++++++++++++++++++++++++++++++++++++++++++++++++
; function get_hk, mnemonic, filename, time_arr, data_arr
;
; This fuction obtains the data for the item specified by mnemonic from the
; file "filename". It returns two array. A time array containing the time of
; each data point relative to the first point and a data array containing the
; data requested.
;
; The result of the function is the number of data points returned.
;--------------------------------------------------- 

function get_hk, mnemonic, filename, stime, hkstr, time_arr, data_arr

task = getenv("MDI_TASK_DIR") + '/read_hist'
spawn, [task, '-s', 'gmt', '-b', '-m', mnemonic, filename], /noshell, pid = pid_ext

pid_str = strtrim (string (format='(I)', pid_ext), 2)
;print, pid_str
 
dirname = getenv ("MDI_TEMP_DIR")
time_fn = dirname + '/time.' + pid_str
;print, time_fn
data_fn = dirname + '/' + mnemonic + '.' + pid_str 
;print, data_fn

nhk = 0l & ndata = 0l & hdroff = 0l
stime = lonarr(4)
hrs = 0l & min = 0l & sec = 0l & typ = 0l
s9 = string (replicate (32b, 10))
s5 = string (replicate (32b, 6))
s32 = string (replicate (32b, 33))
hkstr = {mnemo: s9, units: s5, descr: s32}

openr, lun, time_fn, /get_lun
readu, lun, nhk, ndata, hdroff, hrs, min, sec, typ
stime(0) = hrs
stime(1) = min
stime(2) = sec
stime(3) = typ
;print,'stime = ', stime
readu, lun, hkstr
;print, hkstr.mnemo, ' data read'
time_fn_rec = assoc (lun, lonarr(ndata), hdroff)
time_arr = time_fn_rec(0)
close, lun

openr, lun, data_fn
datarec = assoc (lun, fltarr(ndata))
data_arr = datarec(0)
close, lun

free_lun, lun

spawn, 'rm ' + time_fn
spawn, 'rm ' + data_fn

return, ndata
end
;
;
;
;**************************************************
; plot_it
;**************************************************
pro plot_it,hk,n_data_values,time_axis,data,date_str,time_str,stime,y_value,index,local_time

common plotparam, ymin1, ymax1, xtitle1, t_str1, $
                  ymin2, ymax2, xtitle2, t_str2, $
                  ymin3, ymax3, xtitle3, t_str3, $
                  ymin4, ymax4, xtitle4, t_str4


;ymin = fltarr(4)
;ymax = fltarr(4)
;xtitle = strarr(80,4)
;mtitle = strarr(80,4)


!x.margin=6
!y.margin=5
start_hrs = stime(0)
start_min = stime(1)
start_sec = stime(2)
time_type = stime(3)
;print, 'stime=', stime, '  local time=',local_time
if local_time eq 0 AND time_type eq 1 then time_lab = 'TAI' else $
if local_time eq 0 AND time_type eq 2 then time_lab = 'GMT' else $
if local_time eq 1 AND time_type eq 1 then time_lab = 'LOCAL TAI' else $
if local_time eq 1 AND time_type eq 2 then time_lab = 'LOCAL GMT' else $
time_lab = 'UNKNOWN'

dt = date_str + '  ' + time_str
;print,dt
timhrs = fix(strmid(time_str,0,2))
timmin = fix(strmid(time_str,3,2))
timsec = fix(strmid(time_str,6,2))
;print, timhrs, timmin, timsec
;print, start_hrs, start_min, start_sec

tmsec = long(timhrs)*3600L + long(timmin)*60L + long(timsec)
stsec = long(start_hrs)*3600 + long(start_min)*60 + long(start_sec)
;print, tmsec, stsec
if (stsec lt tmsec) then begin
  dt = fmt_tim(anytim2ints(dt,off=86400))
endif
date_str = strmid (dt, 0, 9)
;print, date_str

units_title = hk.units
!y.title = units_title
;t_str = string(format='((A),4X,(A))',hk.mnemo,hk.descr)
t_str = 'MDI Housekeeping Data'
x_min = min(time_axis)
x_max = max(time_axis)
y_min = min(data)
y_max = max(data)

dur_s = x_max mod 60
tmp = (x_max - dur_s) / 60
dur_m = tmp mod 60
tmp = (tmp - dur_m) / 60
dur_h = tmp mod 24
dur_d = (tmp - dur_h) / 24

if (dur_d eq 0) then begin
    !x.title = '!c' + string(format='((A)," time starting ",(A), " (Dur: ", i2.2,":",i2.2,":",i2.2, ")")',$
	time_lab,date_str, dur_h,dur_m,dur_s)
endif else begin
    !x.title = '!c' + string(format='((A)," time starting ",(A), " (Dur: ", i1,"/",i2.2,":",i2.2,":",i2.2, ")")',$
	time_lab,date_str, dur_d,dur_h,dur_m,dur_s)
endelse

n_x_ticks = 4
x_interval = x_max / (n_x_ticks-1)
xtitle = string(replicate(' ',n_x_ticks))
tmp_days = 0
tmp_hrs = start_hrs
tmp_min = start_min
tmp_sec = start_sec
for i=0,n_x_ticks-1 do begin
  if (dur_d eq 0) then begin
      xtitle(i) = string(format='((I2.2),":",(I2.2),":",(I2.2))',$
          tmp_hrs,tmp_min,tmp_sec)
  endif else begin
      xtitle(i) = string(format='((I1),"/",(I2.2),":",(I2.2),":",(I2.2))',$
          tmp_days,tmp_hrs,tmp_min,tmp_sec)
  endelse
  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
  tmp_days = tmp_days + (n_hrs / 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

case index of 
    0: begin
           ymin1 = y_low
           ymax1 = y_hi
           xtitle1 = xtitle
           t_str1 = t_str
       end
    1: begin
           ymin2 = y_low
           ymax2 = y_hi
           xtitle2 = xtitle
           t_str2 = t_str
       end
    2: begin
           ymin3 = y_low
           ymax3 = y_hi
           xtitle3 = xtitle
           t_str3 = t_str
       end
    3: begin
           ymin4 = y_low
           ymax4 = y_hi
           xtitle4 = xtitle
           t_str4 = t_str
       end
endcase
    
return
end	; end of plot_it
;
;
;
;**************************************************************************
; plot_hc
;**************************************************************************
;
pro plot_hc, win, dev=plotdev

common plotdata, tim11, data11, leg11, tim21, data21, leg21, tim31, data31, leg31, tim41, data41, leg41, $
                 tim12, data12, leg12, tim22, data22, leg22, tim32, data32, leg32, tim42, data42, leg42, $
                 tim13, data13, leg13, tim23, data23, leg23, tim33, data33, leg33, tim43, data43, leg43, $
                 tim14, data14, leg14, tim24, data24, leg24, tim34, data34, leg34, tim44, data44, leg44, $
                 nplots, wopen, n_annot_lines

common plotparam, ymin1, ymax1, xtitle1, t_str1, $
                  ymin2, ymax2, xtitle2, t_str2, $
                  ymin3, ymax3, xtitle3, t_str3, $
                  ymin4, ymax4, xtitle4, t_str4

leg = strarr(4)

pdev = 'X'
if (keyword_set(plotdev) ne 0) then begin
    pdev = strupcase(plotdev)
    if ((pdev ne 'X') and (pdev ne 'TEK')) then pdev = 'X'
endif

set_plot, 'PS'
pltfn = 'rtplot_' + string(FORMAT="(I1)", win)
device, filename=pltfn,bits_per_pixel=8,/landscape

!p.linestyle = 0

case win of 
    0: begin
           if (nplots(0) ge 0) then begin
               x_min = min (tim11)
               x_max = max (tim11)
               plot,tim11, data11, xrange =[x_min,x_max],$
                    yrange =[ymin1,ymax1], xminor=-1,xticks=3,xtickname=xtitle1,$
                    title=t_str1,charsize=.8,xstyle=1
               leg(0) = leg11
           endif
           if (nplots(0) ge 1) then begin !p.linestyle=1 & oplot, tim21, data21 & leg(1) = leg21 & endif
           if (nplots(0) ge 2) then begin !p.linestyle=2 & oplot, tim31, data31 & leg(2) = leg31 & endif
           if (nplots(0) ge 3) then begin !p.linestyle=3 & oplot, tim41, data41 & leg(3) = leg41 & endif
       end
    1: begin
           if (nplots(1) ge 0) then begin
               x_min = min (tim12)
               x_max = max (tim12)
               plot,tim12, data12, xrange =[x_min,x_max],$
                    yrange =[ymin2,ymax2],xminor=-1,xticks=3,xtickname=xtitle2,$
                    title=t_str2,charsize=.8,xstyle=1
               leg(0) = leg12
           endif
           if (nplots(1) ge 1) then begin !p.linestyle=1 & oplot, tim22, data22 & leg(1) = leg22 & endif
           if (nplots(1) ge 2) then begin !p.linestyle=2 & oplot, tim32, data32 & leg(2) = leg32 & endif
           if (nplots(1) ge 3) then begin !p.linestyle=3 & oplot, tim42, data42 & leg(3) = leg42 & endif
       end
    2: begin
           if (nplots(2) ge 0) then begin
               x_min = min (tim13)
               x_max = max (tim13)
               plot,tim13, data13, xrange =[x_min,x_max],$
                    yrange =[ymin3,ymax3],xminor=-1,xticks=3,xtickname=xtitle3,$
                    title=t_str3,charsize=.8,xstyle=1
               leg(0) = leg13
           endif
           if (nplots(2) ge 1) then begin !p.linestyle=1 & oplot, tim23, data23 & leg(1) = leg23 & endif
           if (nplots(2) ge 2) then begin !p.linestyle=2 & oplot, tim33, data33 & leg(2) = leg33 & endif
           if (nplots(2) ge 3) then begin !p.linestyle=3 & oplot, tim43, data43 & leg(3) = leg43 & endif
       end
    3: begin
           if (nplots(3) ge 0) then begin
               x_min = min (tim14)
               x_max = max (tim14)
               plot,tim14, data14, xrange =[x_min,x_max],$
                    yrange =[ymin4,ymax4],xminor=-1,xticks=3,xtickname=xtitle4,$
                    title=t_str4,charsize=.8,xstyle=1
               leg(0) = leg14
           endif
           if (nplots(3) ge 1) then begin !p.linestyle=1 & oplot, tim24, data24 & leg(1) = leg24 & endif
           if (nplots(3) ge 2) then begin !p.linestyle=2 & oplot, tim34, data34 & leg(2) = leg34 & endif
           if (nplots(3) ge 3) then begin !p.linestyle=3 & oplot, tim44, data44 & leg(3) = leg44 & endif
       end
endcase


x0 = !x.crange(0) + (!x.crange(1)-!x.crange(0))/10.0
x1 = 2.0 * x0
xl = x1 + 0.15*x0
yoff = (!y.crange(1)-!y.crange(0))/20.0
annot_line_num = 1 
for n = 0, nplots(win) do begin
    y0 = !y.crange(1)
    y1 = y0
    !p.linestyle = n
    d = convert_coord ([x0, x1], [y0, y1], /data, /to_device) 
    chsiz = !p.charsize * !d.y_ch_size + 5
    d(1,0) = d(1,0) - (annot_line_num * chsiz) 
    d(1,1) = d(1,0)
    plots, [d(0,0), d(0,1)], [d(1,0), d(1,1)],/device
    !p.linestyle = 0
    xyouts,  d(0,1)+fix((0.15)*float(d(0,0))), d(1,0), leg(n),/device
    annot_line_num = annot_line_num + n_annot_lines(win, n)
endfor

device, /close
;;spawn, 'lps20 ' + pltfn
pprint, pltfn		;MDM replaced "lps20" command with PPRINT call 25-Jul-94
set_plot, pdev 
end
;
;
;
;**************************************************************************
;Set Up Common Blocks
;**************************************************************************
pro set_plotdata
common plotdata, tim11, data11, leg11, tim21, data21, leg21, tim31, data31, leg31, tim41, data41, leg41, $
                 tim12, data12, leg12, tim22, data22, leg22, tim32, data32, leg32, tim42, data42, leg42, $
                 tim13, data13, leg13, tim23, data23, leg23, tim33, data33, leg33, tim43, data43, leg43, $
                 tim14, data14, leg14, tim24, data24, leg24, tim34, data34, leg34, tim44, data44, leg44, $
                 nplots, wopen, n_annot_lines

nplots = intarr(4)
wopen = intarr(4)
n_annot_lines = intarr(4,4)
end
;
;
;
;
;**************************************************************************
; 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,dev=plotdev,smooth=smooth_width

common plotdata, tim11, data11, leg11, tim21, data21, leg21, tim31, data31, leg31, tim41, data41, leg41, $
                 tim12, data12, leg12, tim22, data22, leg22, tim32, data32, leg32, tim42, data42, leg42, $
                 tim13, data13, leg13, tim23, data23, leg23, tim33, data33, leg33, tim43, data43, leg43, $
                 tim14, data14, leg14, tim24, data24, leg24, tim34, data34, leg34, tim44, data44, leg44, $
                 nplots, wopen, n_annot_lines


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 = ''

pdev = 'X'
if (keyword_set(plotdev) ne 0) then begin
    pdev = strupcase(plotdev)
    if ((pdev ne 'X') and (pdev ne 'TEK')) then pdev = 'X'
endif


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_buf)
n_hk_vals = 1

if (keyword_set(smooth_width) ne 0) then begin
    s_width = smooth_width
    if (s_width eq 1) then s_width = n_data_values/100
    data_arr = smooth(data_buf,s_width)
endif else begin
    data_arr = data_buf
endelse

;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,pdev 
;print, 'file_parms.plotwin=',  file_parms.plotwin

if (cmd(0).str eq 'oplot') then begin

  nplots(file_parms.plotwin) = nplots(file_parms.plotwin) + 1
  !p.linestyle = nplots(file_parms.plotwin)

; case file_parms.plotwin of
;     0: begin nplots1 = nplots1 + 1 & !p.linestyle = nplots1 & end
;     1: begin nplots2 = nplots2 + 1 & !p.linestyle = nplots2 & end
;     2: begin nplots3 = nplots3 + 1 & !p.linestyle = nplots3 & end
;     3: begin nplots4 = nplots4 + 1 & !p.linestyle = nplots4 & end
; endcase

  oplot, time_axis, data_arr

endif else begin

;print, '1:file_parms.plotwin=',  file_parms.plotwin

; case file_parms.plotwin of
;     0: nplots1 = 0
;     1: nplots2 = 0
;     2: nplots3 = 0
;     3: nplots4 = 0
; endcase

  i = file_parms.plotwin
  nplots(i) = 0
  n_annot_lines(i) = 0

  if !D.NAME eq 'X' then begin
    if (wopen(i) eq 0) then begin
        window,i,retain=2,xpos=xwp(i),ypos=ywp(i)
        wopen(i) = 1
    endif else begin
        wset, i
    endelse
  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)
  !p.linestyle = 0
  !fancy = 1
  plot_it,hk,n_data_values,time_axis,data_arr,file_parms.date,file_parms.time,$
          stime,y_value,i,file_parms.local_time
endelse

pltwin = file_parms.plotwin
;n = !p.linestyle
n = 0
if (nplots(pltwin) gt 0) then begin 
    for i = 0, nplots(pltwin)-1 do begin 
        n = n + n_annot_lines(pltwin,i)
    endfor 
endif

;n = nplots(pltwin)
x0 = !x.crange(0) + (!x.crange(1)-!x.crange(0))/10.0
y0 = !y.crange(1)
x1 = 2.0 * x0
y1 = y0
annotx = [x0, x1]
annoty = [y0, y1]
d = convert_coord ([x0, x1], [y0, y1], /data, /to_device) 
chsiz = !p.charsize * !d.y_ch_size + 5
d(1,0) = d(1,0) - ((n+1) * chsiz) 
d(1,1) = d(1,0)
plots, [d(0,0), d(0,1)], [d(1,0), d(1,1)],/device
!p.linestyle = 0
descr = strcompress(hk.descr) + ' (' + hk.mnemo + ')'
xyouts,  d(0,1)+fix((0.15)*float(d(0,0))), d(1,0), descr,/device
n_annot_lines(pltwin,nplots(pltwin)) = 1

case file_parms.plotwin of
    0: case nplots(0) of
           0: begin tim11 = time_axis & data11 = data_arr & leg11 = descr & end
           1: begin tim21 = time_axis & data21 = data_arr & leg21 = descr & end
           2: begin tim31 = time_axis & data31 = data_arr & leg31 = descr & end
           3: begin tim41 = time_axis & data41 = data_arr & leg41 = descr & end
        endcase
    1: case nplots(1) of
           0: begin tim12 = time_axis & data12 = data_arr & leg12 = descr & end
           1: begin tim22 = time_axis & data22 = data_arr & leg22 = descr & end
           2: begin tim32 = time_axis & data32 = data_arr & leg32 = descr & end
           3: begin tim42 = time_axis & data42 = data_arr & leg42 = descr & end
       endcase 
    2: case nplots(2) of
           0: begin tim13 = time_axis & data13 = data_arr & leg13 = descr & end
           1: begin tim23 = time_axis & data23 = data_arr & leg23 = descr & end
           2: begin tim33 = time_axis & data33 = data_arr & leg33 = descr & end
           3: begin tim43 = time_axis & data43 = data_arr & leg43 = descr & end
       endcase 
    3: case nplots(3) of
           0: begin tim14 = time_axis & data14 = data_arr & leg14 = descr & end
           1: begin tim24 = time_axis & data24 = data_arr & leg24 = descr & end
           2: begin tim34 = time_axis & data34 = data_arr & leg34 = descr & end
           3: begin tim44 = time_axis & data44 = data_arr & leg44 = descr & end
       endcase 
endcase
  
if (file_parms.numplots lt file_parms.plotwin) then $
    file_parms.numplots = file_parms.plotwin
file_parms.plotwin = (file_parms.plotwin + 1) mod 4

end	; end of do_plot
;
;
;
;
;**************************************************************************
; do_OPLOT
; Calls do_PLOT to overlay a plot
;**************************************************************************
pro do_OPLOT, file_parms, cmd_line, auto=auto, dev=plotdev, smooth=smooth_width

;print, 'Oplot called...'
file_parms.plotwin = file_parms.plotwin - 1
if (file_parms.plotwin lt 0) then file_parms.plotwin = 3

;print, 'plotwin = ', file_parms.plotwin

do_plot, file_parms, cmd_line, auto=auto, dev=plotdev, smooth=smooth_width
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, dev=plotdev, smooth=smooth_width

common plotdata, tim11, data11, leg11, tim21, data21, leg21, tim31, data31, leg31, tim41, data41, leg41, $
                 tim12, data12, leg12, tim22, data22, leg22, tim32, data32, leg32, tim42, data42, leg42, $
                 tim13, data13, leg13, tim23, data23, leg23, tim33, data33, leg33, tim43, data43, leg43, $
                 tim14, data14, leg14, tim24, data24, leg24, tim34, data34, leg34, tim44, data44, leg44, $
                 nplots, wopen, n_annot_lines

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

pdev = 'X'
if (keyword_set(plotdev) ne 0) then begin
    pdev = strupcase(plotdev)
    if ((pdev ne 'X') and (pdev ne 'TEK')) then pdev = 'X'
endif

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

pltwin = file_parms.plotwin
;==> Now get data for each parameter identified by a mnemonic
n_annot_lines(pltwin,0) = 1
legend = 'Average of'
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
    descr = strcompress(hk.descr)
    legend = legend + '!C' + descr + ' (' + hk.mnemo + ')'
    n_annot_lines(pltwin,0) = n_annot_lines(pltwin,0) + 1
endfor

;==> Calculate average
data = data / n_mnems

if (keyword_set(smooth_width) ne 0) then begin
    s_width = smooth_width
    if (s_width eq 1) then s_width = n_data_values/100
    data = smooth(data,s_width)
endif
n_hk_vals = 1

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

set_plot,pdev 
i = file_parms.plotwin

if !D.NAME eq 'X' then begin
    if (wopen(i) eq 0) then begin
        window,i,retain=2,xpos=xwp(i),ypos=ywp(i)
        wopen(i) = 1
    endif else begin
        wset, i
    endelse
endif
t_mnemo = strtrim(hk.mnemo,2)

;path(i).str = string(format='((A),"/",(A),".",(A))',$
;			getenv("MDI_TEMP_DIR"),t_mnemo,pid_str)
!p.linestyle = 0
y_value.y_scale = y_scale
hk.mnemo = 'Average'
!fancy = 1
plot_it,hk,n_data_values,time_axis,data,file_parms.date,file_parms.time,$
        stime,y_value,i,file_parms.local_time

;print, 'plotave: file_parms.plotwin = ', file_parms.plotwin

;n = !p.linestyle
;x0 = !x.crange(0) + (!x.crange(1)-!x.crange(0))/10.0
;y0 = !y.crange(1) - (((!y.crange(1)-!y.crange(0))/20.0) * (n+1))
;x1 = 2.0 * x0
;y1 = y0
;print, x0, y0, x1, y1
;plots, [x0, x1], [y0, y1]
;!p.linestyle = 0
;xyouts,  x1+(0.15)*x0, y0, legend

nplots(pltwin) = 0
;n = !p.linestyle
;n = n_annot_lines(pltwin,0)
n = 0
x0 = !x.crange(0) + (!x.crange(1)-!x.crange(0))/10.0
y0 = !y.crange(1)
x1 = 2.0 * x0
y1 = y0
annotx = [x0, x1]
annoty = [y0, y1]
d = convert_coord ([x0, x1], [y0, y1], /data, /to_device) 
chsiz = !p.charsize * !d.y_ch_size
d(1,0) = d(1,0) - chsiz 
d(1,1) = d(1,0)
plots, [d(0,0), d(0,1)], [d(1,0), d(1,1)],/device
!p.linestyle = 0
descr = strcompress(hk.descr) + ' (' + hk.mnemo + ')'
xyouts,  d(0,1)+fix((0.15)*float(d(0,0))), d(1,0), legend,/device

case file_parms.plotwin of
    0: begin tim11 = time_axis & data11 = data & leg11 = legend & end
    1: begin tim12 = time_axis & data12 = data & leg12 = legend & end
    2: begin tim13 = time_axis & data13 = data & leg13 = legend & end
    3: begin tim14 = time_axis & data14 = data & leg14 = legend & end
endcase

if (file_parms.numplots lt file_parms.plotwin) then $
    file_parms.numplots = file_parms.plotwin
file_parms.plotwin = (file_parms.plotwin + 1) mod 4

;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
;****************************************************************
