#!/bin/ksh 
#
#	@(#)filtr 1.08 99/01/13 SMI
#	Copyright (c) 1998 by Sun Microsystems, Inc.
#
###################################################################
#                                                                 #
# Name : FILTr (LBF Testr)                                        #
#                                                                 #
# Goal:   check loop with lbf.  if it doesn't work, bypass        #
#         something  and test again                               #
#                                                                 #
#                                                                 #
# version    : 0.1   working with only one box on a loop          #
#              0.2   clean up per group's suggestions             #
#              0.3   make multiple boxes work per loop            #
#              0.4   changes per pre-beta                         #
#              0.5   fix missing file problem                     #
#              0.6   enable backplane when no failure found       #
#              0.7   exit if no failing pattern is found          #
#              0.8   fix log output, add $bindir where omitted    #
#              0.9   add -q for quickr test, add test for box, fixes #
#              0.10  use logger to write to /var/adm/messages     #
#              0.11  fix minimum config issues                    #
#              0.12  fix check of bypass/enable success           #
#              0.13  wasn't checking io-unit (only sbus) with path#
#              0.14  bug fixes (0.13 didn't fix all sun4d probs)  #
#			fix for  4175892 4175554 4175392-like     #
#              0.15  added initial manual mode                    #
#                       lighten restrictive fix for 4175892       #
#              0.16  check for offline before starting lbf/luxdiag# 
#              0.17  add aol suggestion #2                        #
#              0.18  4181835                                      #
#              0.19  plbf becomes lbf for now                     # 
#              0.20  4183057                                      #
#              0.21  fix to 4183057 fix (typo)                    #
#              0.22  lbf becomes plbf                             #
#              0.23  11 slot support; err if boxname not on loop  #
#                    added -v (verbose flag) remove -e,-b,-q      #
#                    added -r (recover from ^C flag)              #
#              0.24  Dates and log directories                    #
#              0.25  added -f (file input)                        #
#                    added ".cN" to filtlog extention             #
#                    moved warning up front; removed dated logdir #
#              0.26  added -m (manual mode), 4187663 fix          #
#              0.27  mods to initial run option                   #
#                    mods to menu                                 #
#              1.00  Take out the work "Beta"                     #
#              1.00  text changes by Joy                          #
#              1.01  Bug fixes to 4195793 & 4195801               #
#                                 4197020                         #
#              1.02  Bug fixes to 4197013                         #
#                                 4198043 number not correct      #
#                                 4198045 bad backplane was gbic  #
#                                 4198115 bad touch operation     #
#                    fix to test for bad drive in min config slot #
#                                 4198078 fixes for entering      #
#                                                manual mode      #
#              1.03  Further Bug fixes to 4198045                 #
#                    prop up capturing error output               #
#              1.04  Further Bug fixes to 4201561                 #
#              1.05  Bug fix to 4202573                           #
#	       1.06  Added in binary search for failing drives    #
#		     Mike Shapiro 2/22/99			  #
#	       1.07  Replaced dash seperators in names with ':'   # 
#                                                                 #
#                                                                 #
###################################################################
#
########## USER VARIABLE PARAMETERS ##############
PTH=

SES=

VERBOSE=
#VERBOSE="on"

BINDIR=/var/opt/STORtools/bin

LOGDIR=/var/opt/STORtools/logs

FLOGDIR=$LOGDIR/filtr

VERSION=1.08

PROGNAME="$0"

RETEST="TRUE";

NBT=

PTR=

SIZ=

Q=

INPATFILE=			# user defined pattern file

MANUALMODE=			# do manual mode

FORCEMAN=			# not forcing into manual mode


############### New 1.6 variables #######################

INJECTINPUT="off";  # prompt user for P(ASS) or F(AIL) or take CR and do lbf command 
#INJECTINPUT="on"; 

DEXPID=""

USEPAT="off"

DRIVE_FAILURE=

MULTIPLE_BOX_FAILURE=

BINARY_BACKPLANE_FAILURE=

DEXIO=;

DEXPID=

BACKPLANES=

DEXDEVS=

BPBYPASSED=

ENTRY=

globPTime=

T300=no

SEDR=no

T300FAIL=no

A5K=		



unalias awk
unalias cat
unalias grep
unalias mkdir
unalias more
unalias uniq
unalias rm
unalias sed
unalias sort
unalias touch
unalias ls
unalias whoami
unalias sleep
unalias luxadm


PTH=		# path under test
CONTINUESTART=	# continue at start (avoid answering yes at beginning
DIDTHEVXTHNG=	# asked and performed the Veritas turnoff
RECOVER=	# Did a ^C in a previous run, so use the recovered 
		# patterns file to avoid PHASE I running again
NEEDINFILE=	# need an input file (file that contains user specifed 
		#		failing patterns)
DOPHASEI=	# do full PHASE I

let "phaseim = 1"	# multiplier (it's 2 if already found patterns are used)
let "maxnpats = 5"	# maxnpats is the number of patterns to find 
USAGE=ON

trap "Name_file; contc; Clean_exit" 1 2 15



USER=`/usr/bin/id`
USER=`$BINDIR/perl -e '$ARGV[0] =~ /(root)/; print $&;' $USER`;
USER=`$BINDIR/perl -e '$ARGV[0] =~ /(root)/; print $&;' $USER`;
if [[ "$USER" != "root" ]]
	then 
	echo "        $PROGNAME requires root access!"
	exit
fi

######### FUNCTIONS ##############


# get perl time in seconds

function getPTime {



	globPTime=`$BINDIR/perl -e '$time = time; print $time'`;

}


function printPTime {


	TIME=`$BINDIR/perl -e '$time = time; $time1 = $time - $ARGV[0]; $time1 = $time1/60; @a = split(/\./, $time1); print "$a[0]";' $globPTime`;

	echo "Time elapsed in minutes: $TIME";


}



function dexIo 
{

	if [[ "$DEXIO" = "on" ]] ; then
		return 0;
	else 
		return 1;
	fi

}

function sedr_log 
{

	if [[ "$SEDR" = "on" ]] ; then
		return 0;
	else 
		return 1;
	fi

}

function t3 
{

	if [[ "$T300" = "on" ]] ; then
		return 0;
	else 
		return 1;
	fi

}

function a5k 
{

	if [[ "$A5K" = "on" ]] ; then
		return 0;
	else 
		return 1;
	fi

}

function usePat 
{


	if [[ "$USEPAT" = "on" ]] ; then
		echo "WARNING:  using revcoverpat.debug.  Not for production."
		return 0;
	else 
		return 1;
	fi

}



function injectInput 
{

	if [[ "$INJECTINPUT" = "on" ]] ; then
		return 0;
	else 
		return 1;
	fi


}


function bypassAll {


	 for SES in `/bin/cat $SESFILE`
	 do

	    Set_Vars
	    echo "bypassing $BOXNAME $BPASC backplane"
	    if [[ ! -z $BOX2TST ]]; then
		if [[ "$BOXNAME" = "$BOX2TST" ]] ; then
			Bypass_BackPlane $SES
		fi
	    else
		Bypass_BackPlane $SES
	    fi
	 done

}


function Check_4_Offline
{
	ONPORT=`/usr/sbin/luxadm -e port | /usr/bin/grep "$PTH" | /usr/bin/grep -v "NOT CONNECTED" 2> /dev/null`

	if [[ -z $ONPORT ]]; then	# if ONPORT is null string
	    echo " "
	    echo " Path $PTH is OFFLINE. " 
	    echo " "
	    let "numtimes = 0"
	    while [[ -z $ONPORT ]] ;	# while ONPORT is a null string
	    do
		/usr/bin/sleep 5;
		let "numtimes = numtimes + 1"
	        ONPORT=`/usr/sbin/luxadm -e port | /usr/bin/grep "$PTH" | /usr/bin/grep -v "NOT CONNECTED" 2> /dev/null`
		if [[ -z $ONPORT ]]; then
		    echo " "
		    echo " Path $PTH is still OFFLINE.  Sleep 5 seconds" 
		    echo " "
		    if (( numtimes > 12 )); then
		      echo " "
		      echo " *** ERROR! ***   The port should NOT be offline."
		      echo " "
		      echo " "
		      ans=""
		      echo " OFFLINE for over a minute. "
	    	      echo " Do you want to run a manual test to further isolate the "
	    	      echo " possible failure?\c"
	    	      read ans?" [y, <n>]: "
	    	      if [[ "$ans" = "y" && "$ans" != "Y" && "$ans" != "yes" && "$ans" != "YES" ]] ; then
	    		MANMDQ="DONE"
			FORCEMAN="YES"
	    		Do_ManualMode
	    		Clean_exit
	    	      fi

		      ans=""
	    	      read ans?" Do you want to quit filtr? [y, <n>]: "
	    	      if [[ "$ans" = "y" || "$ans" = "Y" || "$ans" = "yes" || "$ans" = "YES" ]] ; then
			echo " "
			echo " IF drives and back planes have been bypassed, "
			echo " -->YOU<-- are responsible for unbypassing them. "

			if [[ -a $ENAFILE ]]; then	# if enable file exists
			  echo " "
			  echo " Refer to the log file ($LOGFILE) on how to enable "
			  echo " backplanes and drives on a loop."
			  echo " "
			  echo " Use these instructions to enable backplanes and drives onto a loop:"
			  echo " "
			  /bin/touch $ENAFILE
			  /usr/bin/sort $ENAFILE | /bin/uniq > $OFILE
			  /bin/cat $OFILE
			  /bin/cat $OFILE >> $LOGFILE
			  echo " "
			  echo " These instructions are appended to the $LOGFILE log file "
			  echo " "
			else
			  echo " "
			  echo " It doesn't appear that anything is bypassed, but just in case, "
			  echo " here's an example for backplane unbypassing: "
			  echo "	/usr/sbin/luxadm -e enable -F -b -r bbox "
			  echo " This enables the B loop of bbox's rear backplane. "
			  echo " "
			  echo " Here's another example:"
			  echo "	/usr/sbin/luxadm -e enable -F -a -f bbox "
			  echo " This enables the A loop of bbox's front backplane. "
			  echo " "
			  echo " Here's an example for unbypassing a drive in a box named bbox:"
			  echo "	/usr/sbin/luxadm -e enable -b bbox,f3 "
			  echo " This enables the B loop of the front drive in the third slot. "
			  echo " "
			  echo " Do a \"/usr/sbin/luxadm disp boxname \" on all the boxes of path: $PTH "
			  echo " to make certain that that all drives and backplanes are online."
			  echo " "
			fi
			echo " "
			Clean_exit
		      else	
			echo " "
			echo " Will check for another minute. "
			let "numtimes = 0"
		      fi
		    fi
		else
		    echo " "
		    echo " Loop back ONLINE.  Continue testing."
		    echo " "

		    
		fi
	    done
	fi
}


function running_contc
{
	echo " "
	# echo " Another Control C trap captured! "
	# echo " Already running Control C capture routine... "
	echo " Please wait.  filtr is putting things back as it found them."
	echo " "
}

function contc_enable
{

	if [[ "$ENTRY" = "" ]] ; then
		SOMEBODYHITCONTC=TRUE	
	fi

# simply remove this message for now
	if ( ! t3 ) ; then
		echo " Going to check your system and "
		echo "      find bypassed devices/backplanes and enable them..."
		echo " This may to take a few minutes."
		echo " "
	fi
	killDex;		  # If it's there kill dex process

	enableAllDrivesBps
	/usr/sbin/luxadm -e forcelip $PTH  # do this for good
						   # measure.

}


function enableAllDrivesBps {

	if ( t3 ) ; then
		return;
	fi

	if [[ "$BPBYPASSED" = "" ]] ; then
		echo " No backplanes to enable"
	else
		for bp in $BPBYPASSED
		do
			getSideLupBoxname $bp  # just like Set_Vars
			echo "enabling $BOXNAME $BPASC backplane";
			Enable_BackPlane;
	
		done
	fi

	if [[ "$BYPASSED" = "" ]] ; then
		echo " No drives to enable"
	else
	
		for DEV in $BYPASSED
		do		
			echo enabling $DEV;
			Enable_Drive $DEV
		done
	fi 
	
	BACKPLANES="ENABLED"; 

}

###################################################################
#                                                                 #
#  Function: contc (control c function)
#                                                                 #
###################################################################

function contc
{
	trap "running_contc" 1 2 15	# set trap so this routine isn't re-run
	echo " "
	echo " "
	if [[ -a $PATFILE ]]; then
	    echo " Save pattern file in $RCVPAT "
	    echo $PTH > $RCVPAT
	    /bin/cat $PATFILE >> $RCVPAT
	fi
	contc_enable
	# kill background pid's if they are there
	if [[ ! -z $LPID ]] ; then
	    kill -9 $LPID > $OFILE 2> $OFILE
			# if any bg_luxadm jobs are running, kill 'em
	fi
	if [[ ! -z $FPID ]] ; then
	    kill -9 $FPID > $OFILE 2> $OFILE	
			# if any lbf jobs are running, kill 'em
	fi
	Display_Results
	trap "contc" 1 2 15	# leave this routine with this trap hdlr enabled
}


#
# manual mode ^C capture routine
#
function contc_man
{
	trap "running_contc" 1 2 15	# set trap so this routine isn't re-run
	if [[ -a $PATFILE ]]; then
	    echo " Save pattern file in $RCVPAT "
	    echo $PTH > $RCVPAT
	    /bin/cat $PATFILE >> $RCVPAT
	fi
	## echo "Control C trap captured"
	echo " "
	echo " ********************************************************** "
	echo " "
	echo " Make certain that ALL GBICs are reinserted properly before "
	echo " leaving this script!!! "
	echo " "
	echo " ********************************************************** "
	echo " "
	ans="n"
	while [[ "$ans" != "y" ]] ; 
	do
	    read ans?" Ready to continue? [y, <n>]: "
	    if [[ "$ans" = "y" && "$ans" = "Y" && "$ans" = "yes" && "$ans" = "YES" ]] ; then
		ans="y"
	    fi
	done
	echo " "
	contc_enable	# call enable routine to enable any bypassed things.
	trap "contc_man" 1 2 15	# exit with this routine enabled for traps
}



#
#	execute a luxadm command in the 'background' so 
#	a ^C can stop it from running
#
#	INPUT: LUXLINE is the luxadm command that is executing
#	OUTPUT: LUXOUT is the results of the luxadm command
#

function bg_luxadm
{
        LPID=

	CONTC=
	$LUXLINE > /tmp/zout.$$ 2> /tmp/eout.$$ &
	LPID=$!

	while [[ -z $CONTC ]] ;
	do
		echo ".\c"
		CJOB=`jobs -l | /usr/bin/grep $LPID`
		if [[ ! -z $CJOB ]] ; then
		    /usr/bin/sleep 2;
		else
		    CONTC="END"
		fi
	done

	LUXOUT=`/bin/cat /tmp/zout.$$`
	/usr/bin/rm /tmp/zout.$$  > $OFILE 2> $OFILE
	/usr/bin/rm /tmp/eout.$$  > $OFILE 2> $OFILE
	CONTC=
LPID=
}









###################################################################
#                                                                 #
#  Function: Test_lbf                                             #
#                                                                 #
#   This function perform plbf in background for all channel      #
#   enabled. This function set the flag according to the result   #
#   of the test and take care also, of the logfiles               #
#   The logfiles are on format compatible to Excel                #
#                                                                 #
#   INPUTS                                                        #
#     NBT    Number of test passes                                #
#     Q      Bytes or Kilobytes                                   #
#     SIZ    Size of the packet                                   #
#     PTH    Soc port (PATH) Under test                           #
#     CH_EN  Set when the test on the channel is enabled          #
#                                                                 #
#   OUTPUTS                                                       #
#     CPASS  Test status for each Channel                         #
#     CGST   Global Test status for each channel                  # 
#               Set at Fail when one or more test fail            #
###################################################################

function Test_all_lbf
{
    Check_4_Offline
    FPID=



    if [ "$VERBOSE" = "on" ]; then
	echo $NAME "("$PTR")" $SIZ$Q "\t\c" 
				# Display Name of the test
    fi

	PP2PROC=

	if [[ "$NEWNBT" != "TRUE" ]] ; then
		let "nbt = $NBT *  phaseim"
	else
		nbt=$NBT;
	fi

	if ( dexIo ) ; then
		startDex;
	fi
	echo "lbf testing all patterns (iterations = $nbt)"; 

        $BINDIR/lbf -n $nbt -$Q $SIZ -a -i $PTH > $OFILE 2> /dev/null &
	FPID=$!		# Get process ID

	# launch test in background on the host specified

	
	let "cont = 1";	

	while (( cont == 1 )) ; do
		echo ".\c"
		sleep 4;
		ps -p $FPID > /dev/null;
		if (( $? == 1 )) ; then
			let "cont = 0";
		fi
		
	done
	
	if ( dexIo ) ; then
	    killDex;
	fi

        integer FIELD;
	FIELD=1 ;
	FAIL="";

	/bin/cat $OFILE;

	for LINE in `/bin/cat $OFILE`
	do
	   if ((FIELD == 1)) ; then
	   
	      # this has pass or fail
	      FAIL=`echo $LINE | grep "FAIL" `
	   fi

	   if [[ "$FAIL" != "" ]]; then
	     if ((FIELD == 2)); then
	        #extract failing pattern
		PATTERN=`echo $LINE | /usr/bin/awk ' {x= split($1,STATUS,"x")
		                  print STATUS[2] }'`



	      fi

	      if (( FIELD == 3 )); then
	         # extract loop cnt
		 TPASS=`echo $LINE| /usr/bin/awk ' {x=split($1,STATUS,"=")
		   print STATUS[2] }' `


		echo " "
	        if [ "$VERBOSE" = "on" ]; then
	 	     echo "				\c"
	        fi
	        echo "  FOUND failing pattern $PATTERN"
	        echo "  FOUND failing pattern $PATTERN" >> $LOGFILE
	        FOUND=YES
	        if [[ ! -z $TPASS ]] ; then
	            echo "$PATTERN $TPASS" >> $PATNNUM
	        else
	          echo "$PATTERN 0" >> $PATNNUM
	        fi
	        echo $PATTERN >> $PATFILE
	        let "numpats = numpats + 1"



	      fi
	   fi

	   FIELD=$FIELD+1

	   if ((FIELD == 5)); then
	     FIELD=1;
	     FAIL=""
	   fi
	done
	# This section take care of the log files

    if [ "$VERBOSE" = "on" ]; then

	STR=`echo $TPASS"/"$NBT `

	if [ "$STR" != "" ]; then
		echo $STR "\t\c"
		STR=""			# clean string
	fi
	## if [[ "$CPASS" = "FAIL" ]] ; then
	##    echo " "
	##    /bin/cat $OFILE
	## fi
 
    fi
    echo "\nlbf status: $CPASS"

}

###################################################################
#                                                                 #
#  Function: Test_lbf                                             #
#                                                                 #
#   This function perform plbf in background for all channel      #
#   enabled. This function set the flag according to the result   #
#   of the test and take care also, of the logfiles               #
#   The logfiles are on format compatible to Excel                #
#                                                                 #
#   INPUTS                                                        #
#     NBT    Number of test passes                                #
#     Q      Bytes or Kilobytes                                   #
#     SIZ    Size of the packet                                   #
#     PTR    Pattern to send                                      # 
#     PTH    Soc port (PATH) Under test                           #
#     CH_EN  Set when the test on the channel is enabled          #
#                                                                 #
#   OUTPUTS                                                       #
#     CPASS  Test status for each Channel                         #
#     CGST   Global Test status for each channel                  # 
#               Set at Fail when one or more test fail            #
###################################################################

function Test_lbf
{
    Check_4_Offline
    FPID=



    if [ "$VERBOSE" = "on" ]; then
	echo $NAME "("$PTR")" $SIZ$Q "\t\c" 
				# Display Name of the test
    fi

	PP2PROC=

	if [[ "$NEWNBT" != "TRUE" ]] ; then
		let "nbt = $NBT *  phaseim"
	else
		nbt=$NBT;
	fi

	if ( dexIo ) ; then
		startDex;
	fi

	echo "lbf -n $nbt -$Q $SIZ -t $PTR $PTH ";

        $BINDIR/lbf -n $nbt -$Q $SIZ -t $PTR $PTH > $OFILE 2> /dev/null &
	FPID=$!		# Get process ID

			# launch test in background on the host specified

	
	let "cont = 1";	

	while (( cont == 1 )) ; do
		echo ".\c"
		sleep 4;
		ps -p $FPID > /dev/null;
		if (( $? == 1 )) ; then
			let "cont = 0";
		fi
		
	done
	
	if ( dexIo ) ; then
	    killDex;
	fi

	echo "";
	# display results
        /bin/cat $OFILE ;

	# Extract number of passes from result file
	TPASS=`/bin/cat $OFILE |  /usr/bin/awk '	
		/PASS/ { x= split($3,STATUS,"=")   # Remove dot point on answer 
		print STATUS[2] }'`		# Return answer

	if [ "$TPASS" = "" ]; then	# did it fail?
		CPASS=FAIL
		# Extract number of passes from result file
		TPASS=`/bin/cat $OFILE |  /usr/bin/awk '	
		/FAIL/ { x= split($3,STATUS,"=")   # Remove dot point on answer 
		print STATUS[2] }'`		# Return answer


		let "a = 0"
		let "b = 0"
		for c in $TPASS
		do
		    let "a = c + a"
		    let "b = b + 1"
		done
		if (( b > 1 )) ; then
		    let "a = a - c"
		    let "b = b - 1"
		    let "TPASS = a / b"
		fi
	else
		CPASS=PASS
	fi

	# This section take care of the log files

    if [ "$VERBOSE" = "on" ]; then

	STR=`echo $TPASS"/"$NBT `

	if [ "$STR" != "" ]; then
		echo $STR "\t\c"
		STR=""			# clean string
	fi
	## if [[ "$CPASS" = "FAIL" ]] ; then
	##    echo " "
	##    /bin/cat $OFILE
	## fi
 
    fi
    echo "\nlbf status: $CPASS"

}

##############################################################################
#
#	Test_lbf_patterns
#
#	for each pattern in $PATFILE
#		call Test_lbf until it doesn't pass
#
#	out: CPASS = whether it passed or not.
#
##############################################################################
function Test_lbf_patterns
{




	LBFSKIP=
	SOFT=
	ORIGNBT=$NBT

	for PTR in `/bin/cat $PATFILE`
	do
	    let "in = $NBT"
	    PATNNEL=`/usr/bin/grep $PTR $PATNNUM`
	    JUSTNUM="`echo "$PATNNEL" | /usr/bin/sed s/$PTR//`"
	    T=`echo $JUSTNUM | /usr/bin/grep " "`

		  # use a little perl to filtr out unwanted chars from number.
		  # BUGID 4198043
	    T=`$BINDIR/perl -e ' $ARGV[0] =~ /\d+/; print $& ' $T`;


	
	    if [[ ! -z $T ]] ; then
	       let "JUSTNUM = 0"
	    fi
	    if [[ -z $JUSTNUM ]] ; then
		let "numin = 0"
	    else
		let "numin = $JUSTNUM"
	    fi
	    let "in = in + numin"
	    NBT=$in


	    #NBT=$GLOBAL_NBT;
	    Test_lbf

	    if [[ "$CPASS" != "PASS"  ]]; then

		if [[ "$RETEST" != "TRUE" ]] ; then
			return;
		fi

		echo " "
		echo "Failed lbf with pattern=$PTR, starting retest."
		echo "Failed lbf with pattern=$PTR, starting retest." >> $LOGFILE
		let "lbfnumerrs = 0"
		CPASS=
		Test_lbf
		if [[ "$VERBOSE" = "on" ]] ; then
		    echo " "
		fi
		if [[ "$CPASS" != "PASS" ]]; then
		    let "lbfnumerrs = lbfnumerrs + 1"
		fi
		CPASS=
		Test_lbf
		if [[ "$VERBOSE" = "on" ]] ; then
		    echo " "
		fi
		if [[ "$CPASS" != "PASS" ]]; then
		    let "lbfnumerrs = lbfnumerrs + 1"
		fi
		if (( lbfnumerrs > 0 )); then
		    CPASS=FAIL
		    LBFSKIP=YES
		    return
		else
		    echo " "
		    echo "\nAttention: two passes of retest successful.\n"
		    echo "Two passes of retest successful." >> $LOGFILE
		    CPASS=PASS
		    SOFT=YES
		fi
	    fi

	    if [[ "$VERBOSE" = "on" ]]; then
		echo " "
	    else
	 	echo ".\c"
	    fi
	    NBT=$ORIGNBT
	done
}

##########################################################
#	Enable_BackPlane
#
#	input:	BOXNAME = box i.e. dbox or c
#		LUP = a/b
#		SIDE = r/f
#
##########################################################

function Enable_BackPlane
{


	echo $BPENABLEDLIST | fgrep "$SIDE:$LUP:$BOXNAME:$SES"
	if [[ "$?" = "0" ]] ; then
		return
	fi


	bpEnableLuxadm $1
	return;

}



##############################################################
#
#	bpEnableLuxadm: using luxadm from release X
#
#	input:	BOXNAME = box i.e. dbox or c
#		LUP = a/b
#		SIDE = r/f
#
##############################################################


function bpEnableLuxadm {


	#put a sleep in here to give time for lup to stabilize after
	# lbf 

	sleep 3;
	echo "luxadm -e enable -F -$LUP -$SIDE $BOXNAME";
	/usr/sbin/luxadm -e enable -F -$LUP -$SIDE $BOXNAME;
       	


	if [[ "$?" != "0" ]] ; then 
		let "tries = 0";
		sleep 10;
		echo "error enable backplane  $LUP -$SIDE $BOXNAME  using luxadm retrying...."	
		while (( tries < 5 )) ; do 
			sleep 3;
			/usr/sbin/luxadm -e enable -F -$LUP -$SIDE $BOXNAME;
			if [[ "$?" = "0" ]] ; then
				echo "retry success....."
				break
				
			else 
				let "tries = tries + 1";
				echo "retrying...."
			fi
		done
		if ((  tries == 5  ))  ; then 
			echo "FATAL: error enable backplane using luxadm"	
			Clean_exit;		
			
		fi


	fi
	#sleep to let loop init 
       sleep 10;

	markBpEnabled "$SIDE:$LUP:$BOXNAME:$SES"

}

##############################################################
#
#	bpBypassLuxadm: using new luxadm from release X
#
#       backplane bypass function
#
#	input:	BOXNAME = box i.e. dbox or c
#		LUP = a/b
#		SIDE = r/f
#
##############################################################


function bpBypassLuxadm {


	echo "luxadm -e bypass -F -$LUP -$SIDE $BOXNAME ";
	/usr/sbin/luxadm -e bypass -F -$LUP -$SIDE $BOXNAME 2> /dev/null
	

	if [[ "$?" != "0" ]] ; then 
		echo "error bypassing backplane $LUP $SIDE $BOXNAME using luxadm retrying...."	
		# must sleep for a few seconds to let loop calm down
        	sleep 10;
		let "tries = 0";
		while (( tries < 5 )) ; do 
			sleep 3;
			/usr/sbin/luxadm -e bypass -F -$LUP -$SIDE $BOXNAME;
			if [[ "$?" = "0" ]] ; then
				echo "retry success..."	
				break
				
			else 
				let "tries = tries + 1";
				echo "retrying...";
			fi
		done
		if ((  tries == 4  ))  ; then 
			echo "FATAL: error bypassing backplane using luxadm"	
			Clean_exit;		
			
		fi


	fi
	# must sleep for a few seconds to let loop calm down
        sleep 10;



	echo "usr/sbin/luxadm -e enable -$SIDE$LUP $BOXNAME ; /usr/bin/sleep 3" >> $ENAFILE


        markBpBypassed "$SIDE:$LUP:$BOXNAME:$SES"



}


##############################################################
#
#	Bypass_BackPlane
#
#	input:	BOXNAME = box i.e. dbox or c
#		LUP = a/b
#		SIDE = r/f
#
##############################################################

function Bypass_BackPlane
{



	echo $BPBYPASSED | fgrep "$SIDE:$LUP:$BOXNAME:$SES"

	if [[ "$?" = "0" ]] ; then
		return
	fi

	
	bpBypassLuxadm $1
	
	return
	
		
}

#########################################################3
#
#	bypassDriveLuxadm	
#
#	input:	DEV = device i.e. dbox,r0 or c,f2
#		LUP = a/b
#
#########################################################3

function bypassDriveLuxadm
{


   Check_4_Offline

   echo "luxadm -e bypass -F -$LUP $DEV" ; 

   echo "/usr/sbin/luxadm -e bypass -F -$LUP $DEV" >> $LOGFILE 

   /usr/sbin/luxadm -e bypass -F -$LUP $DEV 2>/dev/null
   

   if [[ "$?" != "0" ]] ; then
   	let "tries = 0";
   	echo "error bypassing drive $DEV using luxadm retrying...."	
	#must sleep for a few seconds to allow loop time to resync.
        sleep 10;


   	while (( tries < 5 )) ; do 
   		/usr/sbin/luxadm -e bypass -F -$LUP $DEV;
   		sleep 3;
   		if [[ "$?" = "0" ]] ; then
   			echo "retry success...."
   			break
   			
   		else 
   			let "tries = tries + 1";
   			echo "retrying..."
   		fi
   	done
   	if ((  tries == 4  ))  ; then 
   		echo "FATAL: error bypasssing drive using luxadm"	
   		Clean_exit;		
   		
   	fi

   fi
   #must sleep for a few seconds to allow loop time to resync.
   sleep 10;



   markDriveBypassed $DEV



}


#########################################################3
#
#	enableDriveLuxadm	
#
#	input:	DEV = device i.e. dbox,r0 or c,f2
#		LUP = a/b
#
#########################################################3

function enableDriveLuxadm
{


   Check_4_Offline

   echo "/usr/sbin/luxadm -e enable -F -$LUP $DEV" >> $LOGFILE 

    echo "luxadm -e enable -F -$LUP $DEV ";
   /usr/sbin/luxadm -e enable -F -$LUP $DEV 2> /dev/null
   
   if [[ "$?" != "0" ]] ; then
   	let "tries = 0";
	#must sleep a few seconds to allow loop to come online
        sleep 10;


   	echo "\nerror enabling  drive $DEV using luxadm retrying...."	
   	while (( tries < 5 )) ; do 
   		sleep 3;
   		/usr/sbin/luxadm -e enable -F -$LUP $DEV;
   		if [[ "$?" = "0" ]] ; then
   			echo "enable drive succeded"
   			break
   			
   		else 
   			let "tries = tries + 1";
   			echo "retrying enable drive..."
   		fi
   	done
   	if ((  tries == 5  ))  ; then 
   		echo "FATAL: error enabling drive using luxadm"	
		echo "command: luxadm -e enable -F -$LUP $DEV "
   		Clean_exit;		
   		
   	fi
   	sleep 3;

	echo "luxadm -e enable -F -$LUP $DEV"

   	/usr/sbin/luxadm -e enable -F -$LUP $DEV

	

   	if [[ "$?" != "0" ]] ; then

   		echo "FATAL:  enableDriveLuxadm failed command was: "
   		echo "/usr/sbin/luxadm -e enable -F -$LUP $DEV";

   	fi
	#must sleep for a few seconds to allow loop to come online
	sleep 10;

   fi
   #must sleep a few seconds to allow loop to come online
   sleep 10;

  
   markDriveEnabled $DEV



}





#########################################################3
#
#	Enable_Drive
#
#	input:	DEV = device i.e. dbox,r0 or c,f2
#		LUP = a/b
#
#########################################################3

function Enable_Drive
{

   echo $ENABLEDLIST | fgrep "$DEV "
   if [[ "$?" = "0" ]] ; then
   	return;
   fi


    enableDriveLuxadm
    return;



}



#####################################################
#
#	Bypass_Drive
#
#	input:	DEV = device i.e. dbox,r0 or c,f2
#		LUP = a/b
#
####################################################

function Bypass_Drive
{

   echo $BYPASSED | fgrep "$DEV "
   if [[ "$?" = "0" ]] ; then
     #This device is already bypassed
     return
   fi

   # Check for a minimum drive configuration
   min_flag="NO";

   # get this drives boxname 
   # use perl to split apart the name.
   # note that you must must drive name in as an argument into the perl script
   # so that perl will see the variable as argv[0].
   DRIVE_BOXNAME=`perl -e '@str=split(/,/, $ARGV[0]); print $DEV;print @str[0],"\n"; ' $DEV`

   echo $DEV | fgrep ",f" >/dev/null;
   if [[ "$?" = "0" ]] ; then

      # We are attempting to bypass a drive on front backplane
      integer my_count;
      my_count=0;
      for drive_var in $ENABLEDLIST
      do
         echo $drive_var | fgrep "$DRIVE_BOXNAME,f">/dev/null;
         if [[ "$?" = "0" ]] ; then
            my_count=$my_count+1;
         fi

      done	
     
      # my count has the number of drives currently enabled
      # on this backplane.
      # Check to see that my count isn't less than minimum
      # allowed plus one so that if we disable this 
      
      if ((my_count <3 )) then
         # if we bypass this drive there will be less than
         # the minimum required drives installed
         min_flag="YES";
      fi



   fi # end of working on front backplane
   echo $DEV | fgrep ",r" >/dev/null;
   if [[ "$?" = "0" ]] ; then
      # We are attempting to bypass a drive on rear backplane
      integer my_count;
      my_count=0;
      for drive_var in $ENABLEDLIST
      do
         echo $drive_var | fgrep "$DRIVE_BOXNAME,r" >/dev/null;
         if [[ "$?" = "0" ]] ; then
            my_count=$my_count+1;
         fi

      done	
      if ((my_count <4 )) then
         # if we bypass this drive there will be less than
         # the minimum required drives installed
         min_flag="YES";
      fi

   fi # end of working on rear backplane


   if [[ "$min_flag" == "YES" ]] ; then 
      # print out warning indicating that
      # if they bypass this drive, they will be going
      # below the minimum configuration
      echo "";
      echo "By passing $DEV, you will be going below the required number"
      echo "of enabled drives on a backplane. Errors may be encountered due"
      echo "to this condition and not because of a bad drive." 
      read ans?"Are you sure you want to disable $DEV? [y, <n>]: "
       if [[ "$ans" != "y" ]] ; then
   	echo "Not bypassing $DEV";
   	return;
       fi

   fi






   # add the undo command to enable file
   echo "/usr/sbin/luxadm -e enable -$LUP $DEV ; /usr/bin/sleep 2" >> $ENAFILE

   bypassDriveLuxadm;
   return;

}


function Manual_return
{
	echo " "
	echo " "
	echo "Please put all the GBICs back where they were originally."
	echo " "
	ans=""
	while [[ "$ans" != "" ]];
	do
	    read ans?" Ready to continue? [<y>]: "
	    echo " "
	    if [[ "$ans" = "y" || "$ans" = "Y" || "$ans" = "yes" || "$ans" = "YES" || "$ans" = "" ]] ; then
		ans="y"
	    fi
	done
	echo " "
	
	contc_enable	# enable everything that has been bypassed
	BACKPLANES="ENABLED";
	/usr/bin/rm $ENAFILE > $OFILE 2> $OFILE
	MANUAL="DONE"
	trap "contc; Clean_exit" 1 2 15
	## Clean_exit
}


function Test_success
{
	if [[ "$CPASS" != "PASS" ]]; then
	    echo " "
	    echo " ***** Failed lbf ***** "
	    echo " "
	    if ( t3 ) ; then
		T300FAIL=yes;
	    fi
	else
	    if ( t3 ) ; then
		T300FAIL=no;
	    fi
	    echo " "
	    echo " Succeeded!  "
	    echo " "
	fi
}

function  filtr_lbf_short_text {

cat <<eof  >$SUGGESTN


FRU Isolation has detected failures with multiple backplanes. 
Problem cause is not backplane or disk related or there may be 
multiple problems.

Manual intervention is required to isolate.

Hit ENTER to proceed with Manual Mode FRU Isolation:




1). Remove cable from the host adapter (HA), attach loopback cable on 
    GBIC. Test.  PASS - goto step 2.
    FAIL - replace GBIC. Test. PASS - goto step 5.
       FAIL - replace HA and retest.

2). If Hub is being used: Remove Hub side GBICs to arrays. Test.
    PASS - goto step 3.
    FAIL - replace Hub side GBIC to HA.  Test. PASS - goto step 5.
       FAIL - replace cable. Test. PASS - goto step 5.
           FAIL - replace cable. Test. PASS - goto step 5.
              FAIL - replace Hub and retest.

3). For each GBIC on the Hub leading to an array do the following:
      Reinsert Hub-side GBIC into Hub.
      Remove Cable to array; Attach loopback cable on GBIC. Test.
      PASS - goto step 5.
      FAIL - replace GBIC and retest.

4). For Hub or Non-Hub: for each array, do the following:
      Connect array to loop.  Test. PASS - continue to next array.
      FAIL -  replace array GBIC. Test. PASS - continue. 
         FAIL - replace array Cable.  Test. PASS - continue.
            FAIL - replace IB and retest.

5). Reconnect and enable all hardware elements. Test. PASS - exit.
    FAIL - goto step 1.

When the loop and arrays are passing the basic Loop Integrity Test, it 
is recommended that you further verify the loop integrity using the Disk 
Read Loop Test as some failures can only be produced under heavy load.  
Reference the User Guide for more information.

eof


}


function filtr_t3_text {


cat <<eof  >$SUGGESTN

The following is a suggested procedure for Manual Testing using the 
Loop Integrity Test (LIT) or sedr. Reference the STORtools User Guide and the
T300 documentation for more information on troubleshooting.

1). Attached loopback cable to Host Adapter GBIC. Test.  
    PASS - goto step 2. 
    FAIL - replace the GBIC. Test.
       PASS -  goto step 6.
       FAIL - replace Host Adapter. Test.
          PASS - goto step 6.
          FAIL - possible bad replacement part, Loop back cable or I/O card.

2) If a hub is used remove all array hub GBICs. Test. 
   PASS (or hub not used) - goto step 3.
   FAIL - replace hub GBIC. Test.
      PASS - goto step 6.
      FAIL - replace cable. Test.
         PASS - goto step 6.
         FAIL - replace hub. Test. 
            PASS - goto step 6.
            FAIL -  possible bad replacement part or host adapter GBIC.

3). For a single array proceed to step 4, else locate problem array by
    connecting one array to the loop at a time and retesting. When test
    fails on an array proceed with step 4 for that array. If multiple 
    arrays fail, repeat step 4 for each array.

4). If a hub is used attached a loop back cable to the array hub GBIC. Test.
    PASS (or hub not used) - goto step 5.
    FAIL -  replace GBIC. Test.
       PASS - goto step 6.
       FAIL - possible bad hub port or other GBIC.

5). Reconnect array to the loop. Test. 
    PASS - goto step 6.
    FAIL -  replace cable. Test.
       PASS -  goto step 6.
       FAIL - replace MIA. Test. 
          PASS - goto step 6.
          FAIL - replace controller(follow service manual instructions). Test. 
             PASS - goto step 6.
             FAIL - possible bad replacement part or other GBIC. 

6). Reconnect all hardware. Test.
    FAIL - goto step 1 
    PASS - exit. 

When the loop and arrays are passing the basic Loop Integrity Test, it 
is recommended that you further verify the loop integrity using the Disk 
Read Loop Test as some failures can only be produced under heavy load. See 
the User Guide for more information.

eof

}

function filtr_lbf_text {



cat <<eof > $SUGGESTN

The following is a suggested procedure for Manual Testing using the 
Loop Integrity Test (LIT) or sedr. Reference the STORtools User Guide for more
information on loop troubleshooting.

1). Attach loopback cable to Host Adapter GBIC. Test. PASS - goto step 2.     
    FAIL - replace the GBIC. Test. PASS -  goto step 8.
       FAIL - replace Host Adapter. Test. PASS - goto step 8.
          FAIL - possible bad replacement part, Loop back cable or I/O card.

2) If a hub is used remove all array GBICs. Test. 
   PASS (or hub not used) - goto step 3.
   FAIL - replace hub GBIC. Test. PASS - goto step 8.
      FAIL - replace cable. Test. PASS - goto step 8.
         FAIL - replace hub. Test. PASS - goto step 8. 
            FAIL -  possible bad replacement part or host adapter GBIC.

3). For a single array proceed to step 4, else locate problem array by
    connecting one array to the loop at a time and retesting. When test
    fails on an array proceed with step 4 for that array. If multiple 
    arrays fail, repeat step 4 for each array.

4). If a hub is used attach a loop back cable to the array hub GBIC. Test.
    PASS (or hub not used) - goto step 5.
    FAIL -  replace GBIC. Test. PASS - goto step 8.       
       FAIL - possible bad hub port or other GBIC.

5). Reconnect array to the loop. Bypass both backplanes. Test. 
    PASS - goto step 6.
    FAIL -  replace array GBIC. Test. PASS -  goto step 8.
       FAIL - replace array IB. Test. PASS - goto step 8.
          FAIL - replace cable. Test. PASS - goto step 8. 
             FAIL - possible bad replacement part or other GBIC. 

6). Enable the front backplane. Test. PASS - goto step 7.    
    FAIL - for each disk on the backplane do the following:
       Bypass disk. Test. FAIL - enable disk, continue to next disk.
       PASS -  enable disk, replace disk. Test. PASS -  goto step 8.
          FAIL - possible bad backplane, replacement disk, IB or GBIC.

      If test fails for all or multiple disks, replace backplane. Test.
      PASS - go to step 8,
      FAIL - possible bad IB, GBIC or Interconnect Assembly.

7). Enable the rear backplane. Test. 
    FAIL - repeat the following for each disk on the backplane:
      Bypass disk. Test. FAIL - enable disk, continue to next disk.
      PASS - enable disk, replace disk. Test.  PASS - goto step 8.
         FAIL - possible bad backplane, replacement disk, IB or GBIC.

      If test fails for all disks, replace backplane. Test.
      PASS - goto step 8.
      FAIL - possible bad IB, GBIC or Interconnect Assembly.

    If problem can only be reproduced when both backplanes are
    enabled. Enable both backplanes but enable only the minimum disk
    configuration (14 slot min config is f3, f6, r0, r3, r6. 22 slot
    min config is f0, f5, f10, r0, r3, r6, r10). Test.
    PASS - enable each disk until test fails then replace failing disk. 
    FAIL - possible problem cause is one of the min config disks, or any 
           other loop hardware (backplanes, IB, GBICs, Interconnect Assembly).

8). Reconnect and enable all hardware. Test.
    FAIL - goto step 1 
    PASS - exit. 

When the loop and arrays are passing the basic Loop Integrity Test, it 
is recommended that you further verify the loop integrity using the Disk 
Read Loop Test as some failures can only be produced under heavy load. 
Reference the User Guide for more information.

eof

}






function filtr_load_short_text {


cat <<eof > $SUGGESTN

FRU Isolation has detected failures on multiple backplanes. Problem cause
is not backplane or disk related or there may be multiple problems.

Manual intervention is required to isolate.

Hit ENTER to proceed with Manual Mode FRU Isolation:



1). When all array backplanes fail independently the problem cause is most
    likely in a GBIC, host adapter, cable or hub (if used). Leave one array
    connected and replace the following hardware until the test passes.
       Host adapter to hub(if used) GBICs.
       Hub(if used) to array GBICs.
       Hub and or Cable/s.
       Array IB.
       Host adapter. 

   Test PASS - goto step 2.
   Test FAIL - possible bad replacement parts, or array failure. Repeat
               step 2 with alternate array.

2). Reconnect and enable all hardware elements. Test. PASS - exit.
    FAIL - goto step 1.

eof


}



function filtr_load_text {


cat <<eof > $SUGGESTN




The following is a suggested procedure for Manual Testing using the 
Disk Read Loop Test (DRLT). Reference the STORtools User Guide for 
more information on loop troubleshooting.

Multiple Array Configuration
----------------------------
1). For a single array proceed to step 3, else locate problem array by
    connecting one array to the loop at a time and retesting. When test
    fails on an array proceed with step 3 for that array. If multiple 
    arrays fail, repeat step 3 for each array. 

   If all arrays fail goto step 2.

2). When all arrays fail independently the problem cause is probably
    in a GBIC, host adapter, cable or hub (if used). Leave one array
    connected and replace the following hardware until the test passes.
       Host adapter to hub(if used) GBICs.
       Hub(if used) to array GBICs.
       Hub and or Cable/s.
       Array IB.
       Host adapter. 

   Test PASS - goto step 7.
   Test FAIL - possible bad replacement parts, or array failure. Repeat
               step 2 with alternate array.

Single Array Configuration
--------------------------
3). Bypass the front backplane. Test.  PASS goto step 4.
    FAIL - enable front backplane, bypass rear backplane. Test. 
       PASS - goto step 6.
       FAIL - both backplanes failing indicates possible problem
              cause is not in the backplanes and disks, goto step 5.

4). Enable the front backplane and disable the rear backplane. Test.
    PASS - goto step 5.
    FAIL - goto step 6.
  
5). When both backplanes either pass or fail independently the problem 
    cause may not be in the backplanes and disks or there may be multiple
    problems. 

    For a single array configuration replace the following hardware until the 
    test passes.
       Host Adapter GBIC. 
       Array GBIC.
       Cable. 
       Array IB. 
       Host adapter.
       Array Interconnect Assembly.

    For a multiple array configuration replace the following until the
    test passes (note that the host adapter/GBIC and hub/GBIC have
    already been tested).
        Array to hub GBICs.
        Cable.
        Array IB.
        Hub (could be a bad port on the hub).
        Array Interconnect Assembly.

    If test continues to fail there may be multiple problems in
    the backplanes and or disks. Try testing with only the minimum 
    configuration of disks enabled (14 slot min config is f3, f6, 
    r0, r3, r6. 22 slot min config is f0, f5, f10, r0, r3, r6, r10).
    If test continues to fail possible problem cause is one of the 
    min config disks, or any other loop hardware (backplanes, IB, GBICs,  
    Interconnect Assembly).

6). When the Test passes with one backplane bypassed, that backplane
    contains the problem. To further diagnose enable the suspect
    backplane and do the following for each disk:
      Bypass disk. Test. FAIL - enable disk, continue to next disk.
      PASS - enable disk and replace. Test. PASS - goto step 7.
         FAIL - possible bad backplane, replacement disk, IB or GBIC.

      If test fails for all disks, replace backplane. Test. 
      PASS - goto step 7.
      FAIL - possible bad IB, GBIC or Interconnect Assembly.

7). Reconnect and enable all hardware elements. Test. PASS - exit.
    FAIL - goto step 1.




eof

}


function echo_suggestion
{
	echo " "
	/usr/bin/more $SUGGESTN 
}





function Get_Which_BP
{
		
	echo 
	TEST1=
	BPSEL=
	TEST1=

	
	/usr/bin/rm $FOO > $OFILE 2> $OFILE
	let "index = 1"
	echo " "
	echo "Pick one or more of the following backplanes(space seperated):"
	for SES in `/bin/cat $SESFILE`
	do
	    Set_Vars

	    if [[ "$BPASC" = "rear" ]] ; then 
		BSD="Rear BP of"
	    else
		BSD="Front BP of"
	    fi
	    BNAME="$SIDE:$LUP:$BOXNAME:$SES"; 

	    echo $BPENABLEDLIST | fgrep $BNAME > /dev/null;
	    if [[ "$?" = "0" ]] ; then
	    	echo " [$index] $BSD $BOXNAME enabled"
	    else
	    	echo " [$index] $BSD $BOXNAME disabled"
	    fi
	
	
	    echo "$index $SES" >> $FOO
	    let "index = index + 1"
	done
	let "index = index - 1"
	echo " "
	read ans?" Which Backplanes(you may choose more than one - seperate by spaces[1 - $index]: "
	if [[ "$ans" = "" ]] ; then
	    echo " "
	    SES=
	    DEV=
	    return
	fi
	TEST1=`$BINDIR/perl -e  '$i=$ARGV[0]; \
			$i =~ tr/ //s; \
			@a = split(/ /,$i); \
			$error = 0; \
			foreach $num (@a) { \
				if ( $num <= 0 || $num > $ARGV[1] || !( $num =~ /\d+/)) { \
					printf("Error:  $num is not a valid input."); \
					exit;  \
				} else { \
					$line .= "$num ";  \
				}\
			}\
			if (!$error) {print "line = $line";}\
		 ' "$ans" $index`
	echo $TEST1 | fgrep "Error:";
	if [[ "$?" != "1"  ]] ; then
	    echo " "
	    echo " "
	    SES=
	    DEV=
	    return
	fi

	BACKPLN=
	for dev in $TEST1
	do
		SES=`/bin/cat $FOO | /usr/bin/grep "$dev .dev.es.ses" | /usr/bin/awk '{print $2}'`
		BACKPLN="$BACKPLN $SES"
	done	

	#echo BACKPLN = $BACKPLN
}






function Get_Which_Drive
{
	TEST1=
	let "index = 1"
	/usr/bin/rm $FOO > $OFILE 2> $OFILE

	for DEV in `/bin/cat $DEVSONLY`
	do

	    echo "$ENABLEDLIST " | fgrep "$DEV " > /dev/null
	    if [[ "$?" = "0" ]] ; then
		print "$index \t$DEV \tenabled" >>$FOO
	    else
		print "$index \t$DEV \tbypassed" >>$FOO
	    fi
	    let "index = index + 1"
	done
	let "index = index - 1" # adjust
	echo " "
	echo "Pick one or more of the following drives(space seperated):"
	/usr/bin/more $FOO
	echo " "
	read ans?" Which Drive [1 - $index]: "
	if [[ "$ans" = "" ]] ; then
	    echo " "
	    SES=
	    DEV=
	    return
	fi

	TEST1=`$BINDIR/perl -e  '$i=$ARGV[0]; \
			$i =~ tr/ //s; \
			@a = split(/ /,$i); \
			$error = 0; \
			foreach $num (@a) { \
				if ( $num <= 0 || $num > $ARGV[1] || !( $num =~ /\d+/)) { \
					printf("Error:  $num is not a valid input."); \
					exit;  \
				} else { \
					$line .= "$num ";  \
				}\
			}\
			if (!$error) {print "$line";}\
		 ' "$ans" $index`
	echo $TEST1 | fgrep "Error:";

	if [[ "$?" != "1"  ]] ; then
	    echo " "
	    echo " "
	    SES=
	    DEV=
	    return
	fi


	DRIVE=
	for dev in $TEST1
	do
		what=` $BINDIR/perl -e ' open(FOO, $ARGV[1]);while (<FOO>) { \
			@a = split(/ /, $_); \
			if ($a[0] == $ARGV[0]) { \
				printf("$a[1]"); \
				exit;
			}\
		} ' $dev $FOO`
			
		DRIVE="$DRIVE $what"
	done


	# echo "$BOXNAME $BPASC $LUP $SIDE"
}





function Get_Element_Type
{
ALLBPELM=
	echo " [1] Backplanes "
	echo " [2] Drives "
	if [[ ! -z $RQENABLE ]]; then
	    echo " [3] All Bypassed Devices "
	    echo " "
	    read ans?" Which type [1, 2, 3]: "
	else
	    echo " "
	    read ans?" Which type [1, 2]: "
	fi
	case $ans in
	1) Get_Which_BP;;	# Backplane Type
	2) Get_Which_Drive;;	# Drive Type
	3) ALLBPELM="yes";;	# enable all bypassed elems
	esac
}



function Man_Bypass
{

BACKPLN=
DRIVE=
RQENABLE=

	echo "Bypass either"
	Get_Element_Type
	if [[ ! -z $BACKPLN ]] ; then
	    for SES in $BACKPLN
	    do
		Set_Vars;
	    	echo "Going to Bypass $BPASC Backplane of $BOXNAME"
	    	Bypass_BackPlane
	    done
	    echo "Done"
	fi
	if [[ ! -z $DRIVE ]] ; then
	    for DEV in $DRIVE
	    do
	    	echo "Going to Bypass drive at $DEV"
	    	Bypass_Drive $DEV
	    done
	    echo "Done"
	fi
}


function Man_Enable
{
BACKPLN=
DRIVE=
RQENABLE="on"

	echo "Enable either"
	Get_Element_Type

	if [[ ! -z $BACKPLN ]] ; then
	    for SES in $BACKPLN
	    do
		Set_Vars;
	    	echo "Going to Enable $BPASC Backplane of $BOXNAME"
	    	Enable_BackPlane
	    done
	    echo "Done"
	fi

	if [[ ! -z $DRIVE ]] ; then
	    for DEV in $DRIVE
	    do
	    	echo "Going to Enable drive at $DEV"
	    	Enable_Drive $DEV
	    done
	    echo "Done"
	fi

	if [[ ! -z $ALLBPELM ]] ; then

	    enableAllDrivesBps

	    #contc_enable		# Just like ^C, enable everything

	    /usr/bin/rm $ENAFILE > $OFILE 2> $OFILE
	    echo "Done"
	fi

RQENABLE=
}


function Do_man_lbf_test
{
	echo " "
	echo " Running lbf test with following patterns:"
	/bin/cat $PATFILE
	echo " "
	NBT=4096 ; Q=k ; SIZ=64 ; NAME="Manual lbf test"
	Test_lbf_patterns 
	Test_success
	echo " "
}


function Toggle_dex {


	if ( dexIo ) ; then
		echo "setting Dex/IO off";
		DEXIO="off";
	else
		echo "setting Dex/IO on";
		DEXIO="on";
	fi
		

}

function Do_man_lip
{
	echo " LIP is a Fibre Channel Primitive that when executed will force " 
	echo " all nodes on the loop to go through a initialization protocol."
	echo " LIPs are harmless to a loop and are the equivalent to a bus reset."
	ans=
	while [[ "$ans" != "y" ]] 
	do
	    echo " "
	    read ans?" Do you wish to continue? [<y>, n]: "
	    if [[ "$ans" = "n" ]]; then
		return
	    fi
	    if [[ "$ans" = "" ]]; then
		ans="y"
	    fi
	done

	echo " "
	/usr/sbin/luxadm -e forcelip  $PTH
	/usr/bin/sleep 5;
	echo "completed"
}


function Manual_Test
{
	date;
	if [ ! -z $globPTime ] ; then
		printPTime;
	fi
	trap "contc_man" 1 2 15
	ans=" "
	if [[ -z $MANUALMODE ]] ; then
	if [[ -z $MANMDQ ]] ; then
	  echo " "
	  echo " Want to run a manual test to further isolate the "
	  echo " possible failure?\c"
	  read ans?" [y, <n>]: "
	  if [[ "$ans" != "y" && "$ans" != "Y" && "$ans" != "yes" && "$ans" != "YES" ]] ; then
	    trap "contc; Clean_exit" 1 2 15
	    return
	  fi
	fi  #  -z $MANMDQ

	fi # if $MANUALMODE

	if [[ -z $ENTRY ]] ; then

# Not coming from command line directly to this.  Something has failed and 
# we go kicked down here.  Give them the short version of the instructions

	    if ( t3 ) ; then
		filtr_t3_text;
	    else

		    if ( ! dexIo ) ; then
		    	filtr_lbf_text
		    else
		    	filtr_load_text 
		    fi
	    fi
	else

	# Coming from command line.  Need the Full Monty here. ( Long version of the instructions )

	    if ( t3 ) ; then
		filtr_t3_text;
	    else 
	    	if ( ! dexIo ) ; then 
	    		filtr_lbf_short_text
	    	else
			filtr_load_short_text
	    	fi
	    fi

	fi
	## echo "*********** Manual Test ***********"
	echo_suggestion
	HUB=
	TEST=0
	ans=



 

	
	SAVEDEX=$DEXIO
	while [[ "$TEST" != "q" ]] 
	do
	    trap "contc_man" 1 2 15	   # just in case the ha test script altered it somehow
	    echo " "
	    echo " Path under test = $PTH "
	    echo " "

	    if ( t3 ) ; then

			let "t3cont = 1"
			while (( t3cont )) ; do
 
				echo "1) Test with failing patterns"             
				echo "2) Display Manual Test procedure"
				echo "3) Force LIP on loop  "
				echo "q) Exit"
	
	
		   	 	read ans?" Enter choice [1, 2, 3, q]: "
			    	case $ans in
				    	1)	Do_man_lbf_test; TEST=1 ;;
				    	2)      echo_suggestion; TEST=2 ;;
				    	3)  Do_man_lip; TEST=3 ;;
				        q)  let "t3cont = 0";;
				        "") let "t3cont = 1";;
				        a-zA-Z08) let "t3cont = 1";;
			        esac
			done
			trap "contc; Clean_exit" 1 2 15
			Manual_return
			return

	    fi
					     


	    if ( !  dexIo )	;then	
		    echo "1) Test with failing patterns              4) Bypass Element(s)   "
	     else 
		    echo "1) Test with failing patterns with dex     4) Bypass Element(s)   "
	    fi 

	    echo "2) Display Manual Test procedure           5) Enable Element(s)"
	    if ( dexIo ) ; then
		DX="Toggle Dex/IO to off.";
	    else
		DX="Toggle Dex/IO to on.";
	    fi
	    echo "3) Force LIP on loop                       6) $DX" 
	
	    echo "q) Exit" 

	    read ans?" Enter choice [1, 2, 3, 4, 5, 6  q]: "

	    echo " "
	    case $ans in
	    1)	Do_man_lbf_test; TEST=1 ;;
	    2)  echo_suggestion; TEST=2 ;;
	    3)  Do_man_lip; TEST=3 ;;
	    4)  Man_Bypass; TEST=4 ;;
	    5)  Man_Enable; TEST=5 ;;
	    6)  Toggle_dex; TEST=6 ;;
	    q)  TEST=q ;;
	    "") TEST=0 ;;
	    a-zA-Z08) TEST=0 ;;
	    esac

	done


	DEXIO=$SAVEDEX
	Manual_return

	trap "contc; Clean_exit" 1 2 15

}


function Display_OutofBoxMsg
{
	echo " **** Problem is in either the IB(s) "
	echo " ****         or GBIC in the IB"
	echo " ****         or fibre cable to the IB"
	echo " ****         or GBIC leading to the IB in the HUB (if any)"
	echo " ****         or the HUB (if any)"
	echo " ****         or GBIC leading to host the HUB (if any)"
	echo " ****         or fibre cable to the host "
	echo " ****         or GBIC in the host's Host Adapter"
	echo " ****         or in Host Adapter."
}


##############################################################################
#
#	Test_Single_Bp_Nodrive		Test single Backplane no drives
#
# Enable one BP at a time.  Test that BP. 
#	If that BP fails, bypass it again, 
#
##############################################################################

function Test_Single_Bp_Nodrive
{

	# ******  ENABLE BACKPLANE  


	getSideLupBoxname $1
	Enable_BackPlane $1


	echo " "
	echo "  Start test with $BPASC backplane in enclosure \"$BOXNAME\" enabled."
	echo "  Start test with $BPASC backplane in enclosure \"$BOXNAME\" enabled." >> $LOGFILE



	NBT=4096 ; Q=k ; SIZ=64 
	NAME="$BPASC BP enabled on $BOXNAME loop $LOOP"

	# RUN LBF ON ENABLED BACKPLANE

        echo "\nStarting LBF patterns on Single Backplane: "
        Test_lbf_patterns


	if [[ "$CPASS" != "PASS" ]]; then

	    #   BACKPLANE TEST FAILED 

	    echo " "
	    echo " ***** Test with $BPASC backplane in enclosure \"$BOXNAME\" FAILS!"
	    echo "	 ($LOOP LOOP) " 
	    echo " ***** Test with $BPASC backplane in enclosure \"$BOXNAME\" FAILS! " >> $LOGFILE

	    echo "	 ($LOOP LOOP) " >> $LOGFILE


	    echo "$BOXNAME,$BPRF" >> $LOGFILE

	    echo " $BPASC backplane in enclosure \"$BOXNAME\" FAILS! " >> $BP_ERRORS



	else

	    #   BACKPLANE TEST PASSED 

	    echo " "




	      echo " Test with $BPASC backplane in enclosure \"$BOXNAME\" PASSES"
	      echo " Test with $BPASC backplane in enclosure \"$BOXNAME\" PASSES" >> $LOGFILE

	      getSideLupBoxname $1

	fi


	Bypass_BackPlane $1
}

##############################################################################
#
#	Test_Single_Bp_drives		Test single Backplane drives
#
#
##############################################################################

function Test_Single_Bp_Drives
{


	getSideLupBoxname $1
	Enable_BackPlane $1

	/usr/bin/grep "$BOXNAME,$BPRF" $DEVSONLY > $DVS2TST

	SLOT0=`/usr/bin/grep ",$BPRF"0 $DVS2TST`
	SLOT1=`/usr/bin/grep ",$BPRF"1 $DVS2TST`
	SLOT2=`/usr/bin/grep ",$BPRF"2 $DVS2TST`
	SLOT3=`/usr/bin/grep ",$BPRF"3 $DVS2TST`
	SLOT4=`/usr/bin/grep ",$BPRF"4 $DVS2TST`
	SLOT5=`/usr/bin/grep ",$BPRF"5 $DVS2TST`
	SLOT6=`/usr/bin/grep ",$BPRF"6 $DVS2TST`
	SLOT7=`/usr/bin/grep ",$BPRF"7 $DVS2TST`
	SLOT8=`/usr/bin/grep ",$BPRF"8 $DVS2TST`
	SLOT9=`/usr/bin/grep ",$BPRF"9 $DVS2TST`
	SLOT10=`/usr/bin/grep ",$BPRF"10 $DVS2TST`

	# get min config based on f/r 7/11 slot BP

	if [[ "$SLOT10" = "" && "$SLOT9" = "" && "$SLOT8" = "" && "$SLOT7" = "" ]] ; then
	    # This a5k has 7 drives per backplane
	    ALLDVSLST="$SLOT0 $SLOT1 $SLOT2 $SLOT3 $SLOT4 $SLOT5 $SLOT6"
	else
	    # This a5k has 11 drives per backplane
	    ALLDVSLST="$SLOT0 $SLOT1 $SLOT2 $SLOT3 $SLOT4 $SLOT5 $SLOT6 $SLOT7 $SLOT8 $SLOT9 $SLOT10"
	fi

	ACOUNT=`count "$ALLDVSLST"`;

	if (( $ACOUNT == 0 )) ; then
		echo "FATAL:  No drives showing up on this backplane";
		return
	fi
       
        if(( $ACOUNT <= 3)) ; then
	    echo "";
	    echo "There aren't enough drives on this backplane to isolate";
	    echo "to the failing drive. If we attempt to bypass drives in";
	    echo "in order to isolate to the failing drive, we would go ";
	    echo "below the minimum required amount of online drives on a";
	    echo "backplane. ";
	    echo "";
	    return
	fi

	init_binary_drive_test "$ALLDVSLST";


	BADBACKPLANE=""

	binary_drive_test  "$ALLDVSLST";


	if [[ "$FOUNDFAILURE" != "" ]] ; then

		echo "Found suspected bad drive [$FAILED_DRIVE]."
		echo "Going to bypass this drive and run lbf again.  If we get errors this signifies intermittent problems." 
		DEV=$FAILED_DRIVE;
		Bypass_Drive $FAILED_DRIVE			
		Test_lbf_patterns;
		# it shouldn't fail because it's disabled
		if [[ "$CPASS" != "PASS" ]] ; then
			DEV=$FAILED_DRIVE;
			Enable_Drive $FAILED_DRIVE  
			cat $DR_ERRORS >> $INTERMITTENT_ERRORS;
			echo "retesting with failed drive [$FAILED_DRIVE] BYPASSED still produced failures.  Possible backplane, GBIC, HA or IB errors.";
			echo "retesting with failed drive [$FAILED_DRIVE] BYPASSED still produced failures.  Possible backplane, GBIC, HA or IB errors." >> $INTERMITTENT_ERRORS;
			FLAKY_DRIVE=TRUE

		else  # o.k. it did what it was supposed to so lets test with it enabled
		      # this should fail.

			echo "Now adding [$FAILED_DRIVE] back in with all other drives. This should fail if [$FAILED_DRIVE] is really bad.";
			DEV=$FAILED_DRIVE;
			Enable_Drive $FAILED_DRIVE  
			Test_lbf_patterns;
			if [[ "$CPASS" = "PASS" ]] ; then
				cat $DR_ERRORS >> $INTERMITTENT_ERRORS;
				echo "retesting with failed drive [$FAILED_DRIVE] enabled does not produce failures.  Possible backplane, GBIC, HA or IB errors.";
				echo "retesting with failed drive [$FAILED_DRIVE] enabled does not produce failures.  Possible backplane, GBIC, HA or IB errors." >> $INTERMITTENT_ERRORS;

				FLAKY_DRIVE=TRUE

			fi
		fi


	fi

        getSideLupBoxname $1
		
	Bypass_BackPlane $1


	return;   


}
	


	

#####################################################################
#
#
#	init some global for binary_backplane_test	
#
#
#####################################################################



function init_binary_backplane_test {

	BOXFOUND="";
	BPENABLEDLIST="";
	FIRST="1"
	FAILED_DRIVE="";


}

#####################################################################
#
# binary_backplane_test "drive slots"
#
# This will recursively call itself until it fails or is down to one
# backplane.
# Argument $1 is the list.  Cannot be put into variable since this routine 
# is recursive. 
# Assumes starting with all backplanes bypassed
#
#######################################################################


function binary_backplane_test { 

		count=`count "$1"`;


		if (( $count < 1 )) ; then
			return;
		fi


		echo "Entering binary box testing: [$1]"; 

		# Again.  This routine must be called with all backplanes
		# disabled

		for bpfile in `retFirstHalf "$1"` # enable first half of list
		do
			for bp in `cat $FLOGDIR/$bpfile.$$` 
			do
				
				getSideLupBoxname $bp  # just like Set_Vars
				echo "Testing(enabling)  $BOXNAME backplane=$BPASC"
				Enable_BackPlane;
			done
		done

	
		Test_lbf_patterns  		

		for bpfile in `retFirstHalf "$1"`	# re-disable them 
		do
			for bp in `cat $FLOGDIR/$bpfile.$$` 
			do
				getSideLupBoxname $bp  # just like Set_Vars
				echo "re-bypassing [$BOXNAME] $BPASC backplane"
				Bypass_BackPlane $bp;		
			done
		done

		

		if [[ "$CPASS" != "PASS"  ]] ; then 	# now just test first half 

			fh=`retFirstHalf "$BOXPRINT"`;
			sh=`retSecondHalf "$BOXPRINT"`;




			if [[ "$FIRST" = "1" && "$count" != "1" ]] ; then
				FIRST=0;
				
				
				echo "Cross checking box grouping [$fh] against box grouping [$sh]"
				echo "If this fails it indicates problems other than backplanes or drives."
				for bpfile in `retSecondHalf "$1"` # enable first half of list
				do
					for bp in `cat $FLOGDIR/$bpfile.$$` 
					do
						getSideLupBoxname $bp  # just like Set_Vars
						echo "testing(enabling) $BOXNAME backplane=$BPASC"
						Enable_BackPlane;
					done
				done

				Test_lbf_patterns  # run lbf test 

				for bpfile in `retSecondHalf "$1"` # enable first half of list
				do
					for bp in `cat $FLOGDIR/$bpfile.$$` 
					do
						getSideLupBoxname $bp  # just like Set_Vars
						echo "re-bypassing $BOXNAME backplane=$BPASC"
						Bypass_BackPlane BackPlane;
					done
				done

				if [[ "$CPASS" != "PASS" ]] ; then

					
					echo "Failure when [$fh] enabled while [$sh] bypassed and then [$sh] enabled while [$fh] bypassed during lbf testing.\n" >> $BOX_ERRORS
					MULTIPLE_BOX_FAILURE=YES
					return
				 fi

					
			fi
				
			
			firstHalfList=`retFirstHalf "$1"`
                        thiscount=`count "$firstHalfList"`;

                        if [[ "$thiscount" = "1" ]] ; then
                                BOXFOUND=$firstHalfList;
                                return;
                        fi

			binary_backplane_test "`retFirstHalf "$1"`"   
								      
								      

								      
								      
		else

			FIRST=""

			if [[ "$count" = "1" ]] ; then
				return;
			fi

			binary_backplane_test "`retSecondHalf "$1"`";  # now call with second half of list

		fi




}





#####################################################################
#
# binary_drive_test "drive slots"
#
# This will recursively call itself until it fails or is down to one
# component.
# Argument $1 is the list.  Cannot be put into variable since this routine 
# is recursive. 
#
#
#######################################################################




function binary_drive_test { 

		


		if (( found > 0 )) ; then
			return;
		fi


		DEPTH=`expr $DEPTH + 1`;

		DCOUNT=`count "$1"`

		if [[ $DCOUNT != "1" ]] ; then   # we are testing odd drives
			for DEV in `retEven "$1"`
			do
				Bypass_Drive $DEV			# off line 
			
			done
		else

			let "onesFound = onesFound + 1";
			
		fi

		

		CPASS="PASS";

		
		echo "Testing with drives: "
		echo "Enabled = $ENABLEDLIST";
		echo "Bypassed = $BYPASSED";
		echo
		

		Test_lbf_patterns;

		
		echo "result: $CPASS"

		# PUT EVEN BACK ON LINE

		if [[ $DCOUNT != "1" ]] ; then   # we are testing odd drives
			for DEV in `retEven "$1"`   
			do

				Enable_Drive $DEV # put 'em back 
						  # on line cause 
						  # they passed
		
			done
		fi

		if [[ "$DCOUNT" = "1" ]] ; then    

			if [[ "$CPASS" != "PASS" ]] ; then
				let "found = 1";
	    			FOUNDFAILURE="YES";
				echo "Drive failure $BOXNAME is $1" >> $DR_ERRORS
				DRIVE_FAILURE="YES"
				FAILED_DRIVE=$1;

			else

				FOUNDFAILURE="";


			fi
			return;
		fi


		if [[ "$CPASS" != "PASS" ]] ; then   # odds failed

			# this means something online has failed
			# go and do a binary search on the online drives

			if [[ "$FIRST" = "1" ]] ; then   # First pass.  Evens bypassed and odds enabled
						      # failed.  We think we have a problem in the odds.
						      # Lets just test with evens enabled and odds disabled.
						      # If this fails it is a backplane problem.
						      # 
				FIRST=0		      # don't do this again

				EVENS=`retEven "$1"`;  # for messaging later
				ODDS=`retOdd "$1"`;

				for DEV in `retOdd "$1"`
				do
					Bypass_Drive $DEV			

				done

				echo "Enabled = $ENABLEDLIST";
				echo "Bypassed = $BYPASSED";
				echo
				Test_lbf_patterns;

				for DEV in `retOdd "$1"`  # re-enable then no matter what. If we have a failure 
							  # with this we have a backplane issue. 
				do
					Enable_Drive $DEV			
				done


				if [[ "$CPASS" != "PASS" ]] ; then

					BADBACKPLANE="YES"
					return;

				fi
			fi

			binary_drive_test "`retOdd "$1"`";

		else    # no failure on odds so now test evens

			FIRST=

			binary_drive_test "`retEven "$1"`";

		fi



}

# Must be called before binary_drive_test

function init_binary_drive_test {

		ENABLEDLIST="";	
		BYPASSED="";

		for DEV in $1
		do
		   Enable_Drive $DEV			# off line 
		
		done

		let "found = 0";
		let "onesFound = 0";
		DEPTH=0;
		FIRST=1;
		BACKPLANE="NO"
		FOUNDFAILURE=
}


# add arg 2 into the list in arg1 

function addList {

	ADDLIST=`$BINDIR/perl -e ' sub numerically {  \
		$a =~ /\d+/; $c = $&; $b =~ /\d+/;  return($c <=> $&); }; \
		foreach $i (sort numerically @ARGV) { printf("$i ") }  ' $1 $2`;

	echo "$ADDLIST ";
	
}


# delete arg 2 from the list in arg1 

function deleteList {

	DELETELIST=`$BINDIR/perl -e '@a = split(/ /, $ARGV[0]); \
		foreach $i (@a) {if ( ! ($i eq "$ARGV[1]") ) { printf("$i "); } }' \
		"$1" $2`;


	echo "$DELETELIST ";

}


# arg 1 = SIDE-LOOP-BOXNAME.  Split this apart and put into
# variable of same name

function getSideLupBoxname {


	if [[ "$1" = "" ]] ; then  # do nothing because this is not
				   # called with a valid arg.
		return
	fi
	SIDE=`$BINDIR/perl -e '@a=split(":", $ARGV[0]); print @a[0];' $1`	
	LUP=`$BINDIR/perl -e '@a=split(":", $ARGV[0]); print @a[1];' $1`	
	BOXNAME=`$BINDIR/perl -e '@a=split(":", $ARGV[0]); print @a[2];' $1`	
	SES=`$BINDIR/perl -e '@a=split(":", $ARGV[0]); print @a[3];' $1`	

	Set_Vars;




}

function markBpEnabled {

	TEMP=`addList "$BPENABLEDLIST" $1`;
	BPENABLEDLIST=$TEMP	
	TEMP=`deleteList "$BPBYPASSED" $1`;
	BPBYPASSED=$TEMP

}

function markBpBypassed {

	TEMP=`deleteList "$BPENABLEDLIST" $1`;

	BPENABLEDLIST=$TEMP;

	TEMP=`addList "$BPBYPASSED" $1`

	BPBYPASSED=$TEMP;
	

}



function markDriveEnabled {

	TEMP=`addList "$ENABLEDLIST" $1`;
	TEMP=$TEMP
	ENABLEDLIST=$TEMP	
	TEMP=`deleteList "$BYPASSED" $1`;
	BYPASSED=$TEMP

}

function markDriveBypassed {

	TEMP=`deleteList "$ENABLEDLIST" $1`;
	ENABLEDLIST=$TEMP


	TEMP=`addList "$BYPASSED" $1 `
	BYPASSED=$TEMP;

}


function extract_failing_patterns
{


    echo " "
    if ( sedr_log ) ; then
		echo " \"sedr\" found the following patterns:"
	else
		echo " \"loop integrity test\" found the following patterns (up to $maxnpats most popular):"
    fi
    echo " "
    /usr/bin/rm $FAILPATFIL
    CMD1="open FAIL, \"<$FAILPATFIL2\";"
    CMD2='$maxpats = $ARGV[0]; @file = <FAIL>; close FAIL; open NUMFILE, ">$ARGV[1]"; open PATFILE, ">$ARGV[2]"; foreach $line (@file) { $item = ""; $cnt = ""; ($item, $cnt) = ($line =~ /x([a-fA-F0-9]+) Cnt=(\d+)/); next if ($item eq ""); $seen{$item} += $cnt;  } foreach $pat (sort { $seen{$b} <=> $seen{$a} } keys %seen) { print NUMFILE "$pat $seen{$pat}\n"; print PATFILE "$pat\n"; $maxpats --; last if (!($maxpats)); } close PATFILE; close NUMFILE;'
    CMD="$CMD1 $CMD2"
    `$BINDIR/perl -e "$CMD" $maxnpats $PATNNUM $PATFILE`

    /usr/bin/rm -f $FAILPATFIL2
    echo " "
    /bin/cat $PATFILE
}


function extract_mpat_patterns
{
let "i = 1"
# log file LIT  example: /var/opt/STORtools/logs/diags/t_seqrl.14689.c3.14697
# log file sedr example: /var/opt/STORtools/logs/sedr/sedr.log.14689.str.lbf.c3
if [[ ! -a $LOGDIR/diags ]] ; then
    DOPHASEI=YES
    return
fi

# select appropriate log file
VALIDFILE=
if ( sedr_log ) ; then
	/usr/bin/ls $LOGDIR/sedr/sedr.log.*.str.lbf.* 2> /dev/null > $OFILE
else
	/usr/bin/ls -t $LOGDIR/diags/t_seqrl.* 2> /dev/null > $OFILE
        /usr/bin/ls -t $LOGDIR/ivm/run.ivm.log.* 2> /dev/null >> $OFILE
fi
TSEQRLFILE=`cat $OFILE`

if [[ ! -z $TSEQRLFILE ]] ; then
	if ( sedr_log ) ; then
    	for FILENM in `/usr/bin/ls -t $LOGDIR/sedr/sedr.log.*.str.lbf.*`
    	do
		# echo $FILENM
		if [[ ! -z `/usr/bin/grep $PTH $FILENM` ]]; then
	    	# echo $FILENM
			DOPHASEI=NO
			/usr/bin/grep "FAIL=" $FILENM > $FAILPATFIL
			## if [[ ! -z `/usr/bin/grep FAIL $FILENM` ]] ; then
			if [[ ! -z `/bin/cat $FAILPATFIL` ]] ; then
		    	/bin/cat $FAILPATFIL | /usr/bin/sed s/FAIL=43// > $FAILPATFIL2
		    	extract_failing_patterns
		    	# echo "File with latest \"loop integrity test\" run "
		    	# echo "	is $FILENM"
		    	VALIDFILE=YES
		    	return
			else
		    	VALIDFILE=YES
			fi
		fi
		DOPHASEI=YES
    	done
	else
    	#for FILENM in `/usr/bin/ls -t $LOGDIR/diags/t_seqrl.*`
    	for FILENM in `/usr/bin/cat -t $OFILE`
    	do
		# echo $FILENM
		if [[ ! -z `/usr/bin/grep $PTH $FILENM` ]]; then
	    	# echo $FILENM
			DOPHASEI=NO
			/usr/bin/grep "FAIL=" $FILENM > $FAILPATFIL
			## if [[ ! -z `/usr/bin/grep FAIL $FILENM` ]] ; then
			if [[ ! -z `/bin/cat $FAILPATFIL` ]] ; then
		    	/bin/cat $FAILPATFIL | /usr/bin/sed s/FAIL=43// > $FAILPATFIL2
		    	extract_failing_patterns
		    	# echo "File with latest \"loop integrity test\" run "
		    	# echo "	is $FILENM"
		    	VALIDFILE=YES
		    	return
			else
		    	VALIDFILE=YES
			fi
		fi
		DOPHASEI=YES
    	done
	fi
	if [[ ! -z $VALIDFILE ]] ; then
	    echo " All logs showed no failures."
	    read ans?" Do you want filtr to find failing patterns? [<y>, n]: "
	    if [[ "$ans" = "y" || "$ans" = "Y" || "$ans" = "" ]]; then
		DOPHASEI=YES
	    else
		Clean_exit
	    fi
	fi
fi
}


##############################################################################
#
#	Find_PTR
#
# test a specified loop LUP to find failing pattern 
#
# out:	PATURN ( failing paturn to use for rest of testing )
#	FOUND = YES if failure is found.  "" otherwise
#	$PATFILE contains up to "maxnpats" failing patterns
#
##############################################################################
function Find_PTR
{

	FULLWARN=
	echo " "
	echo " * "
	echo " * PHASE I * Find failing patterns "
	echo " * "
	echo " * PHASE I * Find failing patterns " >> $LOGFILE
	let "phaseim = 1"	# phase I multiplier

    if [[ -z $DOPHASEI ]] ; then
	# if -f option specified, 
	#	ask user if patterns in file are desirable.  
	#	Then exit
	if [[ ! -z $INPATFILE ]] ; then
	    echo "User defined pattern file specified"
	    echo "\n"
	    for this in `/bin/cat $INPATFILE`
	    do
		echo "      $this"
	    done
	    
	    echo " "
	    #echo " Do you want filtr to continue and use these patterns or quit? "
	    echo "filtr continuing using the above patterns. Control-C to exit.";
	    echo " "
	    ans=1
	    if [[ "$ans" = "1" || "$ans" = "" ]]; then
		FOUND=YES
		for PTR in `/bin/cat $INPATFILE`    # cp $INPATFILE $PATFILE
		do
		   if [[ -z `echo $PTR | /usr/bin/grep "devices"`  ]] ; then
		   	echo $PTR >> $PATFILE
		   	echo "$PTR 0" >> $PATNNUM
		   fi
		done
		let "phaseim = 2"	# phase I multiplier
		/bin/cat $PATFILE >> $LOGFILE
		return
	    fi
	    if [[ "$ans" = "q" ]] ; then
		Clean_exit
	    fi
	    FOUND=
	else

	RECOVEREDFILE=
	if [[ ! -z $RECOVER ]]; then
	    FULLWARN="YES"
	    /usr/bin/ls $OLDFLOGDIR/recoverpat.* 2> /dev/null > $OFILE
	    RECOVEREDFILE=`/usr/bin/cat $OFILE`
	    # if [[ ! -z `/usr/bin/ls $OLDFLOGDIR/recoverpat.*` ]] ; then
	    if [[ ! -z $RECOVEREDFILE ]] ; then
		let "c = 1"
		for FILENM in `/usr/bin/ls -t $OLDFLOGDIR/recoverpat.*`
		do
		    if [[ ! -z `/usr/bin/grep $PTH $FILENM` ]]; then
		      if ((c > 0)); then
	    		echo " Do you want filtr to continue and use these patterns or quit? "
			/bin/cat $FILENM
	    		echo " "
	    		echo " "
	    		echo " [1] use the patterns above. "
	    		echo " [q] quit "
	    		echo " "
	    		read ans?" Select option [<1>, q]: "
		        if [[ "$ans" = "1" || "$ans" = "" ]]; then
			    FOUND=YES
			    let "phaseim = 2"	# phase I multiplier
			    for D in `/bin/cat $FILENM`
			    do
				if [[ -z `echo "$D" | /usr/bin/grep "devices"` ]] ; then
				    echo $D >> $PATFILE
				    echo "$D 0" >> $PATNNUM
				fi
			    done
			    /bin/touch $PATFILE
			    if [[ -z `/bin/cat $PATFILE` ]]; then
				FOUND=
			    else
				FOUND=YES
				let "phaseim = 2"	# phase I multiplier
				/bin/cat $PATFILE >> $LOGFILE
				return
			    fi
			fi
			if [[ "$ans" = "q" ]]; then
			    Clean_exit
			fi
			let "c = 0"	# just do this once
		      fi		# 
		    fi		# ! -z `/usr/bin/grep $PTH $FILENM`
		done
	    fi			# ! -z `/usr/bin/ls -t $OLDFLOGDIR/*/recoverpat`
	else
	    extract_mpat_patterns
	    if [[ -a $PATFILE ]] ; then
		let "WC = `wc $PATFILE | /usr/bin/awk '
		    / / {print $1}'`"
		if (( WC == 0 )) ; then
		    DOPHASEI="YES"
		    FULLWARN="YES"
		fi
	    fi
	fi			# ! -z $RECOVER
	fi			# ! -z $INPATFILE

	if [[ "$DOPHASEI" = "NO" ]] ; then
	    echo " "
	    echo " Do you want filtr to continue and use these patterns or quit? "
	    echo " "
	    echo " [1] use the patterns above. "
	    echo " [q] quit "
	    echo " "
	    read ans?" Select option [<1>, q]: "
	    if [[ "$ans" = "1" || "$ans" = "" ]]; then
		FOUND=YES
		let "phaseim = 2"	# phase I multiplier
		/bin/cat $PATFILE >> $LOGFILE
		return
	    fi
	    if [[ "$ans" = "q" ]]; then
		Clean_exit
	    fi
	    /usr/bin/rm -f $PATFILE > $OFILE
	    /usr/bin/rm -f $PATNNUM > $OFILE
	fi
    fi			# -z $DOPHASEI

	if [[ ! -z $FULLWARN ]] ; then
	    echo " No files contained failing patterns for the path under test: "
	    echo " $PTH. "
	    echo " So filtr is going into full PHASE I failing pattern search."
	fi

	FOUND=
        /usr/bin/date >> $LOGFILE
	/usr/bin/rm -f $PATFILE > $OFILE
	/usr/bin/rm -f $PAT2FILE > $OFILE
	let "numpats = 0"
	let "numpats2 = 0"

	
        
	NBT=50;

	SIZ=64 ; Q=k ;  NAME="Testing Pattern "    

	Test_all_lbf			# perform test

	if [ "$VERBOSE" = "on" ]; then
	  echo " "
	else
	  echo ".\c"
	fi

	# if there's less than maxnpats patterns, 
	#   fill the pattern file with patterns in the pattern2 file
	if ((numpats < maxnpats)); then
	    let "asum = numpats + numpats2"
	    if ((asum <= maxnpats)); then
		/bin/touch $PAT2FILE
		/bin/cat $PAT2FILE >> $PATFILE
		/usr/bin/sort $PATFILE | /bin/uniq > $FLOGDIR/pattx
		/usr/bin/rm -r $PATFILE > $OFILE
		mv $FLOGDIR/pattx $PATFILE
	    else
		for PATT in `/bin/cat $PAT2FILE`
		do
		    if ((numpats < maxnpats)); then
		    	echo $PATT >> $PATFILE
		    fi
		    let "numpats = numpats + 1"
		done
	    fi
	fi

	if [[ "$FOUND" = "" ]]; then
	    echo " "
	    echo "Found no failing pattern."
	    echo "Found no failing pattern." >> $LOGFILE
	fi


}



##############################################################################
#
#	Set_Vars
#
# input: SES must point to a valid SES path
#
# output: WWN 
#	LUP (a/b), LOOP (A/B)
#	SIDE (f for front/ r for back)
#	BOXNAME of SES device
#
##############################################################################
function Set_Vars
{
    #Set_vars

    SYSTYP=`/usr/bin/uname -m`

    if [[ "$SYSTYP" = "sun4d" ]]; then
        # sun4d machines don't put wwn in the /dev/es/ses path so
	# we must use luxadm to get this info.

	#first strip of /dev/es from SES path
	MYSES=`echo "$SES"| /usr/bin/sed 's/\\/dev\\/es\\///' `

	# do a rawdump, grep for all the ses's that
	# contain the SES we are looking for.
	# Print out WWN and first SES location(The SES
	# shows up in 2 places with different values, we
	# want the first) Then pipe this into another grep
	# to make sure we get the WWN for the SES that
	# we are looking for. I tried to only print
	# out the WWN if the first SES matched  but for
	# some reason ksh will match even when the SES is
	# in the second location. This is why I pipe the
	# output from awk to a second grep.

	# sleep a few seconds to ensure loop is online(mainly for qlc loops)
	sleep 20;

	WWN=`$BINDIR/rawdump | /usr/bin/grep " $MYSES "| /usr/bin/awk '{
                  print $3 " " $4;
               }'|/usr/bin/grep "$MYSES"|/usr/bin/awk '{
               print $1 ;
               }' `

	echo "sun4d WWN= $WWN" >> $LOGFILE
	PATa="5[0-9a-f]\{14\}[129a]"
	PATb="5[0-9a-f]\{14\}[34bc]"
	PATf="5[0-9a-f]\{14\}[139b]"
	PATr="5[0-9a-f]\{14\}[24ac]"
    else

	# extract WWN from path of SES device
	# do a long listing on SES path /dev/es/ses# 
	# keep only the 11th field because it contains the WWN in the form
	# ../../dev.../ses@w####
	# replace the ../../dev../ses@w with just ses
        WWN=`/usr/bin/ls -l  $SES |awk '{print $11}' |/usr/bin/sed s/\..*ses/ses/ `


	echo "WWN= $WWN" >> $LOGFILE
	# if the wwn ends with a 1,2,9 or a this 
	# loop is on the a side.
	# how this next line reads is 
	# search for ses@w5 then 14 chars of 0-9/a-f
	# and then a char "1,2,9 or a" and ",0:0" or ",0:1"
	PATa="ses@w5[0-9a-f]\{14\}[129a]\,0:[01]"
	# if the wwn ends with a 3,4,b or c this
	# loop is on the b side.
	PATb="ses@w5[0-9a-f]\{14\}[34bc]\,0:[01]"
	# if the wwn ends with a 1,3,9 or b the 
	# loop is on the front. 
	PATf="ses@w5[0-9a-f]\{14\}[139b]\,0:[01]"
	# if the wwn ends with a 2,4,a, or c the
	# loop is on the rear. 
	PATr="ses@w5[0-9a-f]\{14\}[24ac]\,0:[01]"
    fi


	LUP=
	# look to see if the wwn ends with a B loop number
	# if it does, replace the string with 'b'
	# if it doesn't, lup will still contain the wwn

	LUP=`echo "$WWN" | /usr/bin/sed s/$PATb/b/`
	# look to see if the wwn ends with a A loop number
	# if it does, replace the string with a 'a'
	# if it doesn't, then lup would still have 
	# the WWN which should become an error.
	LUP=`echo "$LUP" | /usr/bin/sed s/$PATa/a/`
	case $LUP in
	    b) LOOP=B;;
	    a) LOOP=A;;
	  $WWN) echo "Invalid LUP WWN $WWN"; exit;;
	esac

	SIDE=
	SIDE=`echo "$WWN" | /usr/bin/sed s/$PATr/r/`
	SIDE=`echo "$SIDE" | /usr/bin/sed s/$PATf/f/`
	case $SIDE in
	    r) BPRF=r; BPASC="rear";;
	    f) BPRF=f; BPASC="front";;
	    $WWN) echo "Invalid SIDE WWN $WWN"; exit;;
	esac


	# get ses name from SES name file
	TTT=`/usr/bin/grep $SES $SESNMFILE`

	BOXNAME=`echo $TTT | /usr/bin/awk '
		/\// {print $2}'`	# retrieves boxname

	if [[ -z $BOXNAME ]]; then

	    LUXLINE="/usr/sbin/luxadm display $SES"

	    bg_luxadm

	    #luxout contains all the information for SES, must grep out the ses name from
	    # this information: note that we use ':' as a deliminter.
	    BOXNAME=`echo $LUXOUT|grep Enclosure | awk -F: '{print $5 }' | awk '{print $1}'`

	     

	    if [[ -z $BOXNAME ]]; then	# if BOXNAME is a null string
		/usr/sbin/luxadm -e forcelip $PTH
		/usr/bin/sleep 5;

		BOXNAME='/usr/sbin/luxadm display $SES |grep Enclosure \
		       | awk -F: '{print $5 }' | awk '{print $1}``

		if [[ -z $BOXNAME ]]; then	# if BOXNAME is a null string
		  # box name is still null
		  # if we can't get the boxname, we won't beable to get the
		  # rest of the information we need.
		  echo "FATAL unable to get the box name"
		  exit
		fi


	    fi
	    echo ".\c"

	fi
	echo "Set_Vars boxname= $BOXNAME lup= $LUP wwn= $WWN side= $SIDE" >> $LOGFILE
}


##############################################################################
#
#     Clean_tmp
#
#	Delete files in $FLOGDIR
#
##############################################################################
function Clean_tmp
{

	/usr/bin/rm -f $ADEVFAIL >> $OFILE
	/usr/bin/rm -f $ABPSFAIL >> $OFILE
	/usr/bin/rm -f $DEVSONLY >> $OFILE
	/usr/bin/rm -f $BPS >> $OFILE
	/usr/bin/rm -f $BPSONLY >> $OFILE
	/usr/bin/rm -f $DEVFAIL >> $OFILE
	/usr/bin/rm -f $BPSFAIL >> $OFILE
	/usr/bin/rm -f $ZFILE >> $OFILE
	/usr/bin/rm -f $PATFILE >> $OFILE
	/usr/bin/rm -f $PAT2FILE >> $OFILE
	/usr/bin/rm -f $DVS2TST >> $OFILE
	/usr/bin/rm -f $SESFILE >> $OFILE
	/usr/bin/rm -f $SESNMFILE >> $OFILE
	/usr/bin/rm -f $DASHLOGDEVT >> $OFILE
	/usr/bin/rm -f $ENAFILE >> $OFILE
	/usr/bin/rm -f $EFILE >> $OFILE
	/usr/bin/rm -f $PATNNUM >> $OFILE
	/usr/bin/rm -f $SUGGESTN >> $OFILE
	/usr/bin/rm -f $FOO >> $OFILE
	/usr/bin/rm -f $BOX_ERRORS >> $OFILE
	/usr/bin/rm -f $BP_ERRORS >> $OFILE
	/usr/bin/rm -f $DR_ERRORS >> $OFILE
	/usr/bin/rm -f $DR_ERRORS >> $OFILE
	/usr/bin/rm -f $INTERMITTENT_ERRORS >> $OFILE

	for boxname in $BOXLIST	
	do
		if [ -e $FLOGDIR/$boxname.$$ ] ; then
			rm $FLOGDIR/$boxname.$$;
		fi
	done

}


function Exit_tail
{
	DATENOW=`/usr/bin/date`
	/usr/bin/logger -p mail.crit -i -t [StorTools:DIAG:INFO:2001]: filtr test END - $PTH
	echo "$DATENOW [StorTools:DIAG:INFO:2001]:filtr test END" >> $LOGFILE
	echo " "
	echo " >>> $LOGFILE contains filtr output <<< "
	echo " "
	#
	#	Call Veritas script to bring back path HERE.
	#
	if [[ "$DIDTHEVXTHING" = "YES" ]] ; then
	    echo " "
	    echo " Remember to reenable the $CN path for Volume Manager if disabled. "
	    echo " "
	fi

}


##############################################################################
#
#     Clean_exit
#
#	write to messages file and exit
#
##############################################################################

function Clean_exit
{
	if [[ "$MANUAL" == "ON" ]]; then
    	    echo " "
    	    echo "Please put back all IB boards and GBICs where they were originally."
	    ans=
	    while [[ "$ans" != "y" ]]
	    do
		read ans?" Are all the GBICs in place? [y, <n>]: "
	    done

	    contc_enable   # make certain that things aren't bypassed on manual exit
	fi
	Clean_tmp
	if [[ -z $USAGE ]]; then
	    Exit_tail
	fi
	exit
}


function BldDevL_work
{
   # build logical devices from ses path


   echo ".\c"
   	

   # We want to create a structure that contains: box name, drive 
   # location ie:r5, drive path ie: /dev/rdsk/c2t121d0s2
   # Rawdump dumps all info on all devices 
   # look for devices that contain our box name.
   # The box name is in field 1 of the string.
   # The list from that includes DDs(disk drives) and IBs?
   # We only want the disk drives 
   # look for DD in field 8
   # The only part we want out of this string is the box name in
   # field 1 and the cxtxdx number in field 4 
   # We print fields 1 and 4 but we add
   # /dev/rdsk to field 4 to get the full path.
   # 

   integer position=1
   integer match=0
   keep=0
   # have to disable "*" substitution
   set -o noglob
   # sleep a few seconds to ensure loops are good.
   sleep 15;
   for LINE in ` $BINDIR/rawdump`
   do
     if((position == 1)) then
        location=$LINE
        enc_name=`echo $LINE | /usr/bin/awk ' {x=split($1,CUT,","); print CUT[1] }' `
        if [[ "$enc_name" == "$BOXNAME" ]]; then
           match=1
        fi
     fi
     if((match == 1)) then 
         if ((position == 4 )) then
            disk=$LINE

         fi
         if ((position == 8 )) then
           if [[ "$LINE" == "DD" ]]; then
	      # check to see if this drive is on the given path



	   # extract the CN number from the disk
	   # Do this by echoing disk, 
	   # then substitue the 't' in cxtxdxsx with a space and so
	   # that the cx number is separeted from the rest of the string.
	   # Then use awk to print only the cx number
	      DISK_CN=`echo "$disk" |  \
	          /usr/bin/sed -e 's/t/ /' |/usr/bin/awk '{print $1}' `
	      
	      if [[ "$DISK_CN" == "$CN" ]]; then

		 echo "$location /dev/rdsk/${disk}s2" >> $DASHLOGDEVT;

		 echo "$location" >> $DEVSONLY;

		 # mark drive as enabled 
		 markDriveEnabled $location;

	      fi
   	      match=0
   	    fi
         fi	
     fi
     position=$position+1
   
     if(( position == 12 )) then
      position=1
     fi
   
   done 
   #reneable "*" file substitution
   set +o noglob


   #log the box name, disk location, and path to logfile
   /bin/cat $DASHLOGDEVT 2> /dev/null 1>> $LOGFILE;

   # Do a quick check to ensure we found some drives
   ACOUNT=`wc -w $DASHLOGDEVT 2> /dev/null | awk -e '{ print $1 }'`	

   if (( $ACOUNT < 1 )) ; then	
       echo ""
       echo "FATAL: Failed to produce a device list. "
       echo "Check system loop configuration";
       exit;
       
   fi


	    
}


#
#	Build list of devices on loop
#
function Build_DevLists
{

	if ( t3 ) ; then
		return;
	fi

	for SES in `/bin/cat $SESFILE`
	do
	    Set_Vars
	    # build backplane-only files
	    echo "$BOXNAME,$BPRF" >> $BPS
	    echo "$BOXNAME" >> $FLOGDIR/xyz	#$BPSONLY
	done


	/bin/touch $FLOGDIR/xyz
	/usr/bin/sort $FLOGDIR/xyz | /bin/uniq > $BPSONLY
	/usr/bin/rm -f $FLOGDIR/xyz > $OFILE

	/bin/cat $BPSONLY >> $LOGFILE

	echo " "
	echo " Creating a list of drives and their names."

	for BOXNAME in `/bin/cat $BPSONLY`	
	do
	    if [[ ! -z $BOX2TST ]]; then
	    # echo "$BOXNAME $BOX2TST"
		if [[ "$BOXNAME" = "$BOX2TST" ]] ; then
		    BldDevL_work
		fi
	    else
		BldDevL_work
	    fi

	done
	echo " "
}


##############################################################################
#
#	Test_loop
#
# test a specified loop LUP for specific SES devs 
# bypass individual devices (DEV) on the loop until it finds the failing node
#
# vars:	CONTTEST ( continue testing )
#	LUP (either A or B loop)
#	SES (ses device)
#	K (for bacK), Z1, Z2 (temps)
#	SKIP (skip rest of test)
#	DEV (indiviual node on the loop)
#
# output: CONTTEST == YES if failure had been found by Find_PTR
#
# calls: Test_lbf which uses Q, NBT, SIZ, PTR, & NAME as input
#	 as well as BP, LUP and SES
#
# algorithm:
#	Get everything off the loop.
#	Bypass all devices, then bypass all back planes.
#	Then start lbf testing with failing pattern.
#	Add one backplane back on at a time.
#	When all backplanes are added back, add one device back on at a time.
#	Keep track until the list is complete.
#		List is saved in $ZFILE
#
##############################################################################

function Test_loop
{


	echo " "
	echo " * "
	echo " * PHASE II * Attempt to isolate FRU with failing/default patterns."
	echo " * "
	echo " * PHASE II * Attempt to isolate FRU with failing/default patterns." >> $LOGFILE


	echo "\nEntering Loop testing for $PTH\n`date`"
	# Bypass the BPs


	if ( t3 ) ; then 


		NBT=4096;
		Q=k; 
		SIZ=64;    



		echo "Testing T300 on path = $PTH"
		echo

		Test_lbf_patterns

		if [[ "$CPASS" = "PASS" ]] ; then
			echo "Test passes."
			echo "No further testing required. Cleaning up and exiting. ";
			return;
		else

			T300FAIL=yes;
			echo "  Lbf error on <$PTH>"
 			echo "  T300 cannot be tested down to the backplane or disk level."
 			echo "  This indicates a [Media, Cable, GBIC, MIA or HA]"
 			echo "  problem. "
			echo  "  Going to manual mode";


	    		ENTRY="1"

	    		Manual_Test   # never returns

			return;  # just in case ( a little humor )
			



		fi

		# we will go into a loop as long as it fails where they can
		# exchange cables. media, GBIC, MIA or HA and then run filtr
		# again.
		# psuedo code
		# we are going to run dexio with this
		# we will run test_patterns on this
		# if it fails we will go into pseudo manual mode
		
		# if it passes filtr will pass

		


	fi

	echo "\nSkipping enabling of all backplanes.  You've done this?  Right?"
	echo "If NOT type control-c and enable all drives and backplanes and restart this test."
	echo

	# Test with all BPs off here


	if (  dexIo ) ; then
		NBT=1600
	else 
		NBT=2400
	fi


	Q=k ; SIZ=64    # these were set in Text_BP_off
				  # need to set here instead
	echo "Testing with all backplanes enabled."
	echo
	echo "If this fails we will continue testing \nto find failing drives and backplanes."
	echo
	Test_lbf_patterns
	if [[ "$CPASS" = "PASS" ]] ; then
		SKIP="YES"
		echo "Test with all backplanes enabled passes."
		echo "No further testing required. Cleaning up and exiting. ";
		return;
	else
		SKIP="NO"
		echo "Test with all backplanes enabled failed."
		echo "Further testing required. We will try to isolate failing backplanes/drives.";
		echo "First we will bypass all backplanes."
		bypassAll
		echo "Bypassing of backplanes complete."
	fi
	
	# if testing with BPs bypassed is ok, then test each BP.

	if [[ "$SKIP" != "YES" ]]; then

	    BOXLIST=
	    BOXPRINT=
	    for SES in `/bin/cat/ $SESFILE` 
	    do
	    	Set_Vars

	    	if [ ! -e $FLOGDIR/$BOXNAME.$$ ] ; then

	    		touch $FLOGDIR/$BOXNAME.$$
	    		BOXLIST="${BOXLIST}$BOXNAME "
	    		BOXPRINT="${BOXPRINT}$BOXNAME "
	    		
	    	fi

	    	echo "$SIDE:$LUP:$BOXNAME:$SES" >> $FLOGDIR/$BOXNAME.$$
	
	    done

	    init_binary_backplane_test;

	    BPTEST="TRUE";
	    BACKPLANEFILE=
	    BOXFOUND=

	    BCOUNT=`count "$BOXLIST"`;


	    if [[ "$BCOUNT" != "1" ]] ; then
	    	echo "Starting binary search for failing A5000s in this list:  \n[$BOXPRINT]"
	    	binary_backplane_test "$BOXLIST";  # do a binary search for
	    				   	   # bad box
	    else
	    	BOXFOUND=$BOXLIST;   # only one box any so use this box to 
	    			    # do next phase.
	    fi


	    if [[ "$MULTIPLE_BOX_FAILURE" = "YES" ]];  then
	           	printPTime 
	    	echo "Errors detected on multiple backplanes.  \nProbable problem cause is other loop hardware." >> $BOX_ERRORS
	    	echo "Errors detected on multiple backplanes.  \nProbable problem cause is other loop hardware.";

	    	ENTRY="1"
	    	Manual_Test   # never returns

	    	FOUNDFAILURE="YES"
	    	return;
	    fi

	    BPTEST="FALSE";

	    # squeeze out spaces

	    BOXFOUND=`$BINDIR/perl -e '$i = $ARGV[0]; $i =~ tr/ //d; print $i;' $BOXFOUND`

	    BACKPLANEFILE=$BOXFOUND




	    if [[ "$BACKPLANEFILE" != "" ]] ; then  # found bad box
	    					# now test individual
	    					# backplanes
	    	FBX=`$BINDIR/perl -e '@a = split(/\./, $ARGV[0]); print $a[0];' $BOXFOUND`;
	    	echo " ## Failures found for A5x00 [$FBX] while both backplanes enabled:"  >> $BP_ERRORS

	    	for bp in `cat $FLOGDIR/$BOXFOUND.$$`
	    	do
	    		
	    		echo "		$bp" >> $BOX_ERRORS
	    	done

	    	let "badbbcount = 0"
	    	FOUNDFAILURE=
	    	SAVEFAILURE=


	    	# First check the backplanes

	    	for bp in `cat $FLOGDIR/$BACKPLANEFILE.$$`
	    	do
	    		echo 
	    		getSideLupBoxname $bp  # just like Set_Vars
	    		echo "\n TEST_SINGLE_BACKPLANE for box = $BOXNAME backplane = $BPASC\n"
	    		
	    		BADBACKPLANE=""

	    		Test_Single_Bp_Nodrive $bp;
	    		if [[ "$CPASS" != "PASS" ]] ; then
	    			let "badbbcount = badbbcount + 1"
	    			BADBP=$bp;
	    		fi

	    	done

	    	if (( badbbcount == 2 )) ; then

	    		echo
	    		echo
	    		echo "Errors detected on both backplanes on Box [$BACKPLANEFILE].  Probable problem cause is other loop hardware." >> $BP_ERRORS
	    		echo "Errors detected on both backplanes on Box [$BACKPLANEFILE].  Probable problem cause is other loop hardware.";
	    		ENTRY=1;
	    		Manual_Test
	    		return
	    	fi
	    	if (( badbbcount == 0 )) ; then

	    		echo
	    		echo
	    		echo "Errors found on [$BACKPLANEFILE] were not reproducable in tests of individual backplanes.  Probable problem cause is other loop hardware."; >> $BP_ERRORS
	    		echo "Errors found on [$BACKPLANEFILE] were not reproducable in tests of individual backplanes.  Probable problem cause is other loop hardware."; 
	    		ENTRY=1;
	    		Manual_Test
	    		return
	    	fi


	    	let "badbbcount = 0";

	    	getSideLupBoxname $BADBP  # just like Set_Vars
	    	echo "\n $BOXNAME backplane = $BPASC FAILED\n"
	    	echo "Check drives on $BPASC backplane in $BOXNAME\n"
	    		

	    	let "tcont = 1"	

	    	INTERMITTENT=
	    	while (( tcont == 1 )) ; do 

	    		FLAKY_DRIVE=
	    		BADBACKPLANE=

	    		echo > $DR_ERRORS;

	    		Test_Single_Bp_Drives $BADBP;
	    		

	    		if [[ "$BADBACKPLANE" != "" ]] ; then
	    			echo "\n[$BOXNAME $BPASC] backplane failed.  This was determined by testing failures while"  >> $BP_ERRORS
	    			echo "[$EVENS] enabled and [$ODDS] bypassed \nand then the reverse" >>$BP_ERRORS
	    			echo "[$ODDS]  enabled and [$EVENS] bypassed." >>$BP_ERRORS
	    			echo "This is more than one point of drive failure and therefore indicates a backplane problem"  >> $BP_ERRORS
	    			BINARY_BACKPLANE_FAILURE="YES";
	    			let "tcont = 0";
	    			ENTRY=1;
	    			Manual_Test
	    			return
	    		else
	    			if [[ "$FOUNDFAILURE" = "" ]] ;then
	    				INTERMITTENT_BP_ERROR=TRUE
	    				echo "$BOXNAME $BPASC backplane was found to be bad in intial testing."
	    				echo "Subsequent testing finds no problem."
	    				echo "$BOXNAME $BPASC backplane was found to be bad in intial testing." >> $INTERMITTENT_ERRORS
	    				echo "Subsequent testing finds no problem." >> $INTERMITTENT_ERRORS
	    				echo "Dropping into drive testing with option to increase lbf iterations."	
	    			fi

	    		fi


	    		if [[ "$FLAKY_DRIVE" = "TRUE" || "$INTERMITTENT" = "TRUE" || "$INTERMITTENT_BP_ERROR" = "TRUE" ]] ;then

	    			if [[ "$FLAKY_DRIVE" != "TRUE" ]] ; then
	    				echo "More re-testing of drives for intermittent problems?"
	    			else
	    				echo "Intermittent problems. Do you want to retest drives on this backplane."
	    			fi

	    			INTERMITTENT=TRUE; # once your here you can only go to manual mode to exit.
	    			read ans?" [y, <n>]: "
	    			if [[ "$ans" = "y" || "$ans" = "Y" || "$ans" = "yes" || "$ans" = "YES" ]] ; then
	    				change_nbt;
	    			else
	    				let "tcont = 0"
	    				ENTRY=1;
	    				Manual_Test
	    				return
	    			fi

	    		else
	    			let "tcont = 0";

	    		fi


	    	done

	    		
	    		

	    fi

	    for box in $BOXLIST	
	    do
	    	for bp in `cat $FLOGDIR/$box.$$`
	    	do
	    			
	    		getSideLupBoxname $bp  # just like Set_Vars
	    		Enable_BackPlane;
	    		
	    	done
	    	#rm $box
	    done

	    BACKPANES=ENABLED

	    for bpbp in $BOXLIST
	    do
	        rm $FLOGDIR/$bpbp.$$ > /dev/null;   # remove the files
	    done
	
	fi


	enableAllDrivesBps

      ## fi	# CONTTEST = YES
}


function Display_Results
{
	echo " "
	echo " "
	echo " *****************************************************  "
	echo " *****************************************************  "
	echo " *****************************************************  "
	echo " "
	echo " RESULTS OF TESTING $PTH "
	echo " "
	echo " "

	if [[ "$SOMEBODYHITCONTC" != "" ]] ; then

		echo "  This process was interupted by a CONTROL-C";
		echo "  Results are AFFECTED by this action.   "
		echo	
	fi

	if (  t3 ) ; then


		if [[ "$T300FAIL" = "yes" ]] ; then
			echo "  T300 Failure!"
		else
			echo "  T300 pass!"
		fi

		echo " "
		echo " "
		echo " ***************************************************** "
		echo " ***************************************************** "
		echo " ***************************************************** "
		echo " "

		return

	fi


	if [[ "$DRIVE_FAILURE" = "YES" ]] ; then
		
		if [[ "$INTERMITTENT" = "TRUE" || "$INTERMITTENT_BP_ERROR" = "TRUE" ]] ; then
			echo "Intermittent Errors:"
			cat $INTERMITTENT_ERRORS
		else

			if [[ "$BINARY_BACKPLANE_FAILURE" != "YES" ]] ; then
				echo "No individual backplane errors."
			else
				echo "Backplane Errors: \n"
				cat $BP_ERRORS
	
				echo "Also isolated drive problem on other backplane.\n"	
			fi

			echo "Drive error: \n"
	
			cat $DR_ERRORS

		fi

	else  # backplane

		if [[ "$INTERMITTENT" = "TRUE" || "$INTERMITTENT_BP_ERROR" = "TRUE" ]] ; then
			echo "Intermittent Errors:"
			cat $INTERMITTENT_ERRORS
		else
			echo "No individual drive errors.";
	
			if [[ "$BINARY_BACKPLANE_FAILURE" = "YES" ]] ; then
				echo "Multiple drive errors.\n";
				echo "Backplane Errors:\n"
				cat $BP_ERRORS
			else
				echo "No individual backplane errors.\n"
				if [[ "$MULTIPLE_BOX_FAILURE" = "YES" ]] ; then
					cat $BOX_ERRORS;
				fi
				if [[ "$BPS_FAILED" = "YES" ]] ;then
					cat $BP_ERRORS;
				fi
			fi
		fi
	fi

        echo " "
	echo " "
	echo " ***************************************************** "
	echo " ***************************************************** "
	echo " ***************************************************** "
	echo " "
}



##############################################################################
#
#	Test_path
#
# either try the selected path, extracting SES, LUP (A/B Port)
#
# vars:	WWN ( The WWN extracted from the path )
#	LUP (either A or B loop)
#	SES (ses device)
#
# calls: Test_loop which uses SES & LUP as input
#
##############################################################################
function Test_path
{
	echo "Test path = $PTH" >> $LOGFILE


	if ( ! t3 ) ; then
		/usr/sbin/luxadm -e forcelip $PTH
		/usr/bin/sleep 4;

		CHECK_BXNM=
		## SESFILE filled before Check_FWRevs
		for SES in `/bin/cat $SESFILE`
		do
		  Set_Vars
	
		  echo "LOOP $LOOP" >> $LOGFILE
		  echo "SIDE $SIDE" >> $LOGFILE
		  echo "BOXNAME $BOXNAME" >> $LOGFILE
		  case $LUP in
		    b) LOOP=B;;
		    a) LOOP=A;;
		    "") echo " ********** FILTR ERROR *********** "
			echo " Couldn't distinquish loop properly."
			echo " Check and make certain that ses device $SES is named correctly!"
		    	echo " ********** FILTR ERROR *********** " >> $LOGFILE
			echo " Couldn't distinquish loop properly." >> $LOGFILE
			echo " Check and make certain that ses device $SES is named correctly!" >> $LOGFILE
			Clean_exit;;
		  esac
		  case $BOXNAME in
		    "") echo " ********** FILTR ERROR *********** "
			echo " Could not get proper boxname from $SES "
		    	echo " ********** FILTR ERROR *********** " >> $LOGFILE
			echo " Could not get proper boxname from $SES " >> $LOGFILE
			Clean_exit;;
		  esac
		  if [[ "$BOXNAME" == "$BOX2TST" ]]; then
		      CHECK_BXNM="OK"
		  fi
	
		done	# for SES in `/bin/cat $SESFILE`
	
		if [[ "$BOX2TST" != "" && -z $CHECK_BXNM ]]; then
			echo " "
			echo "ERROR: Boxname entered for individual testing: $BOX2TST"
			echo " WAS NOT FOUND ON THE PATH $PTH"
			echo " exiting... "
			echo " "
			echo "ERROR: Boxname entered for individual testing: $BOX2TST" >> $LOGFILE
			echo " WAS NOT FOUND ON THE PATH $PTH" >> $LOGFILE
			Clean_exit
		fi
	
	
		# from the sesfile make two lists
		# one list is devs only (slots for drives)
		# the other is a list of backplanes 
	
		Build_DevLists

	fi  # end; if ( !t3 )

	CONTTEST=
	NOPAT=
	Find_PTR

	CONTTEST=$FOUND


	if [[ "$CONTTEST" = "" ]]; then
	    NOPAT=YES
	else
	    getPTime
	    Test_loop
	    printPTime
	    echo "Exiting Loop testing for $PTH:\n `date`\n"
	fi



      if [[ "$NOPAT" = "" ]] ; then

	   echo " "
   	   echo " "
	   if [[ "$BACKPLANES" != "ENABLED" ]] ;then 
		   if ( ! t3 ) ; then
			   echo " enable devices/backplanes that have been bypassed. " 
			   echo " enable devices/backplanes that have been bypassed. "  >> $LOGFILE
			   enableAllDrivesBps
		   fi
	   fi

	    Display_Results
      else
	## if [[ "$NOPAT" = "YES" ]] ; then
	echo " ***************************************************** "
	echo " "
	echo " "
	echo " * No problem found!! * "
	echo " * No problem found!! * " >> $LOGFILE
	echo " "
	echo " "
	echo " ***************************************************** "
      fi	# NOPAT = ""
}


function Do_ManualMode
{
	if [[ -z $FORCEMAN ]] ; then 
	    # if it wasn't forced into manual mode then find failing patterns
	    Find_PTR
	    echo " "
	    echo " * "
	    echo " * PHASE II * Going into Manual mode testing "
	    echo " * "
	    echo " * PHASE II * Going into Manual mode testing " >> $LOGFILE
            Build_DevLists
	else
	    # else came from user forcing us here from Check_4_Offline
	    #  And we don't know what we have.
	    /bin/touch $DEVSONLY 
	    /bin/touch $PATFILE 
	fi
	    ENTRY=
	    Manual_Test
	    if [[ ! -a $PATFILE ]] ; then
		Display_OutofBoxMsg
	    fi
	    Clean_exit
}


##############################################################################
#
#	Check_FWRevs
#
# checks the fw revision of the IBs.  it needs V1.07 or better for 
#		this script to run.
# vars:	OK2DL ( there's a good version of IB FW in this system that is ok to download) 
#	SES (ses device), SESFW (ses FW Version), 
#	CHANGE (this ses devices needs to download more current ib fw -- 1.07 or later) 
#
# input: PTH
#
##############################################################################

function Check_FWRevs
{

	PATS1="SUN	SENA	1\."
	PATS2="SUN	A5x00	1\."
	FW1=`strings /usr/lib/locale/C/LC_MESSAGES/ibfirmware | /usr/bin/grep SENA | /bin/uniq` 
	FW2=`strings /usr/lib/locale/C/LC_MESSAGES/ibfirmware | /usr/bin/grep A50 | /bin/uniq` 

	Z=`echo $FW1 | /usr/bin/awk '
		/./ {print $3}'`

	OK2DL=
	case $Z in
	    1.07) OK2DL=1;;
	esac
	if [ "$FW2" != "" ]; then
	    OK2DL=1
	fi
	# echo "OK2DL= $OK2DL"

	for SES in `/bin/cat $SESFILE`
	do
	    # Check IB Firmware Version of this SES device
	    SESFW=`/usr/sbin/luxadm inq $SES | /usr/bin/grep Revision`

	    SESFW=`/usr/sbin/luxadm inq $SES | /usr/bin/grep Revision | /usr/bin/awk ' 
		/./ {print $2}'`
	    # date
	# 
	    CHANGE=
	    case $SESFW in
		05) CHANGE=1 ;;
		03) CHANGE=1 ;;
		01) CHANGE=1 ;;
		1.05) CHANGE=1 ;;
		1.03) CHANGE=1 ;;
		1.01) CHANGE=1 ;;
	    esac
	    if [ "$CHANGE" = "1" ]; then
		echo "This IB $SES needs firmware Rev 1.07 or better to run this test.  "
		if [ "$OK2DL" = "1" ]; then
		   echo " Please upgrade the IB firmware. "
		   echo " Always consult the appropriate README before downloading firmware. "
		else
		   echo " The firmware doesn't reside on the system. "
		   echo " Please get the appropriate patch."
		   echo " Always consult the README before downloading firmware. "
		fi
		Clean_exit
	    fi
	done
	if [[ -z $CHANGE ]]; then	# if CHANGE is a null string
	    echo " "
	    echo "Appropriate IB FW level found for bypass testing (FW V1.07 Minimum)."
	    echo "Appropriate IB FW level found for bypass testing (FW V1.07 Minimum)." >> $LOGFILE
	    echo "Testing begins."
	    echo ""
	    echo "  Testing begins." >> $LOGFILE
	fi
}



#
# Input: PTH = the path to extract 'CN"
# Output: CN = the c number 
#
function Get_CN
{
   # get the "C#" from the path

   Z=`echo $PTH | /usr/bin/grep ":0"`
   ## echo $Z  
   if [[ ! -z $Z ]]; then
      #Path is in the form of path:0
      SUBPTH=`echo $PTH | /usr/bin/sed s/:0//`
      SFPTH="/sf@0,0"
   else
      Z=`echo $PTH | /usr/bin/grep ":1"`
      if [[ ! -z $Z ]]; then
         #Path is in the form of path:1
         SUBPTH=`echo $PTH | /usr/bin/sed s/:1//`
         SFPTH="/sf@1,0"
      else
         Z=`echo $PTH | /usr/bin/grep ":devctl"`
         if [[ ! -z $Z ]]; then
            #Path is in the form of path:devctl
         SUBPTH=`echo $PTH | /usr/bin/sed s/:devctl//`
            SFPTH=""
         else
           echo "Get Controller number: Unrecognized path:"
	   echo "$PTH"
         fi
      fi
   fi

   DEVPTH="$SUBPTH""$SFPTH"

   # first get the controller numbers that contain the given path
   # do this by doing a long listing on the /dev/rdsk directory,
   # grep out the path we are looking for,
   # only print the field with the Cxtxdxsx number in it(field 9)

    PATH_CN=`/usr/bin/ls -l /dev/rdsk/c*s2 | /usr/bin/grep "$DEVPTH" \
        | /usr/bin/awk '{print $9}' `
 
  
    # now validate the paths using luxadm inq.
    # do this by doing "luxadm inq path"
    # if it is a valid path, luxadm will print physical path
    
    CN=""
    CN_OK=""
    for CHECK_CN in $PATH_CN
    do
	CN_OK=`luxadm inq $CHECK_CN 2>/dev/null | /usr/bin/grep "Physical" `

        if [[ "$CN_OK" != "" ]]; then
	   #found a valid path
	   # extract the CN number from the PATH_CN
	   # Do this by echoing check_cn, trim off the /dev/rdsk/ path,
	   # then substitue the 't' in cxtxdxsx with a space and so
	   # that the cx number is separeted from the rest of the string.
	   # Then use awk to print only the cx number
	   CN=`echo "$CHECK_CN" | /usr/bin/sed -e 's/\/dev\/rdsk\///' \
	      | /usr/bin/sed -e 's/t/ /' |/usr/bin/awk '{print $1}' `
	   # since we have found a valid path with this CN number, there
	   # is no reason to continue looking so break out of loop.
	   break;
	fi
    done


}


##############################################################################
#
#	Usage - echo proper input and then exit
#
##############################################################################
function Usage
{
	echo "Usage: filtr [-y] [-d]  [-v] [-r] [-slog] [-f filename] [-m] PATH [Boxname]"
	echo " "
	echo " -y    yes, run the test (avoids y/n question at beginning of test) "
	echo " -v    verbose mode "
	echo " -r    recover failing patterns to avoid Phase I "
	echo " -f    use filename with user defined patterns to avoid Phase I "
	echo " -m    go into manual mode "
	echo " -d    use disk I/O (dex) to create load when lbf run"
	echo " -slog use sedr log files"
	echo " "
	echo "  available PATHs: "

	for PTH in  `/usr/sbin/luxadm -e port |/usr/bin/grep devices \
	          |/usr/bin/awk '{print $1} `
	do
	    echo "	$PTH \c"
	    Get_CN
	    echo " ($CN)"
	done
	Clean_exit
}



function check_file
{

	if [[ ! -a $1 ]] ; then
	   echo "filtr: file [$1] not found."
	   let "checkfilefound = 0";
	   echo "";
		
	   return;
	fi

	let "checkFirst = 1"

        for i in `cat $1`
	do

		$BINDIR/perl -e 'if ( $ARGV[0] =~ /devices/ ){ exit(0); } if (length($ARGV[0]) != 8) { exit(1); } @a = split(//, $ARGV[0]);  foreach $z (@a) {    if (!  ($z =~ /a|b|c|d|e|f|\d/i )   ) {  exit(1);  }  } exit(0);' $i;

		
		if [[ "$?" != "0" ]] ; then
	   		echo "filtr: pattern [$i] from file [$1] is not hexadecimal or is not correct length of 8 bytes ."
	   		let "checkfilefound = 0";
			return	

		fi
		
	done

	let "checkfilefound = 1";
}






function checkarg
{


   if ( usePat ) ; then
   	INPATFILE=$FLOGDIR/recoverpat.debug
   fi
   if [[ ! -z $PTH ]] ; then
       BOX2TST=$1
       return
   fi
   if [[ ! -z $LAST ]] ; then
       case $LAST in
       f)	check_file $1
   	if (( ! checkfilefound )) ; then
   		Clean_exit;
   	fi
   	INPATFILE=$1
   	# echo $INPATFILE
   	LAST=
   	return;;
       esac
   fi
   TAG=
   LAST=
   case $1 in
       -slog) SEDR=on;
   	LAST=sedr;
   	TAG=1;;
       -r) RECOVER=on
   	LAST=r
   	TAG=1;;
       -v) VERBOSE=on
   	LAST=v
   	TAG=1;;
       -y) CONTINUESTART=on
   	LAST=y
   	TAG=1;;
       -f) INPATFILE=
   	LAST=f
   	TAG=1;;
       -m) MANUALMODE=on
   	LAST=m
   	TAG=1;;
       -d) DEXIO="on"
   	LAST=d
   	TAG=1;;
       -a) echo "filtr $VERSION" 
   	Clean_exit ;;
       -[c-eg-lnopqstuwxzA-Z0-9]) Usage $1;;
       -[a-zA-Z0-9])	Usage $1;;
   esac
 
   #if [[ -z $TAG ]] ; then


     U=
     UU=
     UUU=
     V=

     T=`echo $1 | /usr/bin/grep "devices"`

     if [[ "$T" != "" ]] ; then
       U=`echo $T | /usr/bin/grep "sbus"`
       UU=`echo $T | /usr/bin/grep "io-unit"`
       UUU=`echo $T | /usr/bin/grep "pci"`

       if [[ "$U" != "" ]] ; then
   	V=`echo $U | /usr/bin/grep "socal"`
	if [[ $V == "" ]] ; then
	   #check for a usoc
	   V=`echo $U | /usr/bin/grep "usoc"`
	fi
       elif [[ "$UU" != "" ]] ; then
   	V=`echo $UU | /usr/bin/grep "socal"`
       elif [[ "$UUU" != "" ]] ; then
   	V=`echo $UUU | /usr/bin/grep "ifp"`
   	if [[ "$V" == "" ]]; then
   	   V=`echo $UUU | /usr/bin/grep "qlc"`
   	fi
       fi  
     fi



     if [[ $V != "" ]] ; then
       PTH=$1
     fi
   #fi  
}


function Name_file
{
######### FILE VARIABLE PARAMETERS ##############
OFILE=$FLOGDIR/filtout.$$
ZFILE=$FLOGDIR/loopn.out.$$
EFILE=$FLOGDIR/error.$$
DEVSONLY=$FLOGDIR/devsonly.$$
BPS=$FLOGDIR/bps.$$
BPSONLY=$FLOGDIR/bpsonly.$$
DEVFAIL=$FLOGDIR/devfail.$$
ADEVFAIL=$FLOGDIR/alldevfail.$$
BPSFAIL=$FLOGDIR/bpsfail.$$
ABPSFAIL=$FLOGDIR/allbpsfail.$$
DVS2TST=$FLOGDIR/devs2test.$$
PATFILE=$FLOGDIR/patterns.$$
PAT2FILE=$FLOGDIR/patterns2.$$
SESFILE=$FLOGDIR/sesout.$$
SESNMFILE=$FLOGDIR/sesname.$$
DASHLOGDEVT=$FLOGDIR/dashlogicaldevstemp.$$
ENAFILE=$FLOGDIR/enable.$$
PATNNUM=$FLOGDIR/patnnum.$$
RCVPAT=$FLOGDIR/recoverpat.$$
FOO=$FLOGDIR/foo.$$
LOGFILE=$FLOGDIR/filtlog.$CN.$$
DRIVESENABLED=$FLOGDIR/drivesenabled.$$
touch $DRIVESENABLED;
FAILPATFIL=$FLOGDIR/patts.failed.$$
FAILPATFIL2=$FLOGDIR/patts.failed2.$$
FAILPATFIL3=$FLOGDIR/patts.failed3.$$
BOX_ERRORS=$FLOGDIR/boxerrors.$$
BP_ERRORS=$FLOGDIR/bperrors.$$
DR_ERRORS=$FLOGDIR/drerrors.$$
INTERMITTENT_ERRORS=$FLOGDIR/intermittent.$$.

SUGGESTN=$FLOGDIR/suggestion.$$

/usr/bin/rm -f $OFILE > /dev/null 2> /dev/null
/usr/bin/rm -f $ZFILE > /dev/null 2> /dev/null
}


# return the first half of the space seperated tokens



function retFirstHalf {

	
	FIRSTHALF=`$BINDIR/perl -e ' $c = $#ARGV+1; \
		
		$t = int($c/2); \
		if (  (hex($c) & 0x1) ) { # if odd
			$c=$t+1;
		} else {
			$c=$t;
		}
	
		if($#ARGV == 0) { \
			print $ARGV[0]; \
		} else { \
			foreach $i (splice(@ARGV, 0, $c)) { \
				printf("$i "); \
			}\
		}' $1`

	echo $FIRSTHALF

}


# return the second half of the space seperated tokens

function retSecondHalf {


	SECONDHALF=`$BINDIR/perl -e '\

	$c = $#ARGV+1; \
	$t = int($c/2);
	if (  (hex($c) & 0x1) ) { # if odd
		$c=$t+1;
	} else {
		$c=$t;
	}
	
	if($#ARGV == 0) { \
		print ""; 
	} else { \
		foreach $i (splice(@ARGV, $c, $#ARGV)) { \
			printf("$i "); \
		} \
	}' $1`

	echo $SECONDHALF
}






# Return even tokens from word array passed in positional param 1
# .  .i.e. passed "a b c d e f " returns "a c e"

function retEven {

	F=`$BINDIR/perl -e 'if($#ARGV == 0) { print $ARGV[0]; exit }; $c = 0; foreach $i (@ARGV ) { if ( !($c++ & 1) ) { print"$i "} };' $1`

	echo $F;
}

# Return odd tokens from word array passed in positinal param 1
# .  .i.e. passed "a b c d e f " returns "b d f"

function retOdd {

	F=`$BINDIR/perl -e 'if($#ARGV == 0) { print $ARGV[0]; exit }; $c = 0; foreach $i (@ARGV ) { if ( ($c++ & 1) ) { print"$i "} };' $1`
	echo $F;
}


# returns the count of words in positional param 1
# passed "a b c d" returns the value 4

function count {

	temp=`echo "$1" | wc -w`;
	temp1=`$BINDIR/perl -e 'printf("%d", $ARGV[0]);' "$temp"` 
	
	echo $temp1;

}



# start up some dex32 IO on the devices
# This checks to see 1) if it is in a bypassed backplane and
# 2) is it a bypassed disk.  If neither it builds a group of
# 10 disks to run dex32 on.

function startDex {


	if [[ "$DEXPID" != "" ]] ; then
		killDex;
	fi


	diskbypassed=$BYPASSED

	bpbypassed=`echo $BYPASSED | $BINDIR/perl -e '@a=split(/ /, $ARGV[0]); foreach $i (@a) { @b=split(/:/, $i); printf("$b[2],$b[0] ");}' "$BPBYPASSED"`; 


	DEXDEVS=""
	LOGDEVS=""

	#initialize variables
	disk="";
	logical="";

	integer index
	index=1
	add=no

	for d in `cat $DASHLOGDEVT 2> /dev/null`
	do

		if (( index==1)) then
  		  logical=$d
		fi

		if (( index == 2 )) then
		   disk=$d
		   add=YES
		fi

		index=index+1

		if (( index == 3 )) then 
		  index=1
		fi     
	
		
		INCLUDE=YES

		for byp in $bpbypassed	
		do
			echo $logical | fgrep $byp > /dev/null
			if [[ "$?" = "0" ]] ;then
				INCLUDE=NO
				
			fi
		done
	
		if [[ "$INCLUDE" = "YES" ]] ; then
		   if [[ "$add" = "YES" ]] ; then

		   
			
			echo $diskbypassed | fgrep $logical > /dev/null
	
			if [[ "$?" = "1" ]] ;then

			
			   LOGDEVS="$LOGDEVS $logical"
			   DEXDEVS="$DEXDEVS $disk"

			fi
			add=no
		   fi
		fi
	
	done

	COUNT=`count "$DEXDEVS"`;
	NEWLIST=

	if (( $COUNT > 14 && $COUNT < 27 )) ; then

		skip=F

		for i in $DEXDEVS
		do
			if [[ "$skip" = "F" ]] ; then
				NEWLIST="$NEWLIST $i"
				skip=T
			else
				skip=F
			fi
		done
			
	fi

	if (( $COUNT >= 27 && $COUNT < 48 )) ; then


		let "counter = 0"

		for i in $DEXDEVS
		do
			if (( counter   <  3 )) ; then
				let "counter = counter + 1"
			else
				NEWLIST="$NEWLIST $i"
				let "counter = 0"
			fi
		done
	
		
			
	fi
	if ((  $COUNT >= 48 )) ; then


		let "counter = 0"

		for i in $DEXDEVS
		do
			if (( counter   <  4 )) ; then
				let "counter = counter + 1"
			else
				NEWLIST="$NEWLIST $i"
				let "counter = 0"
			fi
		done
	
		
			
	fi

	if [[ "$NEWLIST" = "" ]] ; then

		DEXDEVS=$DEXDEVS
	else
		DEXDEVS=$NEWLIST

	fi


# now do the same of LOGDEVS so we get a nice printout of
# what dex is being run on.

	COUNT=`count "$LOGDEVS"`;


	NEWLIST=

	if (( $COUNT > 14 && $COUNT < 27 )) ; then
		skip=F
		for i in $LOGDEVS
		do
			if [[ "$skip" = "F" ]] ; then
				NEWLIST="$NEWLIST $i"
				skip=T
			else
				skip=F
			fi
		done
			
	fi

	if (( $COUNT >= 27 && $COUNT < 48 )) ; then

	   let "counter = 0"

	   for i in $LOGDEVS
	   do
	   	if (( counter   <  3 )) ; then
	   		let "counter = counter + 1"
	   	else
	   		NEWLIST="$NEWLIST $i"
	   		let "counter = 0"
	   	fi
	   done
	    	
	fi
	if ((  $COUNT >= 48 )) ; then
		let "counter = 0"

		for i in $LOGDEVS
		do
			if (( counter   <  4 )) ; then
				let "counter = counter + 1"
			else
				NEWLIST="$NEWLIST $i"
				let "counter = 0"
			fi
		done
	
	fi

	if [[ "$NEWLIST" = "" ]] ; then
		LOGDEVS=$LOGDEVS
	else
		LOGDEVS=$NEWLIST

	fi

	if [[ "$DEXDEVS" = "" ]] ; then
		echo No devices online.  Skipping dex command
	else
		echo "starting dex on [$LOGDEVS]";
        	$BINDIR/dex32 -v -S 8g 0 60m -x 128k -r ${DEXDEVS} 2>/dev/null 1>&2 &
		DEXPID=$!;
	fi

}

# get the user value of NBT

function change_nbt {


	let "cont = 1";


		echo "By increasing lbf iterations you can more thoroughly test an intermittent problem.";

	     echo "Do you want to change the number lbf iterations?\c"
	     read ans?" [y, <n>]: "
	     if [[ "$ans" = "y" && "$ans" != "Y" && "$ans" != "yes" && "$ans" != "YES" ]] ; then
			
		while (( $cont == 1 )) ; do 
			echo "enter new number or <cr> to default to current [$NBT]:\c"
			read ans;	
			newnum=`echo "$ans" | $BINDIR/perl -e '$what=<STDIN>;  if ( ! ($what =~ /\d+/) || $what < 0 )  { print "$ARGV[0]"; exit;} else { ; print $what; }' $NBT`; 
			if [[ "$newnum" = "FALSE" ]] ; then
				echo "bad input";
			else
				TEMPNBT=$newnum;
				echo "lbf iterations are now [$TEMPNBT] is this correct?:\c"
	     			read ans?" [y, <n>]: "
	     			if [[ "$ans" = "y" && "$ans" != "Y" && "$ans" != "yes" && "$ans" != "YES" ]] ; then
					let "cont = 0"
					NBT=$TEMPNBT
					NEWNBT=TRUE
				fi
			fi
		done
	      	else
			return
	      	fi
		

}



# kill dex processes

function killDex {


	if [[ "$DEXPID" != "" ]] ; then
		kill $DEXPID > /dev/null 2>&1;
	fi

	DEXPID=


}



# check to see if T300 is attached to loop


function isItT300 {

	T300="off"

	echo ""
	echo " Generating loop map"
	echo ""
	# Find out if this loop has a t300 on it.

	# create a list of all loops that have a T300.
	# do this by doing a disk inquiry and grep for t300 and then printing
	# the CN(controller number) for that line.
	T300_CN=`$BINDIR/disk_inquiry 2>/dev/null |grep T300 \
	      | awk '{print $1}' `

	# Check to see if the CN for the path that was passed in
	# includes a T300.
	for MYCN in $T300_CN
	do
	  # the form of t300_cn is c#t#d#. We only want the c#
	  # so use sed to pull off the t#d#.
	  # first substitue the 't' in c#t#d# with a space to
	  # seperate the c# from the rest of the string
	  # Now use awk to print only the c#
	  ONLY_CN=`echo "$MYCN" | /usr/bin/sed -e 's/t/ /' \
	            | /usr/bin/awk '{print $1}' `

	  if [[ "$ONLY_CN" == "$CN" ]] 
	  then
	    # We have found a t300 on this loop 
	    T300="on";
	    # since we have found a T300 on this loop there is no
	    # reason to continue in loop
	    break;
	  fi
	done   


	#check for a mixture of T300s and a5ks
	if [[ "$T300" == "on" ]]
	then
	   # call get SES Paths to see if there are SES paths on this path
	   Get_SES_Paths

	   if [[  "$MYVALIDSES" == "" ]]; then
	      echo""
	      echo " *****************************"
	      echo " * Found a T300 on this loop *"
	      echo " *****************************"
              echo ""
	   else
	      # We have found a T300 and a SES on same loop
	      echo ""
	      echo " ************************************************************************"
	      echo " * Filtr has detected that an SES enclosure and a T300 are on the same  * "
	      echo " * loop. In order to better isolate to a failing component please put   *"
	      echo " * the SES enclosure and T300 on separate loops and run filtr again     *"
	      echo " ************************************************************************"

	      exit;
	   fi

        fi



}

# This function will retrieve the SESs on the given path
function Get_SES_Paths {


   MPATH=""

   # search for SES enclosures in /dev/es directory
   # First must remove :xxx from port path
   # Put this value into MPATH - modified path


   Z=`echo $PTH | /usr/bin/grep ":0"`
   if [[ ! -z $Z ]]; then
      #Path is in the form of path:0
      SUBPTH=`echo $PTH | /usr/bin/sed s/:0//`
      SFPTH="/sf@0,0"
   else
      Z=`echo $PTH | /usr/bin/grep ":1"`
      if [[ ! -z $Z ]]; then
         #Path is in the form of path:1
         SUBPTH=`echo $PTH | /usr/bin/sed s/:1//`
         SFPTH="/sf@1,0"
      else
         Z=`echo $PTH | /usr/bin/grep ":devctl"`
         if [[ ! -z $Z ]]; then
            #Path is in the form of path:devctl
            SUBPTH=`echo $PTH | /usr/bin/sed s/:devctl//`
            SFPTH=""
         else
           echo "Get ses paths: Unrecognized path:"
	   echo "$PTH"
         fi
      fi
   fi

   MPATH="$SUBPTH""$SFPTH"

   # This next line of code will put all of /dev/es/sesx 
   # associated with MPATH above into
   # the variable MYSESs.
   # first do an ls -l on the /dev/es directory to get
   # the link listing of all SES's,
   # Pipe the output from this into grep - looking for
   # the modified port path from above.
   # The output of the grep still gives the entire ls -l listing
   # and the only part we want is the link name from this sooo
   # pipe the output of the grep into awk and only print out
   # field 9 of the ls -l listing(this is the link name ie: ses0)
   # But we want the /dev/es/sesx name so pipe the awk output
   # into sed and replace ses with /dev/es/ses

   MYSES="`/usr/bin/ls -l /dev/es | /usr/bin/grep $MPATH \
       | /usr/bin/awk '{print $9}' \
       | /usr/bin/sed 's/ses/\\/dev\\/es\\/ses/' `"

   # At this point, the variable MYSES contains a listing
   # of all SES paths that are associated with the port
   # path. 
   
   #validate the paths in MYSES
   VALIDSES=`luxadm probe|grep Logical | /usr/bin/awk -F: '{print $2}' `

   MYVALIDSES=""

   for CHECKSES in $MYSES
   do
     for CHECKVALID in $VALIDSES
     do

	if [[ "$CHECKVALID" == "$CHECKSES" ]]
        then
           MYVALIDSES=`echo "${CHECKSES}\n${MYVALIDSES}\n\n" `
        fi
     done
   done
   
   	
   #Echo this variable into the file SESFILE.
   if  [[ ! -z $MYVALIDSES ]]; then
      echo $MYVALIDSES > $SESFILE
      if [[ "$VERBOSE" = "on" ]] ; then
         echo " "
         /bin/cat $SESFILE
      fi

   else
      echo "NO SESs found for $PTH" > $SESFILE
   fi

   echo

   /bin/cat $SESFILE >> $LOGFILE
}

####################################################################
#
#		MAIN PROGRAM
#
####################################################################


pwd | fgrep '/dev/es'

if [[ "$?" = "0" ]] ; then
	echo "Please do not execute filtr from within the /dev/es directory";
	exit 1;
fi

echo "  "
# echo "filtr Version $VERSION "
echo "  "
if [ -z $1 ]; then	# if $1 is a null string (No input)
	Usage
else
	#	Check params.  A PATH MUST BE A PARAM
	

	# for every argument passed to filtr, 
	#	check to see if it's a valid argument
	for arg in $@
	do
	    checkarg $arg
	done


	case $BOX2TST in 
	    -[a-zA-Z0-9])       Usage ;;
	esac 
	case $PTH in 
	    -[a-zA-Z0-9])      	Usage ;;
	esac 


		 

	if [[ "$VERBOSE" = "on" ]] ; then
	    echo "r:$RECOVER v:$VERBOSE c:$CONTINUESTART "
	    echo "m:$MANUALMODE f:$INPATFILE "
	    echo "box2test:$BOX2TST path:$PTH"
	    echo "d:$DEXIO"
	fi


        
	if [[ "$PTH" = "" ]] ; then
	   echo "Invalid Path";
	    Usage
	fi

	QLOGIC2100=""
	#check to see if the path passed in was a PCI 2100 board
	QLOGIC2100=`echo "$PTH" |/usr/bin/grep "ifp" `
	if [[ "$QLOGIC2100" != "" ]]
			then 
			echo "        $PROGNAME doesn't support PCI FC100!"
			echo "        Please use sedr for this port   \n\n"
			exit
        fi

	# must check to see if the path that was passed in contains
	# sf@1,0:devctl or sf@0,0:devctl, if it does strip off this
	# portion and replace it with a :1 or :0
	# this can happen if there is a socal board and stormenu
	# calls filtr.
	# Do this check by grepping the string sf@ out of the path.
	# If the pattern is found, go ahead and find out if
	# a :1 or :0 needs to be added. This is done by 
	# breaking the path at the sf@0, so use sed to replace
	# sf@ with a space. Keep only the last part of the string
	# by piping the output to awk and printing the second
	# field of the broken up string. Finally strip off the
	# ,0:devctl using sed. The variable NEED FIX will contain
	# the value 0 or 1 if the path needs to be fixed.
	NEED_FIX=""

	NEED_FIX=`echo "$PTH" | /usr/bin/grep "sf@"  \
	  | /usr/bin/sed 's/sf@/ /' |/usr/bin/awk '{print $2}'  \
	  | /usr/bin/sed 's/,0:devctl//' `

	if [[ ! -z $NEED_FIX ]] ; then
	  # PATH needs to be fixed. NEED_FIX contains the value of 0
	  # or 1 
	  case $NEED_FIX in
	  "0") PTH=`echo "$PTH" |/usr/bin/sed 's/\/sf@0,0:devctl/:0/' ` ;;
	  "1") PTH=`echo "$PTH" |/usr/bin/sed 's/\/sf@1,0:devctl/:1/' ` ;;

	  esac

	fi
	   

	echo "WARNING: "
	echo " This test will be taking devices off and on the fibre loop."
	echo " Devices on this path $PTH "
	echo " will not be accessible while running this test. "
	echo "  "
	echo " Do NOT run this test with arrays that are currently in use "
	echo " unless the loop has be quiesced or disabled. Loops can be"
	echo " quiesced or disabled by either stopping all I/O access to"
	echo " the arrays or by using the Volume Manager Path Management "
	echo " dmp path disable function if available. Reference the User "
	echo " Guide for more information."
	echo "  "

	echo "ALSO: "
	echo " Please make sure all of the enclosure backplanes are enabled"
	echo " for the loop you are testing."
	echo " If they are not enabled the building of the list of arrays and "
	echo " backplanes will be flawed and results cannot be accurate."
	echo ""


	
	if [[ "$CONTINUESTART" != "on" ]] ; then
	    read ans?" Are you sure you want to continue? [y, <n>]: "
	    if [[ "$ans" != "y" ]] ; then
		Clean_exit
	    fi
	fi

	DIDTHEVXTHING="YES"


	

	DATENOW=`/usr/bin/date`
	OLDFLOGDIR=$FLOGDIR	# If FLOGDIR changes from filtr, 
				# then there's a need to maintain 'OLDFLOGDIR'

	if [[ ! -a /var/opt/STORtools ]] ; then
		/bin/mkdir /var/opt/STORtools
		/bin/mkdir /var/opt/STORtools/logs
	elif [[ ! -a /var/opt/STORtools/logs ]] ; then
		/bin/mkdir /var/opt/STORtools/logs
	fi
	if [[ ! -a $FLOGDIR ]] ; then
	    echo " making filtr log directory in $FLOGDIR "
	    /bin/mkdir $FLOGDIR
	fi

	#get the control number of this path.
	Get_CN
        echo "";
	echo " Testing Control Number $CN";


	Name_file		# declare the names of the other files

	
	#check for T300 and SES enclusers.

        isItT300;

	if ( t3 ) ; then
		echo "\n $PTH has a T300 on it:  Running filtr in T300 mode";	
	else
		A5K="on";
	fi



	echo " "
	let "contin = 1"
	while(( contin )); do 
		echo " filtr patterns options: "
		if [[ -z $RECOVER && -z $INPATFILE ]] ; then
		TSEQRLFILE=
		RECOVEREDFILE=
		if ( sedr_log ) ; then
			/usr/bin/ls $LOGDIR/sedr/sedr.log.*.str.lbf.* 2> /dev/null > $OFILE
		else
			/usr/bin/ls $LOGDIR/diags/t_seqrl.* 2> /dev/null > $OFILE
                        /usr/bin/ls $LOGDIR/ivm/run.ivm.log.* 2> /dev/null >> $OFILE
		fi
		TSEQRLFILE=`cat $OFILE`
		PATINP1=
		PATINP2=
		if [[ ! -z $TSEQRLFILE ]] ; then
		  echo " [1]    Use failed patterns from previous loop test logs (if any)"
		else
		  PATINP1="1"
		fi
		/usr/bin/ls $OLDFLOGDIR/recoverpat.* 2> /dev/null > $OFILE
		RECOVEREDFILE=`/usr/bin/cat $OFILE`
		if [[ ! -z $RECOVEREDFILE ]] ; then
		  echo " [2]    Use recovered patterns from previous filtr test logs (-r)"
		else
		  PATINP2="2"
		fi
		echo " [3]    Use a file containing user specified patterns (-f)"
		echo " [4]    Go find failing patterns (Full PHASE I)"
		echo " "
		echo " [q]    Quit "
		echo " "
		echo " Select an operation to perform \c"
		if [[ ! -z $TSEQRLFILE && ! -z $RECOVEREDFILE ]] ; then
		  read ans?" [<1>, 2, 3, 4, q]: "
		elif [[ ! -z $TSEQRLFILE && -z $RECOVEREDFILE ]] ; then
		  read ans?" [<1>, 3, 4, q]: "
		elif [[ -z $TSEQRLFILE && ! -z $RECOVEREDFILE ]] ; then
		  read ans?" [2, 3, 4, q]: "
		elif [[ -z $TSEQRLFILE && -z $RECOVEREDFILE ]] ; then
			  read ans?" [3, 4, q]: "
		fi
		    case $ans in
		    "") if [[ -z $PATINP1 ]] ; then
				DOPHASEI= 
				let "contin = 0";
			else
				echo "Not a valid option.  No failed patterns from previous loops tests.";
			fi;;
		    1) if [[ -z $PATINP1 ]] ; then
				DOPHASEI= 
				let "contin = 0";
			else
				echo "Not a valid option.  No failed patterns from previous loops tests.";
				DOPHASEI="YES" 
			fi;;

		    2) if [[ -z $PATINP2 ]] ; then
				let "contin = 0";
				RECOVER="on"; 
				DOPHASEI=;
			else
				echo "Not a valid option.  No failed patterns from previous FRU isolation tests(This test).";
			fi;;
		    3) NEEDINFILE="on";
		       let "contin = 0";
		       DOPHASEI=;;
	
		    4) DOPHASEI="YES";
			RECOVER=
			let "contin = 0";;
		    q) Clean_exit;;
		    *) 
			echo "\n [$ans] is not a valid option.  \n";
			DOPHASEI="YES";;
		    esac
		    if [[ ! -z $NEEDINFILE ]] ; then
			let "checkfilefound = 0";
			while (( ! checkfilefound )) ;  do
		        	read INPATFILE?" Enter filename containing your patterns<q>: "
	
				if [[ "$INPATFILE" = "" || "$INPATFILE" = "q" ]] ; then
					Clean_exit;
				fi
		        	check_file $INPATFILE
			done
		    fi
		fi
	
	done   # while ( continue )

	echo
	if [[ -z $MANUALMODE ]] ; then

	    NEEDINFILE=
	    echo " Automatic or manual mode? \c"
	    read ans?" [<a>, m, q]: "
	    NEEDINFILE=
	    case $ans in
	    "") MANUALMODE=;;
	    a) MANUALMODE=;;
	    m) MANUALMODE="on";;
	    q) Clean_exit;;
	    [0-9b-lnopr-zA-Z]) echo "Will default to automatic mode." ;;
	    esac
	    echo " "
	fi
	echo
	if ( ! dexIo && a5k ) ; then
	  #check for qlc path
	  QLC=""
	  QLC=`echo $PTH | /usr/bin/grep "qlc"`

          if [[ $QLC == "" ]] ; then
	     # no qlc present, ask if they want disk io.
       		echo " Run disk I/O in conjunction with lbf? \c"
    		read ans?" [<n>, y, q]: "
 	   	case $ans in
 			"") DEXIO="off";;
    			[nN])  DEXIO="off";;
    			[yY])  DEXIO="on";;
    			[qQ]) Clean_exit;;
       			[0-9b-lopr-zA-Z]) echo "Will proceed without Dex I/O loading." ;;
    		esac
	  fi
	fi
	    
	echo
    	echo " Do re-testing on loop failure to see if soft error? \c"
	read ans?" [<n>, y]: "
	RETEST="FALSE";
	case $ans in
	  "") ;;
	  [yY]) RETEST="TRUE";;
	  [nN]) RETEST="FALSE";;
	  [0-9b-lnopr-zA-Z])  ;;
        esac

	if ( dexIo ) ; then
		echo "      ******** Disk stress loading is on"
	else
		echo "      ******** Disk stress loading is off"
	fi

	if ( t3 ) ; then
		echo "      ******** Testing a T300"
	else
		echo "      ******** Testing a A5K"
	fi

	if [[ "$RETEST" = "TRUE" ]] ; then
		echo "      ******** Retesting is on"
	else 
		echo "      ******** Retesting is off"
	fi

	if [[ ! -z $MANUALMODE ]] ; then
		echo "      ******** Manual mode"
	fi

	trap "contc; Clean_exit" 1 2 15

	USAGE=


	/usr/bin/logger -p mail.crit -i -t [StorTools:DIAG:INFO:2000]: filtr test START - $PTH
	echo "$DATENOW [StorTools:DIAG:INFO:2000]:filtr test START" >> $LOGFILE
	echo " "
	echo "filtr log output is saved in $LOGFILE"
	echo " "
	echo "r:$RECOVER v:$VERBOSE c:$CONTINUESTART" >> $LOGFILE
	echo "box2test:$BOX2TST path:$PTH" >> $LOGFILE
	Clean_tmp

	if ( ! t3 ) ; then

		#call get SES paths to get the SESs on this path.
		echo ""
		echo "Retrieving ses paths"
		Get_SES_Paths

	        if [[  "$MYVALIDSES" == "" ]]; then
		   echo "********************************"
		   echo "* Didn't find a SES Enclosure  *"
		   echo "* on this loop. Exiting out of *"
		   echo "* filtr.                       *"
		   echo "********************************"
		   exit;
		fi

		echo " "
		echo "Getting box names from ses paths"
		 for SES in `/bin/cat $SESFILE`
		 do

                     SESNAME=` /usr/sbin/luxadm display $SES \
		       | /usr/bin/grep "Enclosure" \
		       | /usr/bin/awk -F: '{print $5 }' \
		       | /usr/bin/awk '{print $1}'`


		    echo "$SES $SESNAME" >> $SESNMFILE

		    if [[ "$VERBOSE" = "on" ]] ; then
			echo "$SES $SESNAME"
		    else
			echo ".\c"
		    fi
		    echo "$SES $SESNAME" >> $LOGFILE
		 done
		 echo;

		Check_FWRevs			# check firmware revs.		
		MANMDQ=
                print "Box                 Loop               Backplanes to test:";
		print "_________           ____               ___________________";
		for SES in `/bin/cat $SESFILE`
		do
		    Set_Vars

		    markBpEnabled "$SIDE:$LUP:$BOXNAME:$SES" 
		print "                                       [$BPASC]\r                    [$LUP]\r[$BOXNAME]"
 
		
		done
	fi  # if ( ! t3 )  .  T3's do not have session files etc.
	# They appear to be one logical unit.
	if [[ -z $MANUALMODE ]]; then
	    if ( ! t3 ) ;then
		        S=`/bin/cat $SESFILE`
			if [[  -z $S ]] ; then 
	   			 # if here, there's no ses device to check, so go into manual mode

	   			 echo " There's no ses device to check: Will go into manual mode "
	    			echo " "
	    			echo " Do you want to run a manual test to further isolate the "
	    			echo " possible failure?\c"
	    			read ans?" [y, <n>]: "
	    			if [[ "$ans" != "y" && "$ans" != "Y" && "$ans" != "yes" && "$ans" != "YES" ]] ; then
	      				trap "contc; Clean_exit" 1 2 15
	      				return
				fi
	    			MANMDQ="DONE"
	    			Do_ManualMode
  	    		else
				TOQUERY=`head -1 $SESFILE`;	
				LUX=`/usr/sbin/luxadm display $TOQUERY`;
	
				LUX=`echo $LUX | $BINDIR/perl -e 'while (<>) {if (/luxadm version:\w*\d.\d/) { print $& } }'`
	    		fi
	    fi
	    Test_path
	    Clean_exit
	  else
	    Do_ManualMode
	  fi
fi






