// Respond to 'Load file...' button press
        // Loads data from the file, opens dialog for user to assign data to existing/new spectra
        // and creates the list of spectra
        private void loadFileButton_Click(object sender, EventArgs e)
        {
            // Configuring dialog to open a new data file
            openDataFile.InitialDirectory = "Z:/Data";      // Initialise to share drive
            openDataFile.RestoreDirectory = true;           // Open to last viewed directory
            openDataFile.FileName = "";                     // Set default filename to blank
            openDataFile.Multiselect = true;                // Allow selection of multiple files

            // Show dialog to open new data file
            // Do not attempt to open file if user has pressed cancel
            if (openDataFile.ShowDialog() != DialogResult.Cancel)
            {
                // Want to only open files if they have the same number of interleaved spectra
                // So keep a 'master' record of how many there are interleaved in the first file
                int numberInterleavedMaster = new int();
                bool selectionMade = false;     // Flag whether user made the selection successfully

                // These are variables which get initialised in the first loop (when i == 0)
                // Need to declare them here (not in if statement) to avoid compiler errors
                // Array to store user selection of where to assign spectra
                int[] selectedSpectrum = new int[1];        // Have to initialise this here
                spectrumSelect mySpectrumSelectBox = new spectrumSelect();

                // Store number of files being opened
                int numberOfFiles = openDataFile.FileNames.Length;

                // Loop through each file
                for (int i = 0; i < numberOfFiles; i++)
                {
                    // Get and store just the name of the file (without full path)
                    string myFileName = Path.GetFileName(openDataFile.FileNames[i]);

                    // Create new StreamReader instance to open file
                    System.IO.StreamReader myFile = new System.IO.StreamReader(openDataFile.FileNames[i]);
                    // Create new instance of fileHandler to open & process file (pass by reference!)
                    fileHandler myFilehandler = new fileHandler(ref myFile, myFileName);
                    // Clean up StreamReader instance after fileHandler has finished with it
                    myFile.Close();           // Close object & release resources

                    // Check how many interleaved spectra there are
                    int numberInterleaved = myFilehandler.getNumberInterleaved();

                    // If numberInterleaved is zero, then trying to open spectrumSelect window will cause the progam to crash
                    // It would also mean that the fileHandler was not able to process the data correctly
                    if (numberInterleaved != 0)
                    {

                        if (i == 0)
                        {
                            // Set number interleaved to compare other files to
                            numberInterleavedMaster = numberInterleaved;

                            //*************************************************************
                            // Pop up dialog box to select which spectrum to add data to, and save selections

                            // Create spectrumSelect form, give it list of existing spectra, number of spectra in first file
                            // file name of first file, and number of files opened
                            string[] spectrumNamesFromFile = myFilehandler.getSpectrumNames();
                            mySpectrumSelectBox = new spectrumSelect(mySpectrum, ref spectrumNamesFromFile, numberInterleaved,
                                                                    ref myFileName, numberOfFiles);
                            mySpectrumSelectBox.ShowDialog();         // Display form & wait until it is closed to continue

                            // Make sure the user didn't press cancel or close the dialog box
                            if (mySpectrumSelectBox.DialogResult == DialogResult.OK)
                            {
                                // Get array of information about which data to add to which spectrum
                                selectedSpectrum = new int[numberInterleaved];
                                selectedSpectrum = mySpectrumSelectBox.selectedSpectrum.ToArray();
                                selectionMade = true;
                            }

                        } // End of if statement which checks if i == 0

                        // Check that number interleaved is correct
                        if (numberInterleaved == numberInterleavedMaster)
                        {
                            // Check that user has selected destinations for all spectra
                            if (selectionMade)
                            {
                                // For each interleaved spectrum, check where it is being assigned to
                                //
                                for (int j = 0; j < numberInterleaved; j++)
                                {
                                    // If the index >= number of existing spectra, new ones must have been added
                                    // (since for a list of N items, index runs from 0 to N-1)
                                    if (selectedSpectrum[j] >= numberOfSpectra)
                                    {
                                        int specNumInFile = selectedSpectrum[j] - numberOfSpectra;
                                        // Get the list filled with data points, add to list of spectra
                                        mySpectrum.Add(new spectrum(myFilehandler.getDataPoints(j),     // Data points for spectrum
                                                        selectedSpectrum[j],            // Spectrum number
                                                        mySpectrumSelectBox.spectrumNamesForGraph[selectedSpectrum[j]], // Spectrum name
                                                        ref myFilehandler.metadata,     // Metadata from file
                                                        specNumInFile,                  // Which spectrum in the file
                                                        myFilehandler.getNumberInterleaved() ));    // How many interleaved in file

                                        // Add blank PointPairList for storing plot data
                                        dataPlot.Add(new PointPairList());
                                    }
                                    else
                                    {

                                        // Add list of data points from file handler into existing spectrum
                                        mySpectrum[selectedSpectrum[j]].addToSpectrum(myFilehandler.getDataPoints(j));

                                    }
                                }
                                // Update number of spectra
                                numberOfSpectra = mySpectrum.Count();
                            }
                            else
                            {
                                MessageBox.Show("Spectra destinations not assigned. Data not loaded.");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Number of spectra interleaved in file " + myFileName +
                                " (" + numberInterleaved + " spectra) does not match previous files. File skipped.");
                        }

                        // Print out information to the user in the userDisplayText box
                        userDisplayText.Text += @"File """ + myFileName.Replace(".txt", "") + @""" loaded" + System.Environment.NewLine;
                        userDisplayText.Text += "Notes: " + myFilehandler.getNotes();
                        userDisplayText.SelectionStart = userDisplayText.Text.Length;
                        userDisplayText.ScrollToCaret();

                    }   // End of if statement which checks for number interleaved != 0

                } // End of for loop which goes through each file

                // Create the controls for the graph
                this.createGraphControls();

                // Update thresholds & plot data
                this.updateThresholds();

            }
        }
        public void addLiveData(List<int> readings, int CurrentWindowStep, int sidebandStartFreq, int pulseLength)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Delegate_addLiveData(addLiveData), new object[] {readings, CurrentWindowStep, sidebandStartFreq, pulseLength} );
            }
            else
            {
                // Copy data from readings into local array
                int[] myData = readings.ToArray();

                // Create fileHandler object to process the incoming data (use current sidebandStartFreq and currentwindowstep to add datapoint at correct frequency
                fileHandler myFileHandler = new fileHandler(ref myData, repeatsLive, stepSizeLive, numberOfSpectraLive,
                                                            sidebandStartFreq, CurrentWindowStep, pulseLength);

                // How many spectra were loaded before we started running live
                int existingSpectra = numberOfSpectra - numberOfSpectraLive;

                // Loop through the live spectra only
                for (int i = existingSpectra; i < numberOfSpectra; i++)
                {
                    // Add data points to the spectrum
                    mySpectrum[i].addToSpectrum(myFileHandler.getDataPoints(i));
                    // Retrieve the data to plot to graph (has already been updated by the addToSpectrum method)
                    dataPlot[i] = mySpectrum[i].getDataPlot();
                }

                // NB data gets updated automatically when points are added to spectra
                // So just update graph
                updateGraph();
                // Size the control to fill the form with a margin
                SetSize();
            }
        }