#! /bin/sh

#    Oct 16/2007 - F.Majaess

#id arc_shrd- Returns shared "_" separated subfields prefix.

#   AUTHOR  - F.Majaess

#hd PURPOSE - "arc_shrd" code is to be used to scan the supplied
#hd           list of names and returns the maximum shared prefix
#hd           of "_" (underscore) separated fields amongst them.
#hd           Note: The script is not intended to be called directly by
#hd                 the user, instead it's to be called by higher level
#hd                 scripts.
#hd                 Due to using the "_" as the fields separator, an
#hd                 expected "_" at the end of the returned string
#hd                 will not be delivered.

#pr PARAMETERS:
#pr
#pr   POSITIONAL
#pr
#pr     f1 ... fn  = list of the names to be processed.

if [ -n "$Tlist" ] ; then
 unset Tlist
fi

arg_list=$@
for arg in $arg_list
do
  case $arg in
       -*) set $arg                       ;;
      *=*) eval "$arg"                    ;;
        *) if [ -z "$Tlist" ] ; then
            Tlist="$arg"
           else
            Tlist=`clnstrng "$Tlist $arg" ' '`
           fi
  esac
done


if [ -n "$Shrd_Prfx" ] ; then
 unset Shrd_Prfx
fi
if [ -n "$Tlist" ] ; then
 # set -x
 Nf2keep=0 
 for rname in $Tlist
 do

  if [ $Nf2keep -ge 0 ] ; then
   if [ -z "$Shrd_Prfx" -a $Nf2keep -ge 0 ] ; then
 
     # Initialize "Shrd_Prfx" to the first name in the list...

     Shrd_Prfx="$rname"
     Nf2keep=`echo $Shrd_Prfx | $AWK -F '_' '{print NF}'`
 
   else
   
     # Check for matched fields in "Shrd_Prfx" vs. current name...
     i=0
     j=0
     Stop='false'
     unset nShrd_Prfx
     while [ "$i" -le "$Nf2keep" -a $Nf2keep -gt 0 -a "$Stop" != 'true' ] 
     do
      i=`expr $i + 1 `
      # set -x
      Dllri='$'"$i"
      Shrd_Prfx_field=`echo $Shrd_Prfx | $AWK -F '_' "{print $Dllri}"`
 
      rname_field=`echo $rname | $AWK -F '_' "{print $Dllri}"`
      # set +x
 
      if [ "$Shrd_Prfx_field" = "$rname_field" ] ; then
       # Matched fields are preserved with counter adjusted...
       j=$i
       if [ -z "$nShrd_Prfx" ] ; then
        nShrd_Prfx="$Shrd_Prfx_field"
       else
        nShrd_Prfx="${nShrd_Prfx}_${Shrd_Prfx_field}"
       fi
      else
       if [ "$j" -gt 0 ] ; then
        # Unmatched fields, adjust "Shrd_Prfx" and "number of fields" 
        # counter accordingly...
 
        Shrd_Prfx="$nShrd_Prfx"
        Nf2keep="$j"
       else
        # In the case where not even the first field matches...
        unset Shrd_Prfx
        Nf2keep=-1
 
       fi
       Stop='true'
      fi
     done
   fi 
  fi 
 done
 if [ -n "$Shrd_Prfx" ] ; then
  echo "$Shrd_Prfx"
 fi
fi
