"SS_saveAutoTripRes_ALL - archives AutoTripRes in ~/vnmrsys/data with       "
"                        a name constructed from the sample, the nucleus,   "
"                        the region and the autocalibration experiment      "
"                        all in uppercase between underscores.              "

"                        The Sample Name is entered on the first Setup page "
"                        and sets the parameter samplename.  Argument 1 is  "
"                        is the samplename, argument 2 is the nucleus,      " 
"                        argument 3 is the region and argument 4 is the     "
"                        experiment name, DP, CP, CP1 or DCP.               "                       

// Assemble the root filename as uppercase
write('line3','hithere')
$samplename_upper=''
write('line3','hithere1')
format($1,'upper'):$samplename_upper
$region_upper=''
format($3,'upper'):$region_upper
format($4,'upper'):$experiment_upper
$newAutoTripRes = $samplename_upper + '_' + $2 + '_' + $region_upper + '_' + $experiment_upper

// Check for the data directory, make one if needed

$archive_path =  userdir + '/data'
exists($archive_path,'directory'):$e
if ($e < 0.5) then 
   shell('mkdir ' + $archive_path)
endif

// Backup an existing file (up to 100 backups)

$backup_path = ''
$output_path = $archive_path + '/' +  $newAutoTripRes
exists($output_path,'directory'):$e1
if ($e1 > 0.5) then 
   $i = 0
   $j = 0
   while (($i<100) and ($j<100)) do 
      $j = $j + 1
      $i = $i + 1
      $istring=''
      format($i,1,0):$istring
      $backup_path = $output_path + '_' + $istring
      write('line3','%s',$backup_path)
      exists( $backup_path,'directory'):$e2
      if ($e2 > 0.5) then 
         if ($i = 100) then
            write('error','Too Many Backups: Abort')
            abort 
         endif
      else 
         shell('mv ' + $output_path + ' ' + $backup_path)
         write('error','Backup %s created',$istring)
         $i = 100
      endif
   endwhile
endif

// Copy AutoTripRes

$AutoTripRes = userdir +'/AutoTripRes'
cp('-r',$AutoTripRes,$output_path)

write('line3','AutoTripRes Saved as %s',$newAutoTripRes)
