// Use this for initialization
    void Start()
    {
        HandPostureUtils.reload();
        toClick = toPosture = timeOut;
        if (UserStudyData.instance.right)
        {
            hand = rightHand;
            palm = palmRight;
        }
        else
        {
            hand = leftHand;
            palm = palmLeft;
        }

        points = new List <LinePoint>();
        generateRandCurve();
        for (int i = 0; i < points.Count - 1; i++)
        {
            points [i].init(points[i + 1].getOwn());
        }
        string fileHeader = "Name" + endl + "UserEvaluation" + endl + "Discomfort" + endl + "Time" + endl + "Accuracy" + endl + "Postureholdtime" + endl + "Posture" + endl + "AngleDis" + endl + "InterDis" + endl + "YAxisDis" + endl + "HyperDis" + endl + AngleBasedHandModel.getCSVHeader(endl, "ActualHand") + endl + AngleBasedHandModel.getCSVHeader(endl, "GivenHand");

        fileName = PostureDataHandler.instance.filePath + "LineTracingData" + UserStudyData.instance.fileEnding;
        if (!File.Exists(fileName))
        {
            File.AppendAllText(fileName, fileHeader + Environment.NewLine);
        }
        else
        {
            StreamReader read      = new StreamReader(fileName);
            string       oldHeader = read.ReadLine();
            read.Close();
            if (!oldHeader.Equals(fileHeader))
            {
                Debug.Log("Fileheader not matching. Creating new file.");
                File.Delete(fileName);
                File.AppendAllText(fileName, fileHeader + Environment.NewLine);
            }
        }
        if (UserStudyData.instance.right)
        {
            outputHand.transform.localScale = new Vector3(-outputHand.transform.localScale.x, outputHand.transform.localScale.y, outputHand.transform.localScale.z);
        }
        if (UserStudyData.instance.targetHand != null)
        {
            outputHand.visualizeHand(UserStudyData.instance.targetHand);
        }
        else
        {
            outputHand.gameObject.SetActive(false);
        }
    }
    // Use this for initialization
    void Start()
    {
        HandPostureUtils.reload();
        if (UserStudyData.instance.right)
        {
            hand = rightHand;
            palm = palmRight;
        }
        else
        {
            hand = leftHand;
            palm = palmLeft;
        }
        string fileHeader    = "Name" + endl + "UserEvaluation" + endl + "Discomfort" + endl + "Time" + endl + "Precision" + endl + "Postureholdtime" + endl + "TargetIndex" + endl + "Posture" + endl + "AngleDis" + endl + "InterDis" + endl + "YAxisDis" + endl + "HyperDis" + endl + AngleBasedHandModel.getCSVHeader(endl, "ActualHand") + endl + AngleBasedHandModel.getCSVHeader(endl, "GivenHand");
        string fileHeaderEnd =
            "Name" + endl +
            "Rating" + endl +
            "Time" + endl +
            "TrackingTime" + endl +
            "Discomfort" + endl +
            "Comfort" + endl +
            "InterDis" + endl +
            "AbductionDis" + endl +
            "HyperDis" + endl +
            Discomfort.getInterFingerCSVHeader(endl) +
            Discomfort.getAbductionCSVHeader(endl) +
            Discomfort.getHyperExtensionCSVHeader(endl) +
            Comfort.getRRPCSVHeader(endl) +
            AngleBasedHandModel.getCSVHeader(endl, "RandomHand");

        fileName    = PostureDataHandler.instance.filePath + "TargetShootingData" + UserStudyData.instance.fileEnding;
        fileNameEnd = PostureDataHandler.instance.filePath + "TargetShootingDataEnd" + UserStudyData.instance.fileEnding;

        if (!File.Exists(fileName))
        {
            File.AppendAllText(fileName, fileHeader + Environment.NewLine);
        }
        else
        {
            StreamReader read      = new StreamReader(fileName);
            string       oldHeader = read.ReadLine();
            read.Close();
            if (!oldHeader.Equals(fileHeader))
            {
                Debug.Log("Fileheader not matching. Creating new file.");
                File.Delete(fileName);
                File.AppendAllText(fileName, fileHeader + Environment.NewLine);
            }
        }

        if (!File.Exists(fileNameEnd))
        {
            File.AppendAllText(fileNameEnd, fileHeaderEnd + Environment.NewLine);
        }
        else
        {
            StreamReader read      = new StreamReader(fileNameEnd);
            string       oldHeader = read.ReadLine();
            read.Close();
            if (!oldHeader.Equals(fileHeaderEnd))
            {
                Debug.Log("Fileheader not matching. Creating new file.");
                File.Delete(fileNameEnd);
                File.AppendAllText(fileNameEnd, fileHeaderEnd + Environment.NewLine);
            }
        }


        remainingTargets = numTargets;
        if (UserStudyData.instance.right)
        {
            outputHand.transform.localScale = new Vector3(-outputHand.transform.localScale.x, outputHand.transform.localScale.y, outputHand.transform.localScale.z);
        }
        if (UserStudyData.instance.targetHand != null)
        {
            outputHand.visualizeHand(UserStudyData.instance.targetHand);
        }
        else
        {
            outputHand.gameObject.SetActive(false);
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (startPanel.activeInHierarchy && Input.GetKeyDown(KeyCode.JoystickButton0))
        {
            onContinue();
        }
        if (endPanel.activeInHierarchy && Input.GetKeyDown(KeyCode.JoystickButton0))
        {
            onEnd();
        }
        if (!HandPostureUtils.isHolding(UserStudyData.instance.posture, hand.hand) && !Input.GetButton("Emergency"))
        {
            if (holdingPosture)
            {
                progress.text  = "Loosing Hand Posture!";
                progress.color = Color.yellow;
            }
            else
            {
                progress.text  = "Please correct your hand posture!";
                progress.color = Color.red;
            }
            toPosture -= Time.deltaTime;
            if (toPosture < 0)
            {
                holdingPosture = false;
            }
        }
        else
        {
            progress.text  = "Dist: " + accuracy + ", Progress: " + getProgress();
            progress.color = Color.blue;
            toPosture      = timeOut;
            if (!holdingPosture && currentLinePoint != null)
            {
                myPoints.Add(currentLinePoint.GetComponent <LinePoint>());
                isDrawing      = false;
                holdingPosture = true;
            }
        }

        lr.SetPositions(new Vector3[] { rayOrigin, rayOrigin + 10 * rayDirection });
        lr.enabled = hand.gameObject.activeInHierarchy || art.isTracking();

        activeHandVis.SetActive(hand.gameObject.activeInHierarchy || art.isTracking());
        activeHandVis.transform.position = rayOrigin;

        if (playing)
        {
            if (HandPostureUtils.isHolding(UserStudyData.instance.posture, hand.hand))
            {
                holdcounter += Time.deltaTime;
            }
            countdownNumber.enabled = !holdingPosture;
            timer += Time.deltaTime;
            if (Input.GetButton("Fire1"))
            {
                toClick = timeOut;
                if (holdingPosture || Input.GetButton("Emergency"))
                {
                    RaycastHit hit;
                    if (Physics.Raycast(rayOrigin, rayDirection, out hit, 10, lineMask))
                    {
                        accuracy = getDistanceToCurve(hit.point);
                        if (isDrawing == false)
                        {
                            isDrawing        = true;
                            currentLinePoint = (GameObject)Instantiate(myPointPrefab, new Vector3(hit.point.x, hit.point.y, linePlane), Quaternion.identity);
                            myPoints.Add(currentLinePoint.GetComponent <LinePoint>());
                            currentLinePoint = (GameObject)Instantiate(myPointPrefab, new Vector3(hit.point.x, hit.point.y, linePlane), Quaternion.identity);
                        }
                        currentLinePoint.transform.position = new Vector3(hit.point.x, hit.point.y, linePlane);
                        myPoints[myPoints.Count - 1].init(currentLinePoint.transform.position);

                        if (myPoints[myPoints.Count - 1].getPointDistance(currentLinePoint.transform.position) > mySteps)
                        {
                            getDistanceToCurveAndSave(currentLinePoint.transform.position);
                            myPoints.Add(currentLinePoint.GetComponent <LinePoint>());
                            currentLinePoint = (GameObject)Instantiate(myPointPrefab, new Vector3(hit.point.x, hit.point.y, linePlane), Quaternion.identity);
                        }

                        if (isDone())
                        {
                            endStudy();
                        }
                    }
                }
            }
            else
            {
                if (isDrawing)
                {
                    if (toClick < 0)
                    {
                        Debug.Log("Timed Out!");
                        endStudy();
                    }
                    toClick -= Time.deltaTime;
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (startPanel.activeInHierarchy && Input.GetKeyDown(KeyCode.JoystickButton0))
        {
            onContinue();
        }
        if (endPanel.activeInHierarchy && Input.GetKeyDown(KeyCode.JoystickButton0))
        {
            onEnd();
        }
        if (!HandPostureUtils.isHolding(UserStudyData.instance.posture, hand.hand) && !Input.GetButton("Emergency"))
        {
            progress.text = "Please correct your hand posture!";
        }
        else
        {
            progress.text = remainingTargets + " of " + numTargets + " targets remaining.";
        }

        lr.SetPositions(new Vector3[] { rayOrigin, rayOrigin + 10 * rayDirection });
        lr.enabled = hand.gameObject.activeInHierarchy || art.isTracking();


        activeHandVis.SetActive(hand.gameObject.activeInHierarchy || art.isTracking());
        activeHandVis.transform.position = rayOrigin;
        if (playing)
        {
            if (HandPostureUtils.isHolding(UserStudyData.instance.posture, hand.hand))
            {
                holdcounter += Time.deltaTime;
            }
            timer += Time.deltaTime;
            if (art.isTracking())
            {
                timerTracking += Time.deltaTime;
            }
            if (HandPostureUtils.isHolding(UserStudyData.instance.posture, hand.hand) || Input.GetButton("Emergency"))
            {
                countdownNumber.enabled = false;
                if (Input.GetButtonDown("Fire1"))
                {
                    RaycastHit hit;
                    if (Physics.Raycast(rayOrigin, rayDirection, out hit, 10, mask))
                    {
                        float holdperc = holdcounter / timer;
                        try {
                            File.AppendAllText(
                                fileName,

                                UserStudyData.instance.Name + endl +
                                UserStudyData.instance.ComfortEvaluation + endl +
                                UserStudyData.instance.discomfort + endl +
                                timer + endl +
                                (hit.point - hit.collider.transform.position).magnitude + endl +
                                holdperc + endl +
                                targetList [current - 1] + endl +
                                hand.currentPosture + endl +
                                UserStudyData.instance.angleDis + endl +
                                UserStudyData.instance.interDis + endl +
                                UserStudyData.instance.yaxisDis + endl +
                                UserStudyData.instance.hyperDis + endl +
                                hand.hand.ToCSVString(endl) + endl +
                                UserStudyData.instance.targetHand.ToCSVString(endl) + Environment.NewLine
                                );
                        } catch (Exception e) {
                            Debug.LogError("Saving failed!" + e.ToString() + e.StackTrace);
                        }

                        remainingTargets--;
                        if (remainingTargets > 0 && current < targets.Length)
                        {
                            setRandTargetActive();
                            hit.collider.gameObject.SetActive(false);
                        }
                        else
                        {
                            endStudy();
                        }
                    }
                }
            }
            else
            {
                countdownNumber.enabled = true;
            }

            Debug.Log("Distance: " + HandPostureUtils.getMinDistanceToPosture(UserStudyData.instance.posture, hand.hand));
        }
    }