;+
;
; Project   : s3drs reconstruction software
;                   
; Name      : p_encodename
;               
; Purpose   : part of Pixon, part of the s3drs GUI
;               
; Explanation: part of the Pixon wrappers used to access and
; manipulate the various arcane Pixon structures and objects.
;               
; function to return a standardized file name for reconstruction
; runs, based on the resolution, version, and a chosen 'runname'.
; Also does versioning of earlier runs exist to avoid overwriting them.
;
; Use       : typically called from 's3drs.pro' 
;    
; Inputs    : (various)
;               
; Outputs   : (various)
;
; Keywords  : (various)
;               
; Common    : none
;               
; Restrictions: none
;               
; Side effects: none
;               
; Category    : reconstruction, pixon
;               
; Prev. Hist. : None.
;
; Written     : Sandy Antunes, NRC, March-April 2005-2009
;               
;-            
; function to return a standardized file name for reconstruction
; runs, based on the resolution, version, and a chosen 'runname'.
; Also does versioning of earlier runs exist to avoid overwriting them.
;
; Default ending is .dat.  This can be overwritten with stem=stem.
; Also, the version number can be forced with force=version.
; Using getversion=getversion will return the version number it found.
;
; sample use, here it gets a dataname then makes sure the gif has the
;             same name and version number but ends in .gif:
;   dataname = p_encodename(Ncube,runname,getversion=version)
;   gifname = p_encodename(Ncube,runname,force=version,stem='.gif')
;
; The earlier version used the current date also, but that just
; looked confusing since a single run would span multiple dates,
; so we eliminated that.

FUNCTION p_encodename,N,runname,getversion=getversion,stem=stem,force=force

  if (n_elements(stem) eq 0) then stem='.dat';
  if (n_elements(force) ne 0) then begin
      version = force
      forceflag=1;
  end else begin
      version=1                 ;
      forceflag=0;
  end

  NS=strtrim(string(N),2)

;  dateA = strsplit(systime(),/extract)
;  dateS = dateA[1] + dateA[2] + '_' + dateA[4]; dd/mmm/yyyy

  runname2=strjoin(strsplit(runname,' ',/extract),'_')

  ; find and update version numbers
  repeat begin
      versionS = string(version,format='(I03)')
;      savename = runname + '_' + NS + '_' + dateS + '_v' + versionS +
;      stem
      savename = runname2 + '_' + NS + '_v' + versionS + stem
      ++version
  endrep until (forceflag eq 1 or file_test(savename) eq 0)

  --version; in case it is returned, to keep it accurate

  getversion=version
  return,savename

END
