;
; plot.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
      return,0
    endelse
  endelse
endelse
end	; end of line_ok
;************************************************************************
; 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 = ''

done = 0
if keyword_set(auto) eq 1 then goto,do_auto
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
      file_parms.date = tmp_date
      done = 1
    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
      file_parms.date = tmp_date
    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
      file_parms.time = tmp_time
      done = 1
    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
      file_parms.time = tmp_time
    endif
    done = 1
  endelse
endrep until done

done = 0
repeat begin
  if file_parms.duration eq '' then begin
    print,FORMAT='($,"Enter duration (HH:MM:SS | HH:MM)")'
    read,tmp_duration
    if tmp_duration ne '' then begin	; if user input
      file_parms.duration = tmp_duration
      done = 1
    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
      file_parms.duration = tmp_duration
    endif
    done = 1
  endelse
endrep until done

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,else=NO)")'
  read,again
  if again eq '' then goto,skip_input
endif
print,"file_parms.n_mnemos: ",file_parms.n_mnemos
print,"input_line(0).str: ",input_line(0).str
print,"input_line(1).str: ",input_line(1).str
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,date_str,start_hrs,start_min,start_sec,path,y_value,index

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
!x.title = '!c' + string(format='("T A I   t i m e  starting  ",(A))',date_str)
units_title = hk.units
!y.title = units_title
t_str = string(format='((A),4X,(A))',hk.mnemo,hk.descr)
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)
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
  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
repeat begin
  n_tokens = 0
  start = 0
  stop = 0
  cur_len = 0
  last_len = strlen(input_line(i).str)	; init length of last token on line
  repeat begin
    stop = strpos(input_line(i).str,' ',start)
    if stop ne -1 then begin	; if found a blank
      cur_len = stop - start
      cmd(n_tokens).str = strmid(input_line(i).str,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(i).str,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
endrep until i ge file_parms.n_mnemos
;###########################################################################
; Create the file for read_hist that contains multiple mnemonics
;###########################################################################
if file_parms.n_mnemos gt 1 then begin
  tmp_fn = string(format='("plot_mnemos.",(A))',pid_str)
  plot_mnemos_pn = string(format='((A),"/",(A))',getenv("MDI_TEMP_DIR"),tmp_fn)
  openw,unit,plot_mnemos_pn,/GET_LUN
  for j=0,file_parms.n_mnemos-1 do begin
    line1 = strtrim(input_line(j).str,2); remove leading and trailing whitespace
    line2 = strcompress(line1)	; shrink whitespace to single blank
    stop = strpos(line2,' ',0)	; stop = position of blank before mnemo
    if stop ne -1 then begin		; if found a blank
      start = stop + 1		; point to mnemonic
      after_mnemo = strpos(line2,' ',start)
      if after_mnemo eq -1 then begin	; mnemonic is last token on line
        cur_len = strlen(line2) - start
      end else begin
        cur_len = after_mnemo - start
      endelse
      line3 = strmid(line2,start,cur_len)
      printf,unit,format='(a)',line3
    end else begin
      print,"Invalid input line: ", input_line(j).str
      stop
    endelse
  endfor
  close,unit
  free_lun,unit
endif

task_pn = string(format='((A),"/read_hist")',getenv("MDI_TASK_DIR"))
fn = file_parms.date + "," + file_parms.time + "-" + file_parms.duration
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' 
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)
  plot_it,hk(i),n_data_values,time_axis,file_parms.date,$
start_hrs,start_min,start_sec,path(i).str,y_value,i
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
  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
;**************************************************
; hkplot
; to use auto mode (no prompts) do a command line like:
; hkplot,'05-nov-93','00:00','12:00','frog',0,/auto
;**************************************************
pro hkplot,date,time,duration,mnemo_fn,hcopy,auto=auto
again = ''
file_parms = { date: '', time: '', duration: '', fn_arg: '',$
 n_mnemos: 0, max_mnemos: 4, max_args: 5, disp_msgs: 1, hcopy: 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
while again eq '' do begin
  do_plot,file_parms,input_line,auto=auto
  if keyword_set(auto) then begin
    again = 'n'
  end else begin
    print,FORMAT='($,"Plot again? (<CR>=YES,else=NO)")'
    read,again
  endelse
endwhile
end	;end of hkplot
