// Update is called once per frame
    void Update()
    {
        framecount++;

        /*    if(phase ==1 || phase ==2 || phase ==4 ){
            if (!isovrcam)
            {
              isovrcam = true;
              OvrCamObj.SetActive(true);

            }
            else if (isovrcam)
            {
                // set the main cam as true, just in case something messed up or it got disabled somehow
                MainViewObj.SetActive(true);
                OvrCamObj.SetActive(false);
                isovrcam = false;
            }

        } */

        if (phase == 1 && !phaseInit )
        {
            if (framecount % 20 == 0)
            {
                try
                {

                    setHandPointDistanceBytes();
                    bytesSent = bytesSent + WriteToLeftGlove.Length;
                }
                catch (System.NullReferenceException e) { }
            }

        }

        try
        {

            if (phase == 4)
            {
                pinchScripts = GameObject.FindObjectsOfType<MagneticPinch2>();
                foreach (MagneticPinch2 magPinchScript in pinchScripts) magPinchScript.enabled = true;

            }
        }
        catch (System.NullReferenceException e) { }

        if (phase == 0)
        {

            riftManagerScript.enabled = false;

        }

        if (phase == 1)
        {

            if (phaseInit)
            {

                if (timed) tStart = Time.time;
                phaseInit = false;
                activeSphere = 0;
                activeStimScript = findSpheres[activeSphere].GetComponent("StimulusScript") as StimulusScript;
                activeStimScript.setThisActive();
               riftManagerScript.enabled = true;

            }

            if (!timed && activeStimScript.getFound() && !phaseChangeFlag())
            {

                // print("ActiveSphere is: " + active);
                //print("I'm here"); /* For debugging */
                activeStimScript.setThisActive();
                activeSphere++;
                activeStimScript = findSpheres[activeSphere].GetComponent("StimulusScript") as StimulusScript;
                activeStimScript.setThisActive();
            }

            if (Time.time - tStart < searchTime && timed)
            {

                if (activeStimScript.getFound() && !phaseChangeFlag())
                {
                    //print("ActiveSphere is: " + active);
                    //print("I'm here"); /* For debugging */
                    activeStimScript.setThisActive();
                    activeSphere++;
                    activeStimScript = findSpheres[activeSphere].GetComponent("StimulusScript") as StimulusScript;
                    activeStimScript.setThisActive();
                }
                float t = (searchTime - (Time.time - tStart));

                if (t < .02f) timeLeft = 0 + "";
                else timeLeft = t + "";

            }

            if (phaseChangeFlag())
            {

                statusMssg = "FORWARD TRIAL COMPLETED; Please prepare to enter study phase...";
                riftTextPlane2.GetComponent<TextMesh>().text = statusMssg;
                phase = 2;
                phaseInit = true;

            }
            else if (timed && Time.time - tStart > searchTime && !phaseChangeFlag())
            {
                phase = 0;
                statusMssg = " Time expired; Click to reset";
                string riftMssg = "Time expired";
                riftTextPlane2.GetComponent<TextMesh>().text = riftMssg;
                phaseInit = true;

               riftManagerScript.enabled = false;

            }

        }

        if (phase == 2)
        {
            if (phaseInit)
            {
                OpenConnection();
                byte[] test = new byte[16];
                for (int i = 0; i < 16; i++)
                {

                    test[i] = System.Convert.ToByte(i * 16 + 0);

                }
                _SerialPort.Write(test, 0, 16);
                _SerialPort.Close();

                if (loopCount == 0)
                {
                    tStart = Time.time;
                    loopCount++;
                }

                riftManagerScript.enabled = true;

                if (Time.time - tStart > phaseWaitTime)
                {

                    statusMssg = "Now in Study Phase";

                    riftTextPlane2.GetComponent<TextMesh>().text = statusMssg;
                    phaseInit = false;
                }

            }
            if (!phaseInit)
            {
                float t = (studyTime - (Time.time - tStart));

                if (t < .02f) timeLeft = 0 + "";
                else timeLeft = t + "";

                if (Time.time - tStart > studyTime)
                {
                    statusMssg = "STUDY PHASE COMPLETE";
                    riftTextPlane2.GetComponent<TextMesh>().text = statusMssg;
                    phaseInit = true;
                    phase = 3;
                }

            }
        }

        if (phase == 3)
        {
            if (phaseInit)
            {

                tStart = Time.time;
                phaseInit = false;

                riftManagerScript.enabled = false;

            }

            if (Time.time - tStart > phaseWaitTime)
            {

                numFound = 0;
                startClick = 0;
                phaseInit = true;
                foreach (GameObject sphere in findSpheres)
                {
                    activeStimScript = sphere.GetComponent("StimulusScript") as StimulusScript;
                    activeStimScript.hide();
                }
                List<GameObject> delList = new List<GameObject>();
                delList.AddRange(GameObject.FindGameObjectsWithTag("TestCube"));
                foreach (GameObject delObj in delList) Destroy(delObj);
                statusMssg = "Click Start for next trial";

                string riftMssg = "Prepare for next trial";
                riftTextPlane2.GetComponent<TextMesh>().text = riftMssg;
            }
        }

        if (phase == 4)
        {

            if (phaseInit)

                riftManagerScript.enabled = true;
                using (StreamWriter stream = new StreamWriter(path, true))
                {
                    int p = 1;

                        stream.WriteLine("Found Times \r\n");
                    foreach (GameObject gameobj in findSpheres) stream.WriteLine(gameobj.GetComponent<StimulusScript>().getFoundTime() + ",    ");
                    stream.WriteLine("\r\n\nFound Times \r\n");
                    foreach( GameObject sphr in findSpheres){

                        stream.WriteLine("Sphere " + p + " location: " + "(" + sphr.transform.position.x + ", " + sphr.transform.position.y + ", " + sphr.transform.position.z + "),   ");
                    }

                    string s1 = "Recall Phase Time Start: " + Time.time.ToString() + "\r\n\n";

                    stream.Write(s1);

                }
            {
                foreach (GameObject sphere in findSpheres)
                {
                    activeStimScript = sphere.GetComponent("StimulusScript") as StimulusScript;
                    activeStimScript.setThisInactive();
                }
                phaseInit = false;
            }

            if (pinchCount == markLocations.Length)
            {
                try
                {

                    pinchScripts = GameObject.FindObjectsOfType<MagneticPinch2>();
                    foreach (MagneticPinch2 magPinchScript in pinchScripts) magPinchScript.enabled = false;

                }
                catch (System.NullReferenceException e) { }

                statusMssg = "All points recorded! Trial complete.";
                riftTextPlane2.GetComponent<TextMesh>().text = statusMssg;
                phase = 5;
            }

        }
        if (phase == 5)
        {

            riftManagerScript.enabled = false;

            using (StreamWriter stream = new StreamWriter(path, true))
            {

                stream.WriteLine("\r\n\n");
                stream.WriteLine("Mark Times \r\n");
                foreach (string str in stimMarkTimes) stream.WriteLine(str + ",   " + "\r\n");
                foreach (Vector3 vec in markLocations) stream.WriteLine("(" + vec.x + ", " + vec.y + ", " + vec.z + "),    ");
                stream.WriteLine("End trial");
            }

            phase = 0;
        }
    }
    //randomly generate # of spheres contained within this gameobject
    void GenerateSpheres(bool randFlag = false)
    {
        int j = Mathf.RoundToInt(Random.Range(0, randShapeCorners.Length - 1));
        bool sphereOverlap = false;

          while (sphereOverlap || firstPass) {
        // creates # of desired spheres, sets their color to yellow, calls isFound method to hide spheres
        for (int i = 0; i < numSpheres; i++)
        {

            findSpheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            findSpheres[i].layer = 8;
            findSpheres[i].renderer.enabled = false;
            findSpheres[i].collider.isTrigger = true;
            findSpheres[i].AddComponent("Rigidbody");
            findSpheres[i].rigidbody.useGravity = false;
            findSpheres[i].rigidbody.constraints = RigidbodyConstraints.FreezeAll;
            findSpheres[i].renderer.material.color = colors[i];
            findSpheres[i].tag = "Unfound";
            findSpheres[i].AddComponent("StimulusScript");
            myStimScript = findSpheres[i].GetComponent("StimulusScript") as StimulusScript;
            if (randFlag)
            {
                if (!(i > randShapeCorners.Length))
                {
                    //print("J is : " + j);    Debug
                    findSpheres[i].transform.position = randShapeCorners[j];

                    if (j != randShapeCorners.Length - 1) j++;
                    else j = 0;
                }
                else print("Cannot place any more stimuli without second pattern");

            }
            else
            {
                // randomly place spheres, position bounded by searchSpace extents

                findSpheres[i].transform.localPosition = new Vector3(Random.Range(gameObject.transform.position.x - gameObject.transform.localScale.x / 2,
                    gameObject.transform.position.x + gameObject.transform.localScale.x / 2),
                    Random.Range(gameObject.transform.position.y - gameObject.transform.localScale.y / 2, gameObject.transform.position.y + gameObject.transform.localScale.y / 2),
                    Random.Range(gameObject.transform.position.z - gameObject.transform.localScale.z / 2, gameObject.transform.position.z + gameObject.transform.localScale.z / 2));
            }
            findSpheres[i].transform.localScale = gameObject.transform.localScale * sphereRatio;

        }
         firstPass = false;
         for (int k = 0; k < numSpheres; k++)
         {
         if (findSpheres[k].GetComponent<StimulusScript>().hittingOtherSphere) sphereOverlap = true;
         }
          }

        //Do we need to worry about overlap of stimuli?
    }