text:
havekeys=0
havekeys_cmk=0
havekeys_cmk_migration=0
havekeys_tpm2=0
havekeys_binding=0
havekeys_signing=0
end=0

KEYSIZE=2048
KEYSIZE_ST=2048
export TPM_SESSION=osap
export TPM_INSTANCE=0
TPM_VERSION=12
USE_TPMINIT=1
# For HW TPMs with physical presence locked, set to FALSE because owner clear requires
#       manual intervention before take ownership
USE_OWNERCLEAR="1"
# Indicates that one of the HW TPM options was specified
USE_HWTPM="0"
export TPM_SERVER_NAME
export TPM_SERVER_PORT
export TPM_TRANSPORT="0"
export TPM_TRANSPORT_EK
export TPM_TRANSPORT_EKP
export TPM_TRANSPORT_SK
export TPM_TRANSPORT_SKP
export TPM_TRANSPORT_PASS=pass
export TPM_TRANSPORT_HANDLE
export TPM_TRANSPORT_ENONCE
export TPM_TRANSPORT_ENC
export LOADKEY_VERSION=""
export TPM_AUDITING="0"
export TPM_IS_FIPS="0"
export TPM_ET_ENCRYPT_AES="0"
export NO_SRK_PASSWORD=0
export TPM_USE_LOCALITY=0
export TPM_DUMP_COMMANDS="0"
export TPM_REVOKE_EK="0"
# allow keys to be swapped
export TPM_NO_KEY_SWAP="0"
#Need to implement some special handling for the following ordinals
#first in the C-code: OIAP, OSAP, DSAP, ExcecuteTransport, TickStampBlob
#MakeIdentity, ActivateIdentity, LoadIdentity
#OIAP = 10
#OSAP = 11
#DSAP = 17
#GetPubKey = 33
#Terminate_Handle = 150
#ExecuteTransport = 231
#ReleaseTransportSigned = 232
#When testing transport the stack automatically
# tries to open and close the transport session. This is bad
# for the 'GetAuditDigest' command since this changes
# the audit digest that is reported.
TPM_NON_AUDITED_ORDS="33 150 231 232"
CANNOT_AUDIT_WITH_TRANSPORT="10 11 33 150 231 232"

HWTPM_CHOICES="3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 23 25"

INTERACTIVE=1

PATH=$PWD:$PATH

showMenu ()
{
	echo ""
	echo "Master TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT"
	echo "Slave TPM at $SLAVE_TPM_SERVER:$SLAVE_TPM_PORT"
	echo ""
	echo "Please select an item from the following test:"
	echo ""
	echo "1.  NVRAM, DIRs                    15. Context                       "
	echo "2.  Counters                       16. Chg. authority                "
	echo "3.  Sealing                        17. Maintenance                   "
	echo "4.  Binding                        18. Random Numbers                "
	echo "5.  Signing                        19. Ownership                     "
	echo "6.  Key migration, no CMK keys     20. Delegation                    "
	echo "7.  Key migration, CMK keys only   21. vTPM                          "
	echo "8.  Identity & key certification   22. TPM Migration                 "
	echo "9.  Sha1                           23. Transport                     "
	echo "10. Key eviction                   24. Misc. + S3 Suspend/Resume     "
	echo "11. Quoting and PCRs               25. Capabilities (visual verification)"
	echo "12. Self test                      26. Capabilities (may need TPM to reset)"
	echo "13. Auditing                       27. Re-cycle TPM                  "
	echo "14. Ticks                          28. Certificates                  "
	echo ""
	echo "all          Run tests 1-24,28            "
	echo "hwtpm        Tests without reset: $HWTPM_CHOICES"
	echo "hwtpm-owner  Tests without reset or owner clear: $HWTPM_CHOICES"
	echo "conf         configure global test parameters   "
	echo "quit         quit test program                  "
	echo ""
	echo "Current settings: TPM_SESSION=$TPM_SESSION, KEYSIZE=$KEYSIZE"
	echo "                  TPM_INSTANCE=$TPM_INSTANCE, KEYSIZE_ST=$KEYSIZE_ST, USE_TPMINIT=$USE_TPMINIT"
	echo "                  TPM_VERSION=$TPM_VERSION, TPM_TRANSPORT=$TPM_TRANSPORT ($TPM_TRANSPORT_ENC)"
	echo "                  TPM_AUDITING=$TPM_AUDITING, TPM_REVOKE_EK=$TPM_REVOKE_EK"
	read choices
	echo "Your choice: $choices"
	if [ "$choices" == "hwtpm" ]; then
		choices=$HWTPM_CHOICES
                USE_HWTPM="1"
	fi
	if [ "$choices" == "hwtpm-owner" ]; then
		choices=$HWTPM_CHOICES
                USE_HWTPM="1"
                USE_OWNERCLEAR="0"
	fi
}

test_tpm_init()
{
	if [ "$USE_TPMINIT" != "0" ]; then
		tpminit > run.out
		ERR=$?
		if [ $ERR -ne 0 ]; then
			USE_TPMINIT=0
		else
			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
			tpmbios > run.out
			ERR=$?
			if [ $ERR -ne 0 ]; then
				USE_TPMINIT=0
			fi
			TPM_TRANSPORT_EK=
			TPM_TRANSPORT_SK=
		fi
	fi
}

test_tpm_version()
{
	getcapability -cap 0xd > run.out
	if [ $? -ne 0 ]; then
		TPM_VERSION=11
	fi
	if [ "$TPM_VERSION" == "11" ]; then
		LOADKEY_VERSION="-v1"
		TPM_TRANSPORT="0"
	fi
}

disable_auditing_ords()
{
	if [ "$TPM_VERSION" != "11" -a "$TPM_AUDITING" == "1" ]; then
		while [ "$1" != "" ]; do
			enableaudit -o $1 -d -p $OWNER_PASSWORD > run.out
			shift
		done
	fi
}

enable_auditing_ords()
{
	if [ "$TPM_VERSION" != "11" -a "$TPM_AUDITING" == "1" ]; then
		while [ "$1" != "" ]; do
			enableaudit -o $1 -p $OWNER_PASSWORD > run.out
			shift
		done
	fi
}

# Expects the owner password as first parameter
enable_auditing()
{
	if [ "$TPM_VERSION" != "11" -a "$TPM_AUDITING" == "1" ]; then
		#echo "ERROR: Owner password is $1."
		echo
		echo "Enabling auditing."
		AUDITED_ORDS=""
		rm -f .auditing-$TPM_INSTANCE
		let i=1
		while [ $i -le 255 ]; do
			let found=0
			for x in $TPM_NON_AUDITED_ORDS; do
				if [ $i == $x ]; then
					let found=1
					break
				fi
			done
			if [ $found -eq 0 ]; then
				enableaudit -o $i -p $1 > /dev/null
				RES=$?
				if [ $RES -eq 0 ]; then
					AUDITED_ORDS="$AUDITED_ORDS $i"
				else
					true
					#echo "ERROR: Could not enable auditing for ordinal $i"
				fi
			fi
			let i=i+1
		done
		echo " INFO: Enabled auditing."
		echo ""
		sync_auditing
	fi
}

sync_auditing ()
{
	if [ "$TPM_AUDITING" == "1" -a "$TPM_VERSION" != "11" ]; then
		echo "Synchronizing auditing data with TPM."
		rm -f .auditing-$TPM_INSTANCE
		if [ "$TPM_TRANSPORT" == "1" ]; then
			disable_auditing_ords $CANNOT_AUDIT_WITH_TRANSPORT
		fi
		getauditdigest -s 0 > run.out
		getauditdigest -s 0 > run.out
	fi
}

check_audit_digest ()
{
	if [ "$TPM_AUDITING" == "1" -a "$TPM_VERSION" != "11" ]; then
		#ls -l .auditing-0
		echo "Checking audit digest"
		if [ "$TPM_TRANSPORT" == "1" ]; then
			disable_auditing_ords $CANNOT_AUDIT_WITH_TRANSPORT
		fi
		getauditdigest -s 0 > run.out
		ERR=$?
		if [ $ERR -eq 0 ]; then
			if [ "$1" == "1" ]; then
				cat run.out
			fi
			RES=`cat run.out | grep "same digest"`
			if [ "$RES" != "" ]; then
				echo " INFO: Audit digest is the same"
			else
				echo " ERROR: Audit digest is different"
				ACTUAL=`cat run.out | grep "TPM Digest" | gawk '{ print $3}'`
				EXPECTED=`cat run.out | grep "different digest" | gawk '{ print $7 }'`
				echo "        Expected Digest: $EXPECTED"
				echo "        Actual Digest:   $ACTUAL"
				sync_auditing
			fi
		else
			if [ $ERR -eq 38 ]; then
				true
			else
				echo " WARN: Could not run 'getauditdigest'"
				dumpOutput
			fi
		fi
	fi
}

showConfigMenu ()
{
	end=0
	while [ "$end" == "0" ]; do
		echo ""
		echo ""
		echo "1. keysize (binding, signing, legacy) : $KEYSIZE"
		echo "2. keysize (storage,                ) : $KEYSIZE_ST"
		echo "3. preferred session (osap, oiap)     : $TPM_SESSION"
		echo "4. <reserved>"
		echo "5. TPM instance to test               : $TPM_INSTANCE"
		echo "6. Use 'tpminit' for resetting TPM    : $USE_TPMINIT"
		echo "7. Test for version (1.1=11,1.2=12)   : $TPM_VERSION ($LOADKEY_VERSION)"
		echo "8. Enable Transport Mode              : $TPM_TRANSPORT ($TPM_TRANSPORT_ENC)"
		echo "9. Enable auditing                    : $TPM_AUDITING"
		echo "10.Dump all requests and response     : $TPM_DUMP_COMMANDS"
		echo "11.Enable revoke EK interactive test  : $TPM_REVOKE_EK"
		echo ""
		echo "q  back to previous menu"
		read enter

		if [ "$enter" == "1" ]; then
			echo "Enter new key size for legacy, binding and signing keys:"
			read input
			input=`echo $input | tr -c -d "[:digit:]"`
			if [ $input -ge 16 ]; then
				KEYSIZE=$input
			fi
			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi
		if [ "$enter" == "2" ]; then
			echo "Enter new key size for storage keys (>= 2048):"
			read input
			input=`echo $input | tr -c -d "[:digit:]"`
			if [ $input -ge 2048 ]; then
				KEYSIZE_ST=$input
			fi
			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
			if [ $KEYSIZE_ST -lt 2048 ]; then
				KEYSIZE_ST=2048
			fi
		fi
		if [ "$enter" == "3" ]; then
			echo "Enter the preferred session (osap or oiap):"
			read input
			input=`echo "${input}" | tr "[:lower:]" "[:upper:]"`
			case "$input" in
			OIAP)  TPM_SESSION="oiap";;
			OSAP)  TPM_SESSION="osap";;
			*) echo "Invalid session type. Press enter.";
			   read enter;;
			esac
		fi
		if [ "$enter" == "4" ]; then
			true
		fi
		if [ "$enter" == "5" ]; then
			echo "Enter the TPM instance number to run the tests against"
			read TPM_INSTANCE
		fi
		if [ "$enter" == "6" ]; then
			echo "Indicate whether to use 'tpminit' for resetting the TPM"
			echo "'0' means that 'tpminit' is not to be used."
			read USE_TPMINIT
			test_tpm_init
		fi
		if [ "$enter" == "7" ]; then
			echo "Indicate for which version of the TPM to test."
			echo "(1.1=11, 1.2=12)"
			read TPM_VERSION
			LOADKEY_VERSION=""
			if [ "$TPM_VERSION" != "11" ] &&
			   [ "$TPM_VERSION" != "12" ]; then
				TPM_VERSION="11"
			fi
			test_tpm_version

			if [ "$TPM_VERSION" == "11" ]; then
				LOADKEY_VERSION="-v1"
				TPM_TRANSPORT="0"
			fi
		fi
		if [ "$enter" == "8" ]; then
			#EstablishTransport implemented?
			checkOrdImplemented 0xe6
			rc=$?
			if [ $rc -eq 0 ]; then
				echo ""
				echo "Transport not supported by TPM."
				echo ""
			else

				if [ "$TPM_TRANSPORT" == "1" ]; then
					TPM_TRANSPORT="0"
					TPM_TRANSPORT_SK=""
					TPM_TRANSPORT_EK=""
				else
					TPM_TRANSPORT="1"
				fi

				if [ "$TPM_TRANSPORT" == "1" ]; then
					while [ 1 ]; do
						echo "Choose one of the following encryption algorithms:"
						echo "1. MGF1"
						echo "2. AES128-CTR"
						echo "3. AES128-OFB"
						echo ""
						read input
						if [ "$input" == "1" ]; then
							TPM_TRANSPORT_ENC="MGF1"
							break
						elif [ "$input" == "2" ]; then
							TPM_TRANSPORT_ENC="CTR"
							break
						elif [ "$input" == "3" ]; then
							TPM_TRANSPORT_ENC="OFB"
							break
						fi
					done
				fi
			fi
		fi
		if [ "$enter" == "9" ]; then
			clearown $OWNER_PASSWORD > run.out
			tpmbios -n > run.out

			#SetOrdinalAuditStatus implemented
			checkOrdImplemented 0x8d
			rc=$?
			if [ $rc -eq 0 ]; then
				echo ""
				echo "Auditing not supported by TPM."
				echo ""
			else
				if [ "$TPM_AUDITING" == "1" ]; then
					TPM_AUDITING="0"
				else
					TPM_AUDITING="1"
					echo "enabled auditing"
					getauditdigest -s 0 > run.out
					sync_auditing
					sync_auditing
				fi
			fi
		fi

		if [ "$enter" == "10" ]; then
			if [ "$TPM_DUMP_COMMANDS" == "0" ]; then
				echo "Enabling dumping of transactions."
				TPM_DUMP_COMMANDS="1"
			else
				echo "Disabling dumping of transactions."
				TPM_DUMP_COMMANDS="0"
			fi
		fi

		if [ "$enter" == "11" ]; then
		        echo "Indicate whether to run interactive revoke EK tests"
			if [ "$TPM_REVOKE_EK" == "0" ]; then
			    echo "Enabling revoke EK tests"
			    TPM_REVOKE_EK="1"
			else
			    echo "Disabling revoke EK tests"
			    TPM_REVOKE_EK="0"
			fi
		fi

		if [ "$enter" == "q" ]; then
			if [ "$TPM_TRANSPORT" == "1" -a \
			     "$TPM_AUDITING"  == "1" ]; then
			    echo "Transport and auditing together are known to not correctly work in this"
			    echo "test environment. Some bug needs to be fixed. Press enter."
			    read
			fi
			end=1
		fi
	done
	end=0
}

needKeys ()
{
	if [ "$havekeys" == "0" ]; then
		if [ "$TPM_TRANSPORT" != "1" ]; then
			#Cannot remove the keys essential for the transport.
			evictkey all > run.out
			rm -rf /tmp/.key-*
			havekeys_tpm2=0
		fi
		echo "Need to create keys."
		takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
		createAllKeys
		havekeys=1
	fi
}

needKeys_Binding()
{
	if [ "$havekeys_binding" == "0" ]; then
		echo "Need to create additional binding keys."
		createAdditionalBindingKeys
		havekeys_binding=1
	fi
}

needKeys_Signing()
{
	if [ "$havekeys_signing" == "0" ]; then
		echo "Need to create additional signing keys."
		createAdditionalSigningKeys
		havekeys_signing=1
	fi
}

needKeys_cmk ()
{
	needKeys
	if [ "$havekeys_cmk" == "0" -a "$TPM_VERSION" != "11" ]; then
		echo "Need to create CMK keys."
		createAllKeys_CMK
		ERR=$?
		if [ $ERR -eq 0 ]; then
			havekeys_cmk=1
		fi
	fi
}

needKeys_cmk_migration ()
{
	needKeys_tpm2
	if [ "$havekeys_cmk_migration" == "0" ]; then
		echo "Creating CMK keys for migration"
		createKeysCMKMigration
		ERR=$?
		if [ $ERR -eq 0 ]; then
			havekeys_cmk_migration=1
		fi
	fi
}

needKeys_tpm2 ()
{
	### Need to create some keys on 2nd tpm
	if [ "$havekeys_tpm2" == "0" ]; then
		TPM_SERVER_NAME=$SLAVE_TPM_SERVER
		TPM_SERVER_PORT=$SLAVE_TPM_PORT

		takeTPM $TPM2_OWNER_PASSWORD $TPM2_SRK_PASSWORD $KEYSIZE_ST
		echo "Need to create keys on TPM2"
		createKeys_tpm2
		ERR=$?
		if [ $ERR -eq 0 ]; then
			havekeys_tpm2=1
		fi

		TPM_SERVER_NAME=$MASTER_TPM_SERVER
		TPM_SERVER_PORT=$MASTER_TPM_PORT
	fi
}

title ()
{
	echo "------------------------------------------"
	echo "       Beginning test $1"
	echo ""
	echo ""
}

recycleTPM ()
{
	local ima_tcb=`grep ima_tcb /proc/cmdline  2>/dev/null`
	local num_msr=`wc /sys/kernel/security/ima/ascii_runtime_measurements \
	    2>/dev/null | \
	    gawk '{print $1}'`
	if [ "$num_msr" = "" ]; then
		num_msr=0
	fi

	if [ -n "$cmdline" -o $num_msr -gt 1 ]; then
		echo
		echo "IMA may be running and cause some of the tests to fail."
		echo "Consider rebooting with IMA inactive."
		echo "If you continue, then the tests may affect IMA's"
		echo "measurement log. Reboot after running the test."
		echo
		read enter
	fi

	if [ "$USE_TPMINIT" == "0" ]; then
		if [ $INTERACTIVE -ne 0 ]; then
			echo ""
			echo "Please stop the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT and remove all"
			echo "permanent state. Then restart it."
			echo "Press enter to continue."
			read enter
		fi
	else
		tpminit > run.out
		if [ "$?" != "0" ]; then
			echo " ERROR: TPM_Init does not work on TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT."
			USE_TPMINIT=0
		fi
	fi
	TPM_TRANSPORT_EK=
	TPM_TRANSPORT_SK=
	tpmbios > run.out
	if [ "$USE_TPMINIT" == "0" ]; then
		echo ""
		echo "Please restart the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT."
		echo "Press enter to continue."
		echo ""
	else
		tpminit > run.out
		if [ "$?" != "0" ]; then
			echo " ERROR: TPM_Init does not work."
			USE_TPMINIT=0
		fi
	fi
	tpmbios > run.out
	sync_auditing
}

suspendResumeTPM ()
{
	echo "Saving TPM state."
	savestate
	ERR=$?

	if [ $ERR -eq 0 ]; then
		echo " INFO: Successfully saved the TPM's state."
	else
		echo " ERROR: Could not save the TPM's state."
		dumpOutput
	fi

	if [ "$USE_TPMINIT" == "0" ]; then
		if [ $INTERACTIVE -ne 0 ]; then
			echo ""
			echo "Please stop the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT"
			echo "Then restart it."
			echo "Press enter to continue."
			read enter
		fi
	else
		tpminit > run.out
		if [ "$?" != "0" ]; then
			echo " ERROR: TPM_Init does not work on TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT."
			USE_TPMINIT=0
		fi
	fi
	TPM_TRANSPORT_EK=
	TPM_TRANSPORT_SK=
	tpmbios -s -cs > run.out
	ERR=$?
	if [ $ERR -ne 0 ]; then
		echo " ERROR: Could not initialize communication with the TPM."
		echo "    *** Please re-cycle the TPM!! ***"
		dumpOutput
	fi
}

clean_tmp ()
{
	rm -rf /tmp/.key-*
	cd /tmp
	tmp=`ls .*transdigest* .*currentticks* 2>/dev/null`
	if [ "$tmp" != "" ]; then
		rm -rf ${tmp}
	fi
	cd - >/dev/null
}

usage()
{
	cat <<EOF
usage: $0 [options] tests

The following options are available:

--non-interactive : automatically run all tests without prompting the user
--help|-h         : display this test screen

The following test names are available:
nvram, counters, sealing, binding, signing, migration, identity, all, hwtpm

Otherwise the numbers of the tests can be used as well (1..27).

Multiple tests can be invoked by providing their names as parameter. The
tests 'all' and 'hwtpm' should only be passed without any other tests.

EOF
}

#
# Program Entry
#
main()
{
	choices=""

	# I need the constants to show the slave TPM's address
	. ./modules/test_constants

	while [ $# -ge 1 ]; do
		if [ "$1" == "nvram" ]; then
			choices="$choices 1"
		elif [ "$1" == "counters" ]; then
			choices="$choices 2"
		elif [ "$1" == "sealing" ]; then
			choices="$choices 3"
		elif [ "$1" == "binding" ]; then
			choices="$choices 4"
		elif [ "$1" == "signing" ]; then
			choices="$choices 5"
		elif [ "$1" == "migration" ]; then
			choices="$choices 6"
		elif [ "$1" == "identity" ]; then
			choices="$choices 8"
		elif [ "$1" == "all" ]; then
			choices=all
			echo "Master TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT"
			echo "Slave TPM at $SLAVE_TPM_SERVER:$SLAVE_TPM_PORT"
		elif [ "$1" == "--non-interactive" ]; then
			INTERACTIVE=0
		elif [ "$1" == "hwtpm" ]; then
			choices="$HWTPM_CHOICES"
	                USE_HWTPM="1"
		elif [ "$1" == "hwtpm-owner" ]; then
			choices="$HWTPM_CHOICES"
	                USE_HWTPM="1"
	                USE_OWNERCLEAR="0"
	        elif [ "$1" == "--help" -o "$1" == "-h" ]; then
	        	usage "$0"
	        	exit 0
		else
			choices="$1"
		fi
		shift 1
	done

	if [ -z "$choices" ]; then
		showMenu
	fi

	clean_tmp
	test_tpm_init
	test_tpm_version

	# create the test input file
	echo "input_to_test" > input

	while [ $end -eq 0 ]; do
		havekeys=0
		havekeys_cmk=0
		havekeys_cmk_migration=0
		havekeys_binding=0
		havekeys_signing=0

		. ./modules/test_auditing
		. ./modules/test_nvram
		. ./modules/test_basic
		. ./modules/test_constants
		. ./modules/test_counters
		. ./modules/test_migration
		. ./modules/test_identity
		. ./modules/test_binding
		. ./modules/test_quote
		. ./modules/test_seal
		. ./modules/test_signing
		. ./modules/test_selftest
		. ./modules/test_createkeys
		. ./modules/test_eviction
		. ./modules/test_sha
		. ./modules/test_pcr
		. ./modules/test_ticks
		. ./modules/test_context
		. ./modules/test_ownership
		. ./modules/test_capability
		. ./modules/test_maintenance
		. ./modules/test_misc
		. ./modules/test_changeauth
		. ./modules/test_delegation
		. ./modules/test_random
		. ./modules/test_vtpm
		. ./modules/test_transport
		. ./modules/test_certificates

		recycleTPM

		echo ""
		date
		echo ""
		echo "Vendor information for TPM being tested"
		getcapability -cap 0x1a
		echo ""

		for choice in $choices; do

		if [ "$choice" == "all" ]; then
			echo ""
			echo "Plese make sure that your TPM has been reset completely and all"
			echo "previous state has been removed. Some tests might otherwise fail."
			echo "Press enter to continue."
			read enter
		fi

		if [ "$TPM_AUDITING" == "1" -a "$choice" != "all" ]; then
			sync_auditing
		fi

		if [ "$choice" == "1" -o \
		     "$choice" == "all" ]; then
		     	#recycleTPM
		     	sync_auditing
			title "NVRAM"

			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doNVRAMTest

				check_audit_digest

				doNVRAMTest2_Part1

				if [ "$USE_TPMINIT" == "0" ]; then
					echo ""
					echo "Please restart the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT for 2nd part of NV-RAM test."
					echo "Please press enter to continue."
					read enter
				else
					check_audit_digest
					tpminit > run.out
					if [ "$?" != "0" ]; then
						echo " ERROR: TPM_Init does not work."
						USE_TPMINIT=0
					fi
				fi
				TPM_TRANSPORT_EK=
				TPM_TRANSPORT_SK=
				tpmbios > run.out
				sync_auditing
				doNVRAMTest2_Part2

				if [ "$USE_TPMINIT" == "0" ]; then
					echo ""
					echo "Please restart the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT."
					echo "Press enter to continue."
					read enter
				else
					check_audit_digest
					tpminit > run.out
					if [ "$?" != "0" ]; then
						echo " ERROR: TPM_Init does not work."
						USE_TPMINIT=0
					fi
				fi
				./tpmbios > run.out

				# need to re-create the transport keys (if needed)
				# after above reset
				createTransportKeys

				# NV index volatile flag interaction with ST_STATE and ST_CLEAR
				doNVSaveStateTest

				# NV index authorized by PCRs
				doNVPCRTest

				echo ""
				echo "Clearing owner"
				./clearown -pwdo $OWNER_PASSWORD > run.out
				ERR=$?
				if [ $ERR -ne 0 ]; then
					echo " ERROR: Could not properly clear the owner."
				else
					echo " INFO: Successfully cleared ownership."
				fi

				./tpmbios -n > run.out
				sync_auditing
				check_audit_digest

				doNVRAMTest_noOwner_Part1
				check_audit_digest
				if [ $? -eq 0 ]; then
					doNVRAMTest_noOwner_Part2
					check_audit_digest
				fi

			#DirWriteAuth implemented
				checkOrdImplemented 0x19
				rc=$?
				if [ $rc -eq 0 ]; then
					echo "  Skipping DIR-related test since not implemented in TPM"
				else
					doDIRTest
				fi
				check_audit_digest

				if [ "$USE_TPMINIT" == "0" ]; then
					echo ""
					echo "Please restart the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT."
					echo "Press enter to continue."
					read enter
				else
					check_audit_digest
					tpminit > run.out
					if [ "$?" != "0" ]; then
						echo " ERROR: TPM_Init does not work."
						USE_TPMINIT=0
					fi
				fi
				TPM_TRANSPORT_EK=
				TPM_TRANSPORT_SK=
				./tpmbios > run.out

				echo ""
				echo "Clearing owner"
				./clearown -pwdo $OWNER_PASSWORD > run.out
				ERR=$?
				if [ $ERR -ne 0 ]; then
					echo " ERROR: Could not properly clear the owner."
				else
					echo " INFO: Successfully cleared ownership."
				fi

				./tpmbios -n > run.out
				sync_auditing
				check_audit_digest
				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
			fi
		fi

		if [ "$choice" == "2" -o \
		     "$choice" == "all" ]; then
			title "Counters"

			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				if [ "$USE_TPMINIT" == "0" ]; then
					echo ""
					echo "Please restart the TPM at $TPM_SERVER_NAME:$TPM_SERVER_PORT for counter test."
					echo "Please press enter to continue."
					read enter
				else
					check_audit_digest
					tpminit > run.out
					if [ "$?" != "0" ]; then
						echo " ERROR: TPM_Init does not work."
						USE_TPMINIT=0
					fi
					tpmbios > run.out
					sync_auditing

				fi
				TPM_TRANSPORT_EK=
				TPM_TRANSPORT_SK=
				# need to re-create the transport keys (if needed)
				# after above reset
				createTransportKeys

				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST

				if [ $? -ne 0 ]; then
					echo "Check your TPM!"
				else
					doCounterTest
				fi
				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
			fi
		fi

		if [ "$choice" == "3" -o \
		     "$choice" == "all" ]; then
			title "Sealing"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			echo ""
			doSealFileTest

			check_audit_digest

			doSealFileTest_PCRLocking
			check_audit_digest
			if [ "$TPM_VERSION" != "11" ]; then
				checkOrdImplemented 0x3d
				rc=$?
				if [ $rc -eq 0 ]; then
					echo ""
					echo "    Skipping SealX due to missing support in TPM"
					echo ""
				else
					doSealxFileTest_PCRLocking
					check_audit_digest
					doSealxFileTest_PCRLocking_AES_CTR
					check_audit_digest
				fi
			fi

			doSealFileTest_noPwd
			check_audit_digest

	                if [ $USE_OWNERCLEAR == "1" ]; then
	                    takeTPM_noSRKPwd $KEYSIZE_ST
	                    check_audit_digest

	                    if [ $? -eq 0 ]; then
				doSealFileTest_PCRLocking_noSRKPwd
				check_audit_digest
				if [ "$TPM_VERSION" != "11" ]; then
	                            checkOrdImplemented 0x3d
	                            rc=$?
	                            if [ $rc -eq 0 ]; then
	                                echo ""
	                                echo "    Skipping SealX due to missing support in TPM"
	                                echo ""
	                            else
	                                doSealxFileTest_PCRLocking_noSRKPwd
	                                check_audit_digest
	                            fi
				fi
	                    fi
	                    echo "Clearing owner"
	                    clearown -pwdo $OWNER_PASSWORD > run.out
	                    tpmbios -n > run.out
	                fi

			sync_auditing
			check_audit_digest

			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "4" -o \
		     "$choice" == "all" ]; then
			title "Binding"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			needKeys_Binding
			echo ""
			doBindingFileTest
			doBindingFileTestPKCSV15
			check_audit_digest
		fi

		if [ "$choice" == "5" -o \
		     "$choice" == "all" ]; then
			title "Signing"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			needKeys_Signing
			echo ""
			doSignFileTest
			check_audit_digest
		fi

		if [ "$choice" == "6" -o \
		     "$choice" == "all" ]; then
			title "Migration - non-CMK keys"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			echo ""

			doMigrationTest1TPM
			check_audit_digest

			doMigrationTest1TPM_2Steps
			check_audit_digest

	                if [ "$USE_HWTPM" == "0" ]; then

	                    if [ "$TPM_TRANSPORT" != "0" ]; then
				echo ""
				echo " Turning TPM Transport usage off."
				echo ""
				TPM_TRANSPORT_REMEMBER=$TPM_TRANSPORT
				TPM_TRANSPORT="0"
	                    fi

	                    if [ "$TPM_AUDITING" != "0" ]; then
				echo ""
				echo " Turning auditing off."
				echo ""
				TPM_AUDITING_REMEMBER=$TPM_AUDITING
				TPM_AUDITING="0"
	                    fi

	                    MASTER_TPM_SERVER=$TPM_SERVER_NAME
	                    MASTER_TPM_PORT=$TPM_SERVER_PORT

	                    TPM_SERVER_NAME=$SLAVE_TPM_SERVER
	                    TPM_SERVER_PORT=$SLAVE_TPM_PORT

	                    pcrread -ix 0 > run.out
	                    ERR=$?
	                    if [ "$ERR" != "0" -a "$ERR" != "38" ]; then
				recycleTPM
	                    fi

	                    pcrread -ix 0 > run.out
	                    ERR=$?
	                    if [ "$ERR" != "0" -a "$ERR" != "38" ]; then
				echo ""
				echo "Please start the 2nd TPM now. Make sure that it is 'primed'."
				echo "Expecting 2nd TPM at $SLAVE_TPM_SERVER:$SLAVE_TPM_PORT."
				echo "Press 'enter' to continue."
				read enter
	                    fi
	                    echo "Performing some basic initilization on the 2nd TPM."

	                    sync_auditing
			    # Get the 2nd TPM.

	                    takeTPM $TPM2_OWNER_PASSWORD $TPM2_SRK_PASSWORD $KEYSIZE_ST

			    # Create keys on 2nd TPM.

	                    createKeys_tpm2
	                    check_audit_digest

	                    doMigrationTest2TPMs
	                    check_audit_digest

			    # Switch back to TPM 1
	                    TPM_SERVER_NAME=$MASTER_TPM_SERVER
	                    TPM_SERVER_PORT=$MASTER_TPM_PORT

	                    if [ "$TPM_AUDITING_REMEMBER" != "0" ]; then
				echo ""
				echo " Turning auditing on."
				TPM_AUDITING=$TPM_AUDITING_REMEMBER
				TPM_AUDITING_REMEMBER="0"
	                    fi

	                    if [ "$TPM_TRANSPORT_REMEMBER" != "0" ]; then
				echo ""
				echo " Turning TPM Transport usage on."
				echo ""
				TPM_TRANSPORT=$TPM_TRANSPORT_REMEMBER
				TPM_TRANSPORT_REMEMBER="0"
	                    fi
	                fi
			sync_auditing

			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "7" -o \
		     "$choice" == "all" ]; then
			title "Migration CMK-keys"

			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work for 1.1 TPMs"
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				needKeys
				needKeys_cmk
				echo ""

				doMigrationTest1TPM_CMK
				check_audit_digest

	                        if [ "$USE_HWTPM" == "0" ]; then

	                            MASTER_TPM_SERVER=$TPM_SERVER_NAME
	                            MASTER_TPM_PORT=$TPM_SERVER_PORT

	                            if [ "$TPM_TRANSPORT" != "0" ]; then
					echo ""
					echo " Turning TPM Transport usage off."
					echo ""
					TPM_TRANSPORT_REMEMBER=$TPM_TRANSPORT
					TPM_TRANSPORT="0"
	                            fi

	                            if [ "$TPM_AUDITING" != "0" ]; then
					echo ""
					echo " Turning auditing off."
					echo ""
					TPM_AUDITING_REMEMBER=$TPM_AUDITING
					TPM_AUDITING="0"
	                            fi

	                            sync_auditing

	                            needKeys_tpm2
	                            needKeys_cmk_migration

				    ### Need to create a special key on 1st TPM for migration
	                            needKeys_cmk_migration

	                            doMigrationTest2TPMs_CMK

	                            if [ "$TPM_AUDITING_REMEMBER" != "0" ]; then
					echo ""
					echo " Turning auditing on."
					TPM_AUDITING=$TPM_AUDITING_REMEMBER
					TPM_AUDITING_REMEMBER="0"
	                            fi

	                            sync_auditing

	                            if [ "$TPM_TRANSPORT_REMEMBER" != "0" ]; then
					echo ""
					echo " Turning TPM Transport usage on."
					echo ""
					TPM_TRANSPORT=$TPM_TRANSPORT_REMEMBER
					TPM_TRANSPORT_REMEMBER="0"
	                            fi
	                        fi

				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
				havekeys_tpm2=0
			fi
		fi

		if [ "$choice" == "8" -o \
		     "$choice" == "all" ]; then
			title "Identity"
			needKeys
			needKeys_cmk
			needKeys_Signing

			echo ""
			doIdentityTest
			check_audit_digest

			doCertifyKeyTest
			check_audit_digest

			if [ "$TPM_VERSION" != "11" ]; then
				doCertifyKeyTest_CMK
				check_audit_digest
			fi

	                if [ $USE_OWNERCLEAR == "1" ]; then
	                    takeTPM_noSRKPwd $KEYSIZE_ST

	                    if [ $? -eq 0 ]; then
				### Identity test
				doIdentityTest_noSRKPwd
				check_audit_digest
	                    else
				echo " ERROR: Could not run test."
	                    fi

	                    check_audit_digest
	                    echo "Clearing owner"
	                    ./clearown -pwdo $OWNER_PASSWORD > run.out
	                    ./tpmbios -n > run.out
	                fi
			sync_auditing
			check_audit_digest

			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "9" -o \
		     "$choice" == "all" ]; then
			title "Hashing"

			if [ "$TPM_TRANSPORT" != "0" ]; then
				echo ""
				echo " Turning TPM Transport usage off."
				echo ""
				TPM_TRANSPORT_REMEMBER=$TPM_TRANSPORT
				TPM_TRANSPORT="0"
			fi

			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			doSha1Test
			check_audit_digest

			if [ "$TPM_TRANSPORT_REMEMBER" != "0" ]; then
				echo ""
				echo " Turning TPM Transport usage on."
				echo ""
				TPM_TRANSPORT=$TPM_TRANSPORT_REMEMBER
				TPM_TRANSPORT_REMEMBER="0"
			fi
		fi

		if [ "$choice" == "10" -o \
		     "$choice" == "all" ]; then
			title "Eviction"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			echo ""
			doEvictionTest
			check_audit_digest
			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "11" -o \
		     "$choice" == "all" ]; then
			title "PCRs and Quoting"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			needKeys_cmk
			needKeys_Signing
			echo ""
			doQuoting
			check_audit_digest
			if [ "$TPM_VERSION" != "11" ]; then
				doQuoting2
				check_audit_digest
			fi
			doPCRTest
			check_audit_digest
		fi

		if [ "$choice" == "12" -o \
		     "$choice" == "all" ]; then
			title "Self Test"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			doSelfTest
			check_audit_digest
		fi

		if [ "$choice" == "13" -o \
		     "$choice" == "all" ]; then
			title "Auditing"

			checkOrdImplemented 0x85
			rc=$?
			if [ $rc -eq 0 ]; then
				echo ""
				echo "Skipping test since auditing not implemented in TPM"
				echo ""
			else
				if [ "$TPM_VERSION" == "11" ]; then
					echo " This test does not work with 1.1 TPMs"
				else
					takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
					needKeys
					needKeys_Signing
					doAuditTest
				fi
			fi
		fi

		if [ "$choice" == "14" -o \
		     "$choice" == "all" ]; then
			title "Ticks"
			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				needKeys
				needKeys_Signing
				echo ""
				doTickTest
			fi
		fi

		if [ "$choice" == "15" -o \
	             "$choice" == "all" ]; then
			title "Key Context"
			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				needKeys
				echo ""
				doKeyContextTest
				check_audit_digest
				doAuthContextTest
				check_audit_digest
				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
			fi
		fi

		if [ "$choice" == "16" -o \
	             "$choice" == "all" ]; then
			title "Changing authority/password"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			needKeys
			echo ""
			doChangeAuthTest
			check_audit_digest
			doChangeKeyAuthTest
			check_audit_digest
			doChangeSealAuthTest
			check_audit_digest
		fi

		if [ "$choice" == "17" -o \
		     "$choice" == "all" ]; then
			title "Maintenance"

			checkOrdImplemented 0x2f
			rc=$?
			if [ $rc -eq 0 ]; then
				echo ""
				echo "    Skipping Maintenance test since not supported in TPM"
				echo ""
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				needKeys
				echo ""
				doTestMaintenance
				check_audit_digest
			fi
		fi

		if [ "$choice" == "18" -o \
		     "$choice" == "all" ]; then
			title "RNG Test"
			echo ""
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			doTestRandom
			check_audit_digest
		fi

		if [ "$choice" == "19" -o \
		     "$choice" == "all" ]; then
			title "Ownership"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
			doTestOwnership
			doTestOwnershipFile
			if [ "$TPM_REVOKE_EK" == "1" ]; then
			    doTestRevEK
			fi
			havekeys=0
			havekeys_cmk=0
			havekeys_cmk_migration=0
			havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "20" -o \
		     "$choice" == "all" ]; then
		     	title "Delegation"

		     	if [ "$TPM_VERSION" == "11" ]; then
		     		echo " This test does not work with 1.1 TPMs"
		     	else
			     	takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				needKeys
				doDelegationTest
				check_audit_digest
				doDelegationTest_OwnerPointer
				check_audit_digest
			fi
		fi

		if [ "$choice" == "21" -o \
		     "$choice" == "all" ]; then
		     	title "virtual TPM"
		     	takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST

			# Since sync_auditing and enable_auditing take the global
			# onwer password OWNER_PASSWORD as parameter, I cannot run
			# the auditing when testing the vTPM instances with different
			# passwords than OWNER_PASSWORD. So I am disabling auditing for
			# this test...
		     	if [ "$TPM_AUDITING" == "1" ]; then
		     		echo
		     		echo "Temporarily deactivating auditing."
		     		echo
		     		REMEMBER_TPM_AUDITING="1"
		     		TPM_AUDITING="0"
		     	fi

		     	checkVTPM
		     	RET=$?
		     	if [ "$RET" == "0" ]; then
		     		echo " WARN: Skipping test because this is not a VTPM."
		     	else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doTest_vTPM
				doTest_ExtendNotification
			fi

			if [ "$REMEMBER_TPM_AUDITING" == "1" ]; then
				TPM_AUDITING="1"
				REMEMBER_TPM_AUDITING="0"
			fi
		fi

		if [ "$choice" == "22" -o \
		     "$choice" == "all" ]; then
		     	title "TPM Migration"

		     	checkVTPM
		     	RET=$?
		     	if [ "$RET" == "0" ]; then
		     		echo " WARN: Skipping test because this is not a VTPM."
		     	else
				if [ "$TPM_TRANSPORT" != "0" ]; then
					echo ""
					echo " Turning (global) TPM Transport usage off."
					echo ""
					TPM_TRANSPORT_REMEMBER=$TPM_TRANSPORT
					TPM_TRANSPORT="0"
				fi

				echo "Recycling the master TPM"
				recycleTPM
				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST

				echo "Recycling the 2nd TPM."
				MASTER_TPM_SERVER=$TPM_SERVER_NAME
				MASTER_TPM_PORT=$TPM_SERVER_PORT

				TPM_SERVER_NAME=$SLAVE_TPM_SERVER
				TPM_SERVER_PORT=$SLAVE_TPM_PORT
				recycleTPM
				havekeys_tpm2=0
				sync_auditing
				takeTPM $TPM2_OWNER_PASSWORD $TPM2_SRK_PASSWORD $KEYSIZE_ST

				TPM_SERVER_NAME=$MASTER_TPM_SERVER
				TPM_SERVER_PORT=$MASTER_TPM_PORT
				doMigrate_MigrateVTPM
				havekeys=0
				havekeys_cmk=0
				havekeys_cmk_migration=0
				havekeys_binding=0
				havekeys_signing=0
				havekeys_tpm2=0
				TPM_SERVER_NAME=$MASTER_TPM_SERVER
				TPM_SERVER_PORT=$MASTER_TPM_PORT
				sync_auditing

				if [ "$TPM_TRANSPORT_REMEMBER" != "0" ]; then
					echo ""
					echo " Turning TPM Transport usage on."
					echo ""
					TPM_TRANSPORT=$TPM_TRANSPORT_REMEMBER
					TPM_TRANSPORT_REMEMBER="0"
				fi

			fi
		fi

		if [ "$choice" == "23" -o \
		     "$choice" == "all" ]; then
			title "Transport"

			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else

				if [ "$TPM_TRANSPORT" != "0" ]; then
					echo ""
					echo " Turning (global) TPM Transport usage off."
					echo ""
					TPM_TRANSPORT_REMEMBER=$TPM_TRANSPORT
					TPM_TRANSPORT="0"
				fi

				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doTransportTest
				check_audit_digest

				if [ "$TPM_TRANSPORT_REMEMBER" != "0" ]; then
					echo ""
					echo " Turning TPM Transport usage on."
					echo ""
					TPM_TRANSPORT=$TPM_TRANSPORT_REMEMBER
					TPM_TRANSPORT_REMEMBER="0"
					sync_auditing
				fi
			fi
		fi

		if [ "$choice" == "24" -o \
		     "$choice" == "all" ]; then
			title "Misc"
			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doMiscTest
				check_audit_digest

				echo "Clearing owner"
				./clearown -pwdo $OWNER_PASSWORD > run.out
				./tpmbios -n > run.out
				sync_auditing
				check_audit_digest

				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doPhysPresenceTest
				check_audit_digest

				echo "Clearing owner"
				./clearown -pwdo $OWNER_PASSWORD > run.out
				./tpmbios -n > run.out
				sync_auditing
				recycleTPM

				takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST
				doSuspendResumeTest
				recycleTPM
			fi
		fi

		if [ "$choice" == "25" -o \
		     "$choice" == "all" ]; then
			title "Capability"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST

			if [ "$havekeys" == "1" -a \
			     "$choice" != "all" -a \
			     "$TPM_VERSION" == "11" ]; then
				doTestGetCapability "-hk $SIGNINGKEY_HANDLE -pwdk $SIGNINGKEY_PASSWORD"
				check_audit_digest
			else
				doTestGetCapability
				check_audit_digest
			fi
			check_audit_digest
			havekeys=0
		     	havekeys_cmk=0
		     	havekeys_cmk_migration=0
		     	havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "26" ]; then
			title "Capability (needs reset of TPM afterwards)"
			takeTPM $OWNER_PASSWORD $SRK_PASSWORD $KEYSIZE_ST

			if [ "$havekeys" == "1" -a \
			     "$choice" != "all" -a \
			     "$TPM_VERSION" == "11" ]; then
				doTestGetCapability "-hk $SIGNINGKEY_HANDLE -pwdk $SIGNINGKEY_PASSWORD"
				check_audit_digest
				if [ "$TPM_VERSION" != "11" ]; then
					doTestSetCapability $OWNER_PASSWORD
					check_audit_digest
				fi
			else
				doTestGetCapability
				check_audit_digest
				if [ "$TPM_VERSION" != "11" ]; then
					doTestSetCapability $OWNER_PASSWORD
					check_audit_digest
				fi
			fi
			check_audit_digest
			if [ "$USE_TPMINIT" != "0" ]; then
				tpminit
				if [ "$?" != "0" ]; then
					echo " ERROR: TPM_Init does not work."
					USE_TPMINIT=0
				fi
				./tpmbios > run.out
				TPM_TRANSPORT_EK=
				TPM_TRANSPORT_SK=
			fi
			sync_auditing
			check_audit_digest
			havekeys=0
		     	havekeys_cmk=0
		     	havekeys_cmk_migration=0
		     	havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "27" ]; then
		     	title "Recycling TPM"
		     	recycleTPM
		     	havekeys=0
		     	havekeys_cmk=0
		     	havekeys_cmk_migration=0
		     	havekeys_binding=0
			havekeys_signing=0
		fi

		if [ "$choice" == "28" -o \
		     "$choice" == "all" ]; then
			title "Certificates"
			if [ "$TPM_VERSION" == "11" ]; then
				echo " This test does not work with 1.1 TPMs"
			else
				echo ""
				doCertificatesTest
			fi
		fi
		if [ "$choice" == "conf" ]; then
			showConfigMenu
		fi

		if [ "$choice" == "quit" ]; then
			end=1
		fi

		done

		[ $INTERACTIVE -eq 0 ] && end=1

		choice=none
		if [ "$end" == "0" ]; then
			showMenu
		fi
	done
}

main "$@"


text:
__version__ = "2022.4.2"
__doc_title__ = "Quaternion dtype for NumPy"
__doc__ = "Adds a quaternion dtype to NumPy."
__all__ = ['quaternion',
           'as_quat_array', 'as_spinor_array',
           'as_float_array', 'from_float_array',
           'as_vector_part', 'from_vector_part',
           'as_rotation_matrix', 'from_rotation_matrix',
           'as_rotation_vector', 'from_rotation_vector',
           'as_euler_angles', 'from_euler_angles',
           'as_spherical_coords', 'from_spherical_coords',
           'rotate_vectors', 'allclose',
           'rotor_intrinsic_distance', 'rotor_chordal_distance',
           'rotation_intrinsic_distance', 'rotation_chordal_distance',
           'slerp_evaluate', 'squad_evaluate',
           'zero', 'one', 'x', 'y', 'z', 'integrate_angular_velocity',
           'squad', 'slerp', 'derivative', 'definite_integral', 'indefinite_integral']

import numpy as np

from .numpy_quaternion import (
    quaternion, _eps, slerp_evaluate, squad_evaluate,
    # slerp_vectorized, squad_vectorized, slerp, squad,
)
from .quaternion_time_series import (
    unflip_rotors, slerp, squad, integrate_angular_velocity, minimal_rotation, angular_velocity,
)
from .calculus import (
    derivative, antiderivative, definite_integral, indefinite_integral,
    fd_derivative, fd_definite_integral, fd_indefinite_integral,
    spline_derivative, spline_definite_integral, spline_indefinite_integral,
)
try:
    from .calculus import spline
except:
    pass
from .means import (
    mean_rotor_in_chordal_metric,
    optimal_alignment_in_chordal_metric,
    optimal_alignment_in_Euclidean_metric
)

np.quaternion = quaternion
np.sctypeDict['quaternion'] = np.dtype(quaternion)

zero = np.quaternion(0, 0, 0, 0)
one = np.quaternion(1, 0, 0, 0)
x = np.quaternion(0, 1, 0, 0)
y = np.quaternion(0, 0, 1, 0)
z = np.quaternion(0, 0, 0, 1)

rotor_intrinsic_distance = np.rotor_intrinsic_distance
rotor_chordal_distance = np.rotor_chordal_distance
rotation_intrinsic_distance = np.rotation_intrinsic_distance
rotation_chordal_distance = np.rotation_chordal_distance

def as_float_array(a):
    """View the quaternion array as an array of floats

    This function is fast (of order 1 microsecond) because no data is
    copied; the returned quantity is just a "view" of the original.

    The output view has one more dimension (of size 4) than the input
    array, but is otherwise the same shape.  The components along
    that last dimension represent the scalar and vector components of
    each quaternion in that order: `w`, `x`, `y`, `z`.

    """
    return np.asarray(a, dtype=np.quaternion).view((np.double, 4))

def as_quat_array(a):
    """View a float array as an array of quaternions

    The input array must have a final dimension whose size is
    divisible by four (or better yet *is* 4), because successive
    indices in that last dimension will be considered successive
    components of the output quaternion.  Each set of 4 components
    will be interpreted as the scalar and vector components of a
    quaternion in that order: `w`, `x`, `y`, `z`.

    This function is usually fast (of order 1 microsecond) because no
    data is copied; the returned quantity is just a "view" of the
    original.  However, if the input array is not C-contiguous
    (basically, as you increment the index into the last dimension of
    the array, you just move to the neighboring float in memory), the
    data will need to be copied which may be quite slow.  Therefore,
    you should try to ensure that the input array is in that order.
    Slices and transpositions will frequently break that rule.

    We will not convert back from a two-spinor array because there is
    no unique convention for them, so I don't want to mess with that.
    Also, we want to discourage users from the slow, memory-copying
    process of swapping columns required for useful definitions of
    the two-spinors.

    """
    a = np.asarray(a, dtype=np.double)

    # fast path
    if a.shape == (4,):
        return quaternion(a[0], a[1], a[2], a[3])

    # view only works if the last axis is C-contiguous
    if not a.flags['C_CONTIGUOUS'] or a.strides[-1] != a.itemsize:
        a = a.copy(order='C')
    try:
        av = a.view(np.quaternion)
    except ValueError as e:
        message = (str(e) + '\n            '
                   + 'Failed to view input data as a series of quaternions.  '
                   + 'Please ensure that the last dimension has size divisible by 4.\n            '
                   + 'Input data has shape {0} and dtype {1}.'.format(a.shape, a.dtype))
        raise ValueError(message)

    # special case: don't create an axis for a single quaternion, to
    # match the output of `as_float_array`
    if av.shape[-1] == 1:
        av = av.reshape(a.shape[:-1])

    return av

def from_float_array(a):
    return as_quat_array(a)

def from_vector_part(v, vector_axis=-1):
    """Create a quaternion array from an array of the vector parts.

    Essentially, this just inserts a 0 in front of each vector part, and
    re-interprets the result as a quaternion.

    Parameters
    ----------
    v : array_like
        Array of vector parts of quaternions.  When interpreted as a numpy array,
        if the dtype is `quaternion`, the array is returned immediately, and the
        following argument is ignored.  Otherwise, it it must be a float array with
        dimension `vector_axis` of size 3 or 4.
    vector_axis : int, optional
        The axis to interpret as containing the vector components.  The default is
        -1.

    Returns
    -------
    q : array of quaternions
        Quaternions with vector parts corresponding to input vectors.

    """
    v = np.asarray(v)
    if v.dtype != np.quaternion:
        input_shape = v.shape
        if vector_axis != -1:
            v = np.moveaxis(v, vector_axis, -1)
        if v.shape[-1] == 3:
            v = from_float_array(np.insert(v, 0, 0.0, axis=-1))
        elif v.shape[-1] == 4:
            v = v.copy()
            v[..., 0] = 0.0
            v = from_float_array(v)
        else:
            raise ValueError(
                "Vector input has shape {0}, which cannot be interpreted as quaternions ".format(input_shape)
                + "with vector axis {0}".format(vector_axis)
            )
    return v

def as_vector_part(q):
    """Create an array of vector parts from an array of quaternions.

    Parameters
    ----------
    q : quaternion array_like
        Array of quaternions.

    Returns
    -------
    v : array
        Float array of shape `q.shape + (3,)`

    """
    q = np.asarray(q, dtype=np.quaternion)
    return as_float_array(q)[..., 1:]

def as_spinor_array(a):
    """View a quaternion array as spinors in two-complex representation

    This function is relatively slow and scales poorly, because memory
    copying is apparently involved -- I think it's due to the
    "advanced indexing" required to swap the columns.

    """
    a = np.atleast_1d(a)
    assert a.dtype == np.dtype(np.quaternion)
    # I'm not sure why it has to be so complicated, but all of these steps
    # appear to be necessary in this case.
    return a.view(np.float64).reshape(a.shape + (4,))[..., [0, 3, 2, 1]].ravel().view(np.complex128).reshape(a.shape + (2,))

def as_rotation_matrix(q):
    """Convert input quaternion to 3x3 rotation matrix

    For any quaternion `q`, this function returns a matrix `m` such that, for every
    vector `v`, we have

        m @ v.vec == q * v * q.conjugate()

    Here, `@` is the standard python matrix multiplication operator and `v.vec` is
    the 3-vector part of the quaternion `v`.

    Parameters
    ----------
    q : quaternion or array of quaternions
        The quaternion(s) need not be normalized, but must all be nonzero

    Returns
    -------
    m : float array
        Output shape is q.shape+(3,3).  This matrix should multiply (from
        the left) a column vector to produce the rotated column vector.

    Raises
    ------
    ZeroDivisionError
        If any of the input quaternions have norm 0.0.

    """
    if q.shape == () and not isinstance(q, np.ndarray):  # This is just a single quaternion
        n = q.norm()
        if n == 0.0:
            raise ZeroDivisionError("Input to `as_rotation_matrix({0})` has zero norm".format(q))
        elif abs(n-1.0) < _eps:  # Input q is basically normalized
            return np.array([
                [1 - 2*(q.y**2 + q.z**2),   2*(q.x*q.y - q.z*q.w),      2*(q.x*q.z + q.y*q.w)],
                [2*(q.x*q.y + q.z*q.w),     1 - 2*(q.x**2 + q.z**2),    2*(q.y*q.z - q.x*q.w)],
                [2*(q.x*q.z - q.y*q.w),     2*(q.y*q.z + q.x*q.w),      1 - 2*(q.x**2 + q.y**2)]
            ])
        else:  # Input q is not normalized
            return np.array([
                [1 - 2*(q.y**2 + q.z**2)/n,   2*(q.x*q.y - q.z*q.w)/n,      2*(q.x*q.z + q.y*q.w)/n],
                [2*(q.x*q.y + q.z*q.w)/n,     1 - 2*(q.x**2 + q.z**2)/n,    2*(q.y*q.z - q.x*q.w)/n],
                [2*(q.x*q.z - q.y*q.w)/n,     2*(q.y*q.z + q.x*q.w)/n,      1 - 2*(q.x**2 + q.y**2)/n]
            ])
    else:  # This is an array of quaternions
        n = np.norm(q)
        if np.any(n == 0.0):
            raise ZeroDivisionError("Array input to `as_rotation_matrix` has at least one element with zero norm")
        else:  # Assume input q is not normalized
            m = np.empty(q.shape + (3, 3))
            q = as_float_array(q)
            m[..., 0, 0] = 1.0 - 2*(q[..., 2]**2 + q[..., 3]**2)/n
            m[..., 0, 1] = 2*(q[..., 1]*q[..., 2] - q[..., 3]*q[..., 0])/n
            m[..., 0, 2] = 2*(q[..., 1]*q[..., 3] + q[..., 2]*q[..., 0])/n
            m[..., 1, 0] = 2*(q[..., 1]*q[..., 2] + q[..., 3]*q[..., 0])/n
            m[..., 1, 1] = 1.0 - 2*(q[..., 1]**2 + q[..., 3]**2)/n
            m[..., 1, 2] = 2*(q[..., 2]*q[..., 3] - q[..., 1]*q[..., 0])/n
            m[..., 2, 0] = 2*(q[..., 1]*q[..., 3] - q[..., 2]*q[..., 0])/n
            m[..., 2, 1] = 2*(q[..., 2]*q[..., 3] + q[..., 1]*q[..., 0])/n
            m[..., 2, 2] = 1.0 - 2*(q[..., 1]**2 + q[..., 2]**2)/n
            return m

def from_rotation_matrix(rot, nonorthogonal=True):
    """Convert input 3x3 rotation matrix to unit quaternion

    For any orthogonal matrix `rot`, this function returns a quaternion `q` such
    that, for every pure-vector quaternion `v`, we have

        q * v * q.conjugate() == rot @ v.vec

    Here, `@` is the standard python matrix multiplication operator and `v.vec` is
    the 3-vector part of the quaternion `v`.  If `rot` is not orthogonal the
    "closest" orthogonal matrix is used; see Notes below.

    Parameters
    ----------
    rot : (..., N, 3, 3) float array
        Each 3x3 matrix represents a rotation by multiplying (from the left) a
        column vector to produce a rotated column vector.  Note that this input may
        actually have ndims>3; it is just assumed that the last two dimensions have
        size 3, representing the matrix.
    nonorthogonal : bool, optional
        If scipy.linalg is available, use the more robust algorithm of Bar-Itzhack.
        Default value is True.

    Returns
    -------
    q : array of quaternions
        Unit quaternions resulting in rotations corresponding to input rotations.
        Output shape is rot.shape[:-2].

    Raises
    ------
    LinAlgError
        If any of the eigenvalue solutions does not converge

    Notes
    -----
    By default, if scipy.linalg is available, this function uses Bar-Itzhack's
    algorithm to allow for non-orthogonal matrices.  [J. Guidance, Vol. 23, No. 6,
    p. 1085 <http://dx.doi.org/10.2514/2.4654>] This will almost certainly be quite
    a bit slower than simpler versions, though it will be more robust to numerical
    errors in the rotation matrix.  Also note that Bar-Itzhack uses some pretty
    weird conventions.  The last component of the quaternion appears to represent
    the scalar, and the quaternion itself is conjugated relative to the convention
    used throughout this module.

    If scipy.linalg is not available or if the optional `nonorthogonal` parameter
    is set to `False`, this function falls back to the possibly faster, but less
    robust, algorithm of Markley [J. Guidance, Vol. 31, No. 2, p. 440
    <http://dx.doi.org/10.2514/1.31730>].

    """
    try:
        from scipy import linalg
    except ImportError:
        linalg = False

    rot = np.array(rot, copy=False)
    shape = rot.shape[:-2]

    if linalg and nonorthogonal:
        from operator import mul
        from functools import reduce

        K3 = np.empty(shape+(4, 4))
        K3[..., 0, 0] = (rot[..., 0, 0] - rot[..., 1, 1] - rot[..., 2, 2])/3.0
        K3[..., 0, 1] = (rot[..., 1, 0] + rot[..., 0, 1])/3.0
        K3[..., 0, 2] = (rot[..., 2, 0] + rot[..., 0, 2])/3.0
        K3[..., 0, 3] = (rot[..., 1, 2] - rot[..., 2, 1])/3.0
        K3[..., 1, 0] = K3[..., 0, 1]
        K3[..., 1, 1] = (rot[..., 1, 1] - rot[..., 0, 0] - rot[..., 2, 2])/3.0
        K3[..., 1, 2] = (rot[..., 2, 1] + rot[..., 1, 2])/3.0
        K3[..., 1, 3] = (rot[..., 2, 0] - rot[..., 0, 2])/3.0
        K3[..., 2, 0] = K3[..., 0, 2]
        K3[..., 2, 1] = K3[..., 1, 2]
        K3[..., 2, 2] = (rot[..., 2, 2] - rot[..., 0, 0] - rot[..., 1, 1])/3.0
        K3[..., 2, 3] = (rot[..., 0, 1] - rot[..., 1, 0])/3.0
        K3[..., 3, 0] = K3[..., 0, 3]
        K3[..., 3, 1] = K3[..., 1, 3]
        K3[..., 3, 2] = K3[..., 2, 3]
        K3[..., 3, 3] = (rot[..., 0, 0] + rot[..., 1, 1] + rot[..., 2, 2])/3.0

        if not shape:
            q = zero.copy()
            eigvals, eigvecs = linalg.eigh(K3.T, eigvals=(3, 3))
            q.components[0] = eigvecs[-1]
            q.components[1:] = -eigvecs[:-1].flatten()
            return q
        else:
            q = np.empty(shape+(4,), dtype=np.float64)
            for flat_index in range(reduce(mul, shape)):
                multi_index = np.unravel_index(flat_index, shape)
                eigvals, eigvecs = linalg.eigh(K3[multi_index], eigvals=(3, 3))
                q[multi_index+(0,)] = eigvecs[-1]
                q[multi_index+(slice(1,None),)] = -eigvecs[:-1].flatten()
            return as_quat_array(q)

    else:  # No scipy.linalg or not `nonorthogonal`
        diagonals = np.empty(shape+(4,))
        diagonals[..., 0] = rot[..., 0, 0]
        diagonals[..., 1] = rot[..., 1, 1]
        diagonals[..., 2] = rot[..., 2, 2]
        diagonals[..., 3] = rot[..., 0, 0] + rot[..., 1, 1] + rot[..., 2, 2]

        indices = np.argmax(diagonals, axis=-1)

        q = diagonals  # reuse storage space
        indices_i = (indices == 0)
        if np.any(indices_i):
            if indices_i.shape == ():
                indices_i = Ellipsis
            rot_i = rot[indices_i, :, :]
            q[indices_i, 0] = rot_i[..., 2, 1] - rot_i[..., 1, 2]
            q[indices_i, 1] = 1 + rot_i[..., 0, 0] - rot_i[..., 1, 1] - rot_i[..., 2, 2]
            q[indices_i, 2] = rot_i[..., 0, 1] + rot_i[..., 1, 0]
            q[indices_i, 3] = rot_i[..., 0, 2] + rot_i[..., 2, 0]
        indices_i = (indices == 1)
        if np.any(indices_i):
            if indices_i.shape == ():
                indices_i = Ellipsis
            rot_i = rot[indices_i, :, :]
            q[indices_i, 0] = rot_i[..., 0, 2] - rot_i[..., 2, 0]
            q[indices_i, 1] = rot_i[..., 1, 0] + rot_i[..., 0, 1]
            q[indices_i, 2] = 1 - rot_i[..., 0, 0] + rot_i[..., 1, 1] - rot_i[..., 2, 2]
            q[indices_i, 3] = rot_i[..., 1, 2] + rot_i[..., 2, 1]
        indices_i = (indices == 2)
        if np.any(indices_i):
            if indices_i.shape == ():
                indices_i = Ellipsis
            rot_i = rot[indices_i, :, :]
            q[indices_i, 0] = rot_i[..., 1, 0] - rot_i[..., 0, 1]
            q[indices_i, 1] = rot_i[..., 2, 0] + rot_i[..., 0, 2]
            q[indices_i, 2] = rot_i[..., 2, 1] + rot_i[..., 1, 2]
            q[indices_i, 3] = 1 - rot_i[..., 0, 0] - rot_i[..., 1, 1] + rot_i[..., 2, 2]
        indices_i = (indices == 3)
        if np.any(indices_i):
            if indices_i.shape == ():
                indices_i = Ellipsis
            rot_i = rot[indices_i, :, :]
            q[indices_i, 0] = 1 + rot_i[..., 0, 0] + rot_i[..., 1, 1] + rot_i[..., 2, 2]
            q[indices_i, 1] = rot_i[..., 2, 1] - rot_i[..., 1, 2]
            q[indices_i, 2] = rot_i[..., 0, 2] - rot_i[..., 2, 0]
            q[indices_i, 3] = rot_i[..., 1, 0] - rot_i[..., 0, 1]

        q /= np.linalg.norm(q, axis=-1)[..., np.newaxis]

        return as_quat_array(q)

def as_rotation_vector(q):
    """Convert input quaternion to the axis-angle representation

    Note that if any of the input quaternions has norm zero, no error is
    raised, but NaNs will appear in the output.

    Parameters
    ----------
    q : quaternion or array of quaternions
        The quaternion(s) need not be normalized, but must all be nonzero

    Returns
    -------
    rot : float array
        Output shape is q.shape+(3,).  Each vector represents the axis of
        the rotation, with norm proportional to the angle of the rotation in
        radians.

    """
    return as_float_array(2*np.log(np.normalized(q)))[..., 1:]

def from_rotation_vector(rot):
    """Convert input 3-vector in axis-angle representation to unit quaternion

    Parameters
    ----------
    rot : (Nx3) float array
        Each vector represents the axis of the rotation, with norm
        proportional to the angle of the rotation in radians.

    Returns
    -------
    q : array of quaternions
        Unit quaternions resulting in rotations corresponding to input
        rotations.  Output shape is rot.shape[:-1].

    """
    rot = np.array(rot, copy=False)
    quats = np.zeros(rot.shape[:-1]+(4,))
    quats[..., 1:] = rot[...]/2
    quats = as_quat_array(quats)
    return np.exp(quats)

def as_euler_angles(q):
    """Open Pandora's Box

    If somebody is trying to make you use Euler angles, tell them no, and
    walk away, and go and tell your mum.

    You don't want to use Euler angles.  They are awful.  Stay away.  It's
    one thing to convert from Euler angles to quaternions; at least you're
    moving in the right direction.  But to go the other way?!  It's just not
    right.

    Assumes the Euler angles correspond to the quaternion R via

        R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)

    The angles are naturally in radians.

    NOTE: Before opening an issue reporting something "wrong" with this
    function, be sure to read all of the following page, *especially* the
    very last section about opening issues or pull requests.
    <https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>

    Parameters
    ----------
    q : quaternion or array of quaternions
        The quaternion(s) need not be normalized, but must all be nonzero

    Returns
    -------
    alpha_beta_gamma : float array
        Output shape is q.shape+(3,).  These represent the angles (alpha,
        beta, gamma) in radians, where the normalized input quaternion
        represents `exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)`.

    Raises
    ------
    AllHell
        ...if you try to actually use Euler angles, when you could have
        been using quaternions like a sensible person.

    """
    alpha_beta_gamma = np.empty(q.shape + (3,), dtype=np.float64)
    n = np.norm(q)
    q = as_float_array(q)
    alpha_beta_gamma[..., 0] = np.arctan2(q[..., 3], q[..., 0]) + np.arctan2(-q[..., 1], q[..., 2])
    alpha_beta_gamma[..., 1] = 2*np.arccos(np.sqrt((q[..., 0]**2 + q[..., 3]**2)/n))
    alpha_beta_gamma[..., 2] = np.arctan2(q[..., 3], q[..., 0]) - np.arctan2(-q[..., 1], q[..., 2])
    return alpha_beta_gamma

def from_euler_angles(alpha_beta_gamma, beta=None, gamma=None):
    """Improve your life drastically

    Assumes the Euler angles correspond to the quaternion R via

        R = exp(alpha*z/2) * exp(beta*y/2) * exp(gamma*z/2)

    The angles naturally must be in radians for this to make any sense.

    NOTE: Before opening an issue reporting something "wrong" with this
    function, be sure to read all of the following page, *especially* the
    very last section about opening issues or pull requests.
    <https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible>

    Parameters
    ----------
    alpha_beta_gamma : float or array of floats
        This argument may either contain an array with last dimension of
        size 3, where those three elements describe the (alpha, beta, gamma)
        radian values for each rotation; or it may contain just the alpha
        values, in which case the next two arguments must also be given.
    beta : None, float, or array of floats
        If this array is given, it must be able to broadcast against the
        first and third arguments.
    gamma : None, float, or array of floats
        If this array is given, it must be able to broadcast against the
        first and second arguments.

    Returns
    -------
    R : quaternion array
        The shape of this array will be the same as the input, except that
        the last dimension will be removed.

    """
    # Figure out the input angles from either type of input
    if gamma is None:
        alpha_beta_gamma = np.asarray(alpha_beta_gamma, dtype=np.double)
        alpha = alpha_beta_gamma[..., 0]
        beta  = alpha_beta_gamma[..., 1]
        gamma = alpha_beta_gamma[..., 2]
    else:
        alpha = np.asarray(alpha_beta_gamma, dtype=np.double)
        beta  = np.asarray(beta, dtype=np.double)
        gamma = np.asarray(gamma, dtype=np.double)

    # Set up the output array
    R = np.empty(np.broadcast(alpha, beta, gamma).shape + (4,), dtype=np.double)

    # Compute the actual values of the quaternion components
    R[..., 0] =  np.cos(beta/2)*np.cos((alpha+gamma)/2)  # scalar quaternion components
    R[..., 1] = -np.sin(beta/2)*np.sin((alpha-gamma)/2)  # x quaternion components
    R[..., 2] =  np.sin(beta/2)*np.cos((alpha-gamma)/2)  # y quaternion components
    R[..., 3] =  np.cos(beta/2)*np.sin((alpha+gamma)/2)  # z quaternion components

    return as_quat_array(R)

def as_spherical_coords(q):
    """Return the spherical coordinates corresponding to this quaternion

    Obviously, spherical coordinates do not contain as much information as a
    quaternion, so this function does lose some information.  However, the
    returned spherical coordinates will represent the point(s) on the sphere
    to which the input quaternion(s) rotate the z axis.

    Parameters
    ----------
    q : quaternion or array of quaternions
        The quaternion(s) need not be normalized, but must be nonzero

    Returns
    -------
    vartheta_varphi : float array
        Output shape is q.shape+(2,).  These represent the angles (vartheta,
        varphi) in radians, where the normalized input quaternion represents
        `exp(varphi*z/2) * exp(vartheta*y/2)`, up to an arbitrary inital
        rotation about `z`.

    """
    return as_euler_angles(q)[..., 1::-1]

def from_spherical_coords(theta_phi, phi=None):
    """Return the quaternion corresponding to these spherical coordinates

    Assumes the spherical coordinates correspond to the quaternion R via

        R = exp(phi*z/2) * exp(theta*y/2)

    The angles naturally must be in radians for this to make any sense.

    Note that this quaternion rotates `z` onto the point with the given
    spherical coordinates, but also rotates `x` and `y` onto the usual basis
    vectors (theta and phi, respectively) at that point.

    Parameters
    ----------
    theta_phi : float or array of floats
        This argument may either contain an array with last dimension of
        size 2, where those two elements describe the (theta, phi) values in
        radians for each point; or it may contain just the theta values in
        radians, in which case the next argument must also be given.
    phi : None, float, or array of floats
        If this array is given, it must be able to broadcast against the
        first argument.

    Returns
    -------
    R : quaternion array
        If the second argument is not given to this function, the shape
        will be the same as the input shape except for the last dimension,
        which will be removed.  If the second argument is given, this
        output array will have the shape resulting from broadcasting the
        two input arrays against each other.

    """
    # Figure out the input angles from either type of input
    if phi is None:
        theta_phi = np.asarray(theta_phi, dtype=np.double)
        theta = theta_phi[..., 0]
        phi  = theta_phi[..., 1]
    else:
        theta = np.asarray(theta_phi, dtype=np.double)
        phi = np.asarray(phi, dtype=np.double)

    # Set up the output array
    R = np.empty(np.broadcast(theta, phi).shape + (4,), dtype=np.double)

    # Compute the actual values of the quaternion components
    R[..., 0] =  np.cos(phi/2)*np.cos(theta/2)  # scalar quaternion components
    R[..., 1] = -np.sin(phi/2)*np.sin(theta/2)  # x quaternion components
    R[..., 2] =  np.cos(phi/2)*np.sin(theta/2)  # y quaternion components
    R[..., 3] =  np.sin(phi/2)*np.cos(theta/2)  # z quaternion components

    return as_quat_array(R)

def rotate_vectors(R, v, axis=-1):
    """Rotate vectors by given quaternions

    This function is for the case where each quaternion (possibly the only input
    quaternion) is used to rotate multiple vectors.  If each quaternion is only
    rotating a single vector, it is more efficient to use the standard formula

        vprime = R * v * R.conjugate()

    (Note that `from_vector_part` and `as_vector_part` may be helpful.)

    Parameters
    ----------
    R : quaternion array
        Quaternions by which to rotate the input vectors
    v : float array
        Three-vectors to be rotated.
    axis : int
        Axis of the `v` array to use as the vector dimension.  This
        axis of `v` must have length 3.

    Returns
    -------
    vprime : float array
        The rotated vectors.  This array has shape R.shape+v.shape.

    Notes
    -----
    For simplicity, this function converts the input quaternion(s) to matrix form,
    and rotates the input vector(s) by the usual matrix multiplication.  As noted
    above, if each input quaternion is only used to rotate a single vector, this is
    not the most efficient approach.  The simple formula shown above is faster than
    this function, though it should be noted that the most efficient approach (in
    terms of operation counts) is to use the formula

      v' = v + 2 * r x (s * v + r x v) / m

    where x represents the cross product, s and r are the scalar and vector parts
    of the quaternion, respectively, and m is the sum of the squares of the
    components of the quaternion.  If you are looping over a very large number of
    quaternions, and just rotating a single vector each time, you might want to
    implement that alternative algorithm using numba (or something that doesn't use
    python).

    """
    R = np.asarray(R, dtype=np.quaternion)
    v = np.asarray(v, dtype=float)
    if v.ndim < 1 or 3 not in v.shape:
        raise ValueError("Input `v` does not have at least one dimension of length 3")
    if v.shape[axis] != 3:
        raise ValueError("Input `v` axis {0} has length {1}, not 3.".format(axis, v.shape[axis]))
    m = as_rotation_matrix(R)
    tensordot_axis = m.ndim-2
    final_axis = tensordot_axis + (axis % v.ndim)
    return np.moveaxis(
        np.tensordot(m, v, axes=(-1, axis)),
        tensordot_axis, final_axis
    )

def isclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False):
    """
    Returns a boolean array where two arrays are element-wise equal within a
    tolerance.

    This function is essentially a copy of the `numpy.isclose` function,
    with different default tolerances and one minor changes necessary to
    deal correctly with quaternions.

    The tolerance values are positive, typically very small numbers.  The
    relative difference (`rtol` * abs(`b`)) and the absolute difference
    `atol` are added together to compare against the absolute difference
    between `a` and `b`.

    Parameters
    ----------
    a, b : array_like
        Input arrays to compare.
    rtol : float
        The relative tolerance parameter (see Notes).
    atol : float
        The absolute tolerance parameter (see Notes).
    equal_nan : bool
        Whether to compare NaN's as equal.  If True, NaN's in `a` will be
        considered equal to NaN's in `b` in the output array.

    Returns
    -------
    y : array_like
        Returns a boolean array of where `a` and `b` are equal within the
        given tolerance. If both `a` and `b` are scalars, returns a single
        boolean value.

    See Also
    --------
    allclose

    Notes
    -----
    For finite values, isclose uses the following equation to test whether
    two floating point values are equivalent:

      absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

    The above equation is not symmetric in `a` and `b`, so that
    `isclose(a, b)` might be different from `isclose(b, a)` in
    some rare cases.

    Examples
    --------
    >>> quaternion.isclose([1e10*quaternion.x, 1e-7*quaternion.y], [1.00001e10*quaternion.x, 1e-8*quaternion.y],
    ...     rtol=1.e-5, atol=1.e-8)
    array([True, False])
    >>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.00001e10*quaternion.x, 1e-9*quaternion.y],
    ...     rtol=1.e-5, atol=1.e-8)
    array([True, True])
    >>> quaternion.isclose([1e10*quaternion.x, 1e-8*quaternion.y], [1.0001e10*quaternion.x, 1e-9*quaternion.y],
    ...     rtol=1.e-5, atol=1.e-8)
    array([False, True])
    >>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y])
    array([True, False])
    >>> quaternion.isclose([quaternion.x, np.nan*quaternion.y], [quaternion.x, np.nan*quaternion.y], equal_nan=True)
    array([True, True])
    """
    def within_tol(x, y, atol, rtol):
        with np.errstate(invalid='ignore'):
            result = np.less_equal(abs(x-y), atol + rtol * abs(y))
        return result[()]

    x = np.array(a, copy=False, subok=True, ndmin=1)
    y = np.array(b, copy=False, subok=True, ndmin=1)

    # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
    # This will cause casting of x later. Also, make sure to allow subclasses
    # (e.g., for numpy.ma).
    try:
        dt = np.result_type(y, 1.)
    except TypeError:
        dt = np.dtype(np.quaternion)
    y = np.array(y, dtype=dt, copy=False, subok=True)

    xfin = np.isfinite(x)
    yfin = np.isfinite(y)
    if np.all(xfin) and np.all(yfin):
        return within_tol(x, y, atol, rtol)
    else:
        finite = xfin & yfin
        cond = np.zeros_like(finite, subok=True)
        # Because we're using boolean indexing, x & y must be the same shape.
        # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
        # lib.stride_tricks, though, so we can't import it here.
        x = x * np.ones_like(cond)
        y = y * np.ones_like(cond)
        # Avoid subtraction with infinite/nan values...
        cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
        # Check for equality of infinite values...
        cond[~finite] = (x[~finite] == y[~finite])
        if equal_nan:
            # Make NaN == NaN
            both_nan = np.isnan(x) & np.isnan(y)
            cond[both_nan] = both_nan[both_nan]

        return cond[()]

def allclose(a, b, rtol=4*np.finfo(float).eps, atol=0.0, equal_nan=False, verbose=False):
    """Returns True if two arrays are element-wise equal within a tolerance.

    This function is essentially a wrapper for the `quaternion.isclose`
    function, but returns a single boolean value of True if all elements
    of the output from `quaternion.isclose` are True, and False otherwise.
    This function also adds the option.

    Note that this function has stricter tolerances than the
    `numpy.allclose` function, as well as the additional `verbose` option.

    Parameters
    ----------
    a, b : array_like
        Input arrays to compare.
    rtol : float
        The relative tolerance parameter (see Notes).
    atol : float
        The absolute tolerance parameter (see Notes).
    equal_nan : bool
        Whether to compare NaN's as equal.  If True, NaN's in `a` will be
        considered equal to NaN's in `b` in the output array.
    verbose : bool
        If the return value is False, all the non-close values are printed,
        iterating through the non-close indices in order, displaying the
        array values along with the index, with a separate line for each
        pair of values.

    See Also
    --------
    isclose, numpy.all, numpy.any, numpy.allclose

    Returns
    -------
    allclose : bool
        Returns True if the two arrays are equal within the given
        tolerance; False otherwise.

    Notes
    -----
    If the following equation is element-wise True, then allclose returns
    True.

      absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

    The above equation is not symmetric in `a` and `b`, so that
    `allclose(a, b)` might be different from `allclose(b, a)` in
    some rare cases.

    """
    close = isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
    result = np.all(close)
    if verbose and not result:
        a, b = np.atleast_1d(a), np.atleast_1d(b)
        a, b = np.broadcast_arrays(a, b)
        print('Non-close values:')
        for i in np.nonzero(close == False):
            print('    a[{0}]={1}\n    b[{0}]={2}'.format(i, a[i], b[i]))
    return result

redpajama_set_name: RedPajamaGithub