;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;
;  print_time.pro - in a loop, prints time remaining/elapsed to finish loop
;
;  usage:  print_time,str,it,nit,tst,slen,/elapsed
;          where str = string prepended to time left message
;                it = current iteration number (starting from 1)
;                nit = total number of iterations
;                tst = long(systime(1)) just before intering loop
;                slen = on input, contains string length of message to erase,
;                       on output, contains length of the message printed here
;                elapsed = set flag if you want time elapsed to be printed
;
;  M.DeRosa - 11 Mar 2000 - created
;             15 Mar 2000 - now prints time left in seconds if under 1
;                           minute (for the truly impatient!)
;              1 Aug 2000 - added capability for tst to be calculated
;                           upon entering routine if not already done 
;              8 Feb 2001 - added extra print statement if on final interation
;             10 Jan 2002 - changed routine to be able to print both time 
;                           remaining and time elapsed, renamed as print_time
;                           (formerly print_time_left)
;             23 Jan 2006 - now does a CR without backspacing by using the
;                           CR ASCII character with a $ format, instead of
;                           using the BS (backspace) character.  This works
;                           better in the IDLDE and doesn't TTY behavior
;
;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

pro pfss_print_time,str,it,nit,tst,slen,elapsed=elapsed

;  sets tst if not set
if ((n_elements(tst) eq 0) or (it eq 1)) then tst=long(systime(1))

;  calculate time remaining in minutes (or seconds if under 1 minute)
telapsed=double(long(systime(1))-tst)  ;  time elapsed (seconds)
if it gt 1 then begin  ;  avoids division by zero errors
  if keyword_set(elapsed) then begin
    time=telapsed
  endif else begin
    itrate=telapsed/(it-1)  ;  current iteration rate (iterations per second)
    time=(nit-it+1)*itrate  ;  time remaining (seconds)
  endelse
  if time lt 59.5 then begin
    time=round(time)
    label=' second'
  endif else begin
    time=round(time/60.)
    label=' minute'
  endelse
  timestr=strcompress(time,/r)+label
  if time ne 1 then timestr=timestr+'s'
endif else timestr='---'
if keyword_set(elapsed) then timestr='elapsed = '+timestr $
  else timestr='left = '+timestr

;  erase previous message
if n_elements(slen) gt 0 then print,string(13b),f='($,A)'

;  print time left
outstr=str+'on iteration '+strcompress(it,/r)+' of '+strcompress(nit,/r)+$
  ', time '+timestr+'     '
print,outstr,f='($,A)'

;  set slen variable
slen=strlen(outstr)

;  print if on final iteration
if it eq nit then print

end