#!/bin/csh -f

# Note:  $1 is the portion of the name to replace
#        $2 (optional) is what will replace $1 (Default: $2 is blank)
#        $3 (optional) is the specific file to modify
#        Wildcards (*) may be used in $1
#
# eg_1: stripdate _restart.e19860525_21z _rst
#       will replace all occurances of "_restart.e19860525_21z" with "_rst"
#
# eg_2: stripdate .e19860525_21z
#       will replace all occurances of ".e19860525_21z" with ""
# -----------------------------------------------------------------------

# Determine if $1 has a wildcard
# ------------------------------
    @ j = 0
    @ k = 1
    set bit = `echo "$1" | cut -b$k`
    while ( $bit != '' )
    set bit = `echo "$1" | cut -b$k`
    if( "$bit" == "*" ) then
         @ j = $k - 1
         @ k = $k + 1
    else
         @ k = $k + 1
    endif
    end

if( $j != 0 ) then
    set name1 = `echo "$1" | cut -b1-$j`
else
    set name1 = $1
endif

if( .$2 == . ) then
    set name2 = ""
else
    set name2 = $2
endif

if( .$3 == . ) then
    set files = `ls -1 *$name1*`
else
    set files = $3
endif
set num = $#files

if( $num != 0 ) then
    if( $j != 0 ) then
      set length0 = `echo $files[1] | awk '{print length}'`
      set length1 = `echo $name1    | awk '{print length}'`
      @ m = 1
      @ n = $length1
      set test = `echo $files[1] | cut -b${m}-${n}`
      while ( $test != $name1 )
           @ m = $m + 1
           @ n = $n + 1
      set test = `echo $files[1] | cut -b${m}-${n}`
      end
      set name1 = `echo $files[1] | cut -b${m}-${length0}`
    endif
endif
    
foreach file ($files)

if(-e filename1 ) /bin/rm filename1
if(-e filename2 ) /bin/rm filename2
echo $file                                > filename1
echo $file |  sed -e "s/$name1/$name2/g"  > filename2

/bin/mv `cat filename1 filename2`

end

if(-e filename1 ) /bin/rm filename1
if(-e filename2 ) /bin/rm filename2
exit
