private static bool SubstackToolStripMenuItem_click(string path, List <TabPage> Collection, TabPage tp, ImageAnalyser IA, loci.formats.ChannelSeparator reader, int[][] dim)
        {
            TifFileInfo fi = tp.tifFI;

            if (dim == null)
            {
                return(false);
            }
            ////////
            /////background worker
            bool loaded = false;
            //Add handlers to the backgroundworker
            var bgw = new BackgroundWorker();

            bgw.WorkerReportsProgress = true;

            TifFileInfo newFI = null;

            //Add event for projection here
            bgw.DoWork += new DoWorkEventHandler(delegate(Object o, DoWorkEventArgs a)
            {
                //Prepare matrix
                int T, Z, C, f = 0,
                curT, curZ, curC;
                List <int> matrix = new List <int>();
                for (T = 0, curT = dim[0][0] - 1; T < fi.sizeT; T++)
                {
                    if (T == curT && T < dim[0][1])
                    {
                        for (Z = 0, curZ = dim[1][0] - 1; Z < fi.sizeZ; Z++)
                        {
                            if (Z == curZ && Z < dim[1][1])
                            {
                                for (C = 0, curC = dim[2][0] - 1; C < fi.sizeC; C++, f++)
                                {
                                    if (C == curC && C < dim[2][1])
                                    {
                                        //matrix.Add(f);
                                        matrix.Add(reader.getIndex(Z, C, T));
                                        curC += dim[2][2];
                                    }
                                }

                                curZ += dim[1][2];
                            }
                            else
                            {
                                f += fi.sizeC;
                            }
                        }

                        curT += dim[0][2];
                    }
                    else
                    {
                        f += fi.sizeC * fi.sizeZ;
                    }
                }

                newFI     = fi;
                newFI.Dir = newFI.Dir.Substring(0, newFI.Dir.LastIndexOf(".")) +
                            "_Substack.tif";

                newFI.sizeT = 0;
                for (int i = dim[0][0] - 1; i < dim[0][1]; i += dim[0][2])
                {
                    newFI.sizeT++;
                }

                newFI.sizeZ = 0;
                for (int i = dim[1][0] - 1; i < dim[1][1]; i += dim[1][2])
                {
                    newFI.sizeZ++;
                }

                newFI.sizeC          = 0;
                List <Color> colList = new List <Color>();
                for (int i = dim[2][0] - 1; i < dim[2][1]; i += dim[2][2])
                {
                    newFI.sizeC++;
                    colList.Add(fi.LutList[i]);
                }

                newFI.imageCount   = matrix.Count;
                newFI.openedImages = matrix.Count;
                AddEmptyArraysToFI(newFI);
                newFI.LutList = colList;

                //read image

                //Read the first T
                //prepare array and read file
                if (isLibTifCompatible(path) && !reader.isRGB())
                {
                    int[] dimOrder = matrix.ToArray();
                    Tiff image     = Tiff.Open(path, "r");
                    //prepare array and read file
                    int midFrame = fi.sizeC * fi.sizeZ;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[fi.imageCount][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image8bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;

                    case 16:
                        fi.image16bit = new ushort[fi.imageCount][][];
                        for (int i = 0; i < midFrame; i++)
                        {
                            if (i >= fi.imageCount)
                            {
                                break;
                            }
                            IA.TabPages.myFileDecoder.Image16bit_readFrame(i, image, fi, dimOrder);
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //parallel readers
                    IA.TabPages.myFileDecoder.ImageReader_BGW(Collection, image, fi, IA, path, dimOrder);
                    //report progress
                    dimOrder = null;
                    image.Close();

                    ((BackgroundWorker)o).ReportProgress(1);
                }
                else
                {
                    byte[] buf;
                    switch (fi.bitsPerPixel)
                    {
                    case 8:
                        fi.image8bit = new byte[fi.imageCount][][];

                        buf = new byte[fi.sizeX * fi.sizeY];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image8bit[i] = Image8bit_readFrame(
                                    reader.openBytes(
                                        matrix[i], buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }

                        break;

                    case 16:
                        fi.image16bit = new ushort[fi.imageCount][][];
                        buf           = new byte[fi.sizeX * fi.sizeY * 2];

                        for (int z = 0, i = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                fi.image16bit[i] = Image16bit_readFrame(
                                    reader.openBytes(
                                        matrix[i], buf),
                                    fi.sizeX, fi.sizeY);

                                //fi.LutList[c] = ReadLut(reader);
                            }
                        }
                        break;
                    }
                    loaded = true;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(0);
                    //Read the rest T
                    byte[][] bigBuf = new byte[fi.imageCount][];

                    int ZCcount = fi.sizeC * fi.sizeZ;

                    for (int t = 1, i = ZCcount; t < fi.sizeT; t++)
                    {
                        for (int z = 0; z < fi.sizeZ; z++)
                        {
                            for (int c = 0; c < fi.sizeC; c++, i++)
                            {
                                if (fi.image8bit != null || fi.image16bit != null)
                                {
                                    bigBuf[i] = reader.openBytes(matrix[i]);
                                }
                            }
                        }
                    }
                    //Format the arrays for CellTool
                    Parallel.For(ZCcount, fi.imageCount, (int i) =>
                    {
                        try
                        {
                            switch (fi.bitsPerPixel)
                            {
                            case 8:
                                if (fi.image8bit != null)
                                {
                                    fi.image8bit[i] = Image8bit_readFrame(bigBuf[i],
                                                                          fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;

                            case 16:
                                if (fi.image16bit != null)
                                {
                                    fi.image16bit[i] = Image16bit_readFrame(bigBuf[i],
                                                                            fi.sizeX, fi.sizeY);
                                }
                                bigBuf[i] = null;
                                break;
                            }
                        }
                        catch { }
                    });
                    bigBuf = null;
                    //report progress
                    ((BackgroundWorker)o).ReportProgress(1);
                }
            });
            bgw.ProgressChanged += new ProgressChangedEventHandler(delegate(Object o, ProgressChangedEventArgs a)
            {
                if (a.ProgressPercentage == 0)
                {
                    fi.openedImages = fi.sizeC * fi.sizeZ;
                    try
                    {
                        IA.ReloadImages();
                    }
                    catch { }
                }
                else if (a.ProgressPercentage == 1)
                {
                    //dispose the reader
                    reader.close();
                    reader = null;
                    //mark as loaded
                    fi.openedImages = fi.imageCount;
                    fi.available    = true;
                    fi.loaded       = true;
                    newFI.original  = false;

                    IA.TabPages.myFileDecoder.CalculateAllRois(fi);

                    IA.ReloadImages();
                    bool check = true;
                    foreach (TabPage tp1 in Collection)
                    {
                        if (tp1.tifFI != null && tp1.tifFI.available == false)
                        {
                            check = false;
                            break;
                        }
                    }
                    if (check == true)
                    {
                        IA.TabPages.myFileDecoder.loadingTimer.Stop();
                        IA.FileBrowser.StatusLabel.Text = "Ready";
                    }

                    if (IA.Segmentation.AutoSetUp.LibTB.SelectedIndex > 0 &&
                        IA.Segmentation.AutoSetUp.ApplyToNewCheckB.Checked &&
                        MessageBox.Show("Do you want to open the image with the following protocol:\n" +
                                        IA.Segmentation.AutoSetUp.LibTB.Text,
                                        "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        IA.Segmentation.AutoSetUp.ApplyCT3Tags(IA.Segmentation.AutoSetUp.protocols[
                                                                   IA.Segmentation.AutoSetUp.LibTB.SelectedIndex].Split(
                                                                   new string[] { ";\n" }, StringSplitOptions.None), fi);
                    }
                }
            });

            //Start background worker
            IA.FileBrowser.StatusLabel.Text = "Reading Image...";
            //Clear OldImage
            IA.IDrawer.ClearImage();

            //start bgw
            bgw.RunWorkerAsync();
            //add taskbar
            tp.tifFI.tpTaskbar.Initialize(IA.TabPages.ImageMainPanel, IA, fi);

            try
            {
                if (loaded == true)
                {
                    IA.ReloadImages();
                }
            }
            catch { }
            //output
            return(true);
        }
        private static loci.formats.ChannelSeparator ReadMetadata(string path, List <TabPage> Collection, TabPage tp, ImageAnalyser IA)
        {
            // read metadata using ImageReader
            loci.formats.ImageReader FirstReader = new loci.formats.ImageReader();
            try
            {
                FirstReader.setId(path);
            }
            catch
            {
                FirstReader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }

            bool isRGB = FirstReader.isRGB();

            //check is it rgb colored
            loci.formats.ChannelSeparator reader = loci.formats.ChannelSeparator.makeChannelSeparator(FirstReader);
            FirstReader = null;

            TifFileInfo fi = tp.tifFI;

            fi.seriesCount = reader.getSeriesCount();
            //Select which series to open!!!!!
            int ser = SelectSeries(reader, IA.TabPages.FileBrowser.StatusLabel);

            if (ser == -1)
            {
                fi = null;
                reader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }
            else
            {
                reader.setSeries(ser);
            }
            //Check file bits per pixel - currently supported: 8 bit GrayScale, 16 bit GrayScale
            fi.bitsPerPixel = reader.getBitsPerPixel();
            if (fi.bitsPerPixel <= 8)
            {
                fi.bitsPerPixel = 8;
            }
            else if (fi.bitsPerPixel <= 16)
            {
                fi.bitsPerPixel = 16;
            }
            else
            {
                fi = null;
                reader.close();
                IA.FileBrowser.StatusLabel.Text = "Ready";
                return(null);
            }
            //Check is the metadata complieted and return message if not

            /*
             * if (reader.isMetadataComplete() == false)
             * {
             *  MessageBox.Show("Metadata is not complete!");
             * }
             */
            //read tags

            fi.imageCount = reader.getImageCount();
            fi.sizeX      = reader.getSizeX();
            fi.sizeY      = reader.getSizeY();
            fi.sizeZ      = reader.getSizeZ();
            fi.sizeC      = reader.getSizeC();
            fi.sizeT      = reader.getSizeT();
            //fi.dimensionOrder = reader.getDimensionOrder();
            fi.dimensionOrder              = "XYCZT";
            fi.umZ                         = 0;
            fi.umXY                        = 0;
            fi.pixelType                   = reader.getPixelType();
            fi.FalseColored                = reader.isFalseColor();
            fi.isIndexed                   = reader.isIndexed();
            fi.MetadataComplete            = reader.isMetadataComplete();
            fi.DatasetStructureDescription = reader.getDatasetStructureDescription();
            string description = getLibTifFileDescription(path);

            fi.FileDescription = string.Join("\n", new string[] { "-----------------", "CoreMetadata:\n", reader.getCoreMetadataList().ToString(),
                                                                  "-----------------", "GlobalMetadata:\n", reader.getGlobalMetadata().ToString(),
                                                                  "-----------------", "SeriesMetadata:\n", reader.getSeriesMetadata().ToString(),
                                                                  "-----------------", "FileDescription:\n", description });
            //Apply def settings
            fi.Dir       = path;
            fi.xAxisTB   = IA.chart.Properties.xAxisTB.SelectedIndex;
            fi.yAxisTB   = IA.chart.Properties.yAxisTB.SelectedIndex;
            fi.available = false;
            fi.original  = false;
            //Create LUT table
            if (isRGB)
            {
                fi.LutList = new List <Color>()
                {
                    Color.FromArgb(255, 255, 0, 0),
                    Color.FromArgb(255, 0, 255, 0),
                    Color.FromArgb(255, 0, 0, 255)
                };
            }
            else
            {
                fi.LutList = new List <Color>();
                for (int i = 0; i < fi.sizeC; i++)
                {
                    fi.LutList.Add(Color.White);
                }
            }
            //Create time steps table
            fi.TimeSteps = new List <double>();
            fi.TimeSteps.Add(fi.imageCount + 1);
            fi.TimeSteps.Add(1);

            //If its IQ3 format or Dragonflye - try to read the colors and the timesteps
            TryAndorDecoders(fi, description);

            if (fi.sizeC == 0)
            {
                fi.sizeC = 1;
            }
            if (fi.sizeZ == 0)
            {
                fi.sizeZ = 1;
            }
            if (fi.sizeT == 0)
            {
                fi.sizeT = 1;
            }

            #region Segmentation variables
            fi.SegmentationCBoxIndex = new int[fi.sizeC];
            fi.SegmentationProtocol  = new int[fi.sizeC];
            fi.thresholdsCBoxIndex   = new int[fi.sizeC];
            fi.sumHistogramChecked   = new bool[fi.sizeC];
            fi.thresholdValues       = new int[fi.sizeC][];
            fi.thresholdColors       = new Color[fi.sizeC][];
            fi.RefThresholdColors    = new Color[fi.sizeC][];
            fi.thresholds            = new int[fi.sizeC];
            fi.SpotColor             = new Color[fi.sizeC];
            fi.RefSpotColor          = new Color[fi.sizeC];
            fi.SelectedSpotThresh    = new int[fi.sizeC];
            fi.SpotThresh            = new int[fi.sizeC];
            fi.typeSpotThresh        = new int[fi.sizeC];
            fi.SpotTailType          = new string[fi.sizeC];
            fi.spotSensitivity       = new int[fi.sizeC];
            fi.roiList          = new List <ROI> [fi.sizeC];
            fi.tracking_MaxSize = new int[fi.sizeC];
            fi.tracking_MinSize = new int[fi.sizeC];
            fi.tracking_Speed   = new int[fi.sizeC];
            for (int i = 0; i < fi.sizeC; i++)
            {
                fi.sumHistogramChecked[i] = false;
                fi.thresholdValues[i]     = new int[5];
                fi.thresholdColors[i]     = new Color[]
                { Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent, Color.Transparent };
                fi.RefThresholdColors[i] = new Color[]
                { Color.Black, Color.Orange, Color.Green, Color.Blue, Color.Magenta };
                fi.SpotColor[i]        = Color.Red;
                fi.RefSpotColor[i]     = Color.Red;
                fi.SpotTailType[i]     = "<";
                fi.spotSensitivity[i]  = 100;
                fi.tracking_MaxSize[i] = 10000;
                fi.tracking_MinSize[i] = 5;
                fi.tracking_Speed[i]   = 5;
            }
            #endregion Segmentation variables
            return(reader);
        }