load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/shea_util.ncl"

begin

  filenames = systemfunc("ls 3B42*.HDF")	; get list of the filenames
  nfiles = dimsizes(filenames)

; now extract each part of the filename and store it separately
  type      = str_get_field(filenames,1,".")
  date      = str_get_field(filenames,2,".")
  hour      = str_get_field(filenames,3,".")	
  level     = str_get_field(filenames,4,".")
  extension = str_get_field(filenames,5,".")
  
  print(hour)	; note that we now have a list of strings for hour
  
; now add some zeroes using sprinti - must convert the old string to an integer before giving it to sprinti!  
  new_hour = sprinti("%0.2i",stringtoint(hour)) 

  print(new_hour) ; note that this worked as expected - now we have the strings with zeroes so they can be sorted properly

; reconstruct the filenames with the new hour strings
  new_filenames = type + "." + date + "." + new_hour + "." + level + "." + extension

  print(new_filenames)   ; now we have a list that we can sort

  new_filenames!0 = "old_names"		; define a named dimension for the old names 
  new_filenames&old_names = filenames	; now store the original filenames as an attribute array of the new_filenames variable
  
  sqsort(new_filenames)	; now do a string sort so that the filenames are in order; the associated attribute array (old filenames) gets sorted according to the order of new_filenames
  
  print(new_filenames)	; verify that this had the desired effect with the new filenames
  print(new_filenames&old_names)   ; now you have a list of the old filenames, but in the correct order 

;  fins  = addfiles(new_filename&old_names,"r")   ; now you can open all the files together, or loop through one by one

  do ifile = 0, nfiles-1  
     print(new_filenames&old_names(ifile))
;     fin = addfiles(new_filename&old_names(ifile),"r")
; do stuff now then delete the file before opening up the next one
;     delete(fin)
  end do


end
