//Bakalarska prace

//TEMA:
//UZIVATELSKY PROGRAM PRO ZOBRAZENI
//A ZPRACOVANI KVANTITATIVNI FAZE
//Z DIGITALNIHO HOLOGRAFICKEHO MIKROSKOPU

//FAKULTA STROJNIHO INZENYRSTVI
//USTAV FYZIKALNIHO INZENYRSTVI

//Jmeno:		Hladik Lukas
//Skupina:		3E/91
//Verze:		1.0
//Datum:		27. kvetna 2010


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using QuartzTypeLib;
using System.Runtime.InteropServices.ComTypes;
using System.Diagnostics;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        //--DEKLARACE PRO VIDEO
        private FilgraphManager m_objFilterGraph = null;
        //private IBasicAudio m_objBasicAudio = null;
        private IVideoWindow m_objVideoWindow = null;
        private IMediaEvent m_objMediaEvent = null;
        private IMediaEventEx m_objMediaEventEx = null;
        private IMediaPosition m_objMediaPosition = null;
        private IMediaControl m_objMediaControl = null;

        
        enum MediaStatus { None, Stopped, Paused, Running };


        private const int WM_APP = 0x8000;
        private const int WM_GRAPHNOTIFY = WM_APP + 1;
        private const int EC_COMPLETE = 0x01;
        private const int WS_CHILD = 0x40000000;
        private const int WS_CLIPCHILDREN = 0x2000000;

        private MediaStatus m_CurrentStatus = MediaStatus.None;
        

        
        private int[, ,] m_BitmapPole = null;
        public string nazev_videa = null;
        string nazevSlozky;
        string[] poleSouboru;
        string[] poleSouboru_poOdectu;
        double[, ,] Pha;
        int n = 10;  //krok
        //int n = Va  1;  //krok
        int PreviewCount;//pocita pocet stiknuti tlacitka nahled
        int Zobrazovat;
        bool nahled;
        protected PerformanceCounter ramCounter;
        Process procesAplikace = Process.GetCurrentProcess();
        
        public Form1()
        {
            InitializeComponent();
            //PreviewCount = 0;
           
        }




     
        

        //---------------ULOZENI DO POLE
        unsafe public static int[, ,] ZiskejBitmapPole(Bitmap bitMapa)   //NACTENI RGB MATICE
        {

            BitmapData data = bitMapa.LockBits(
                 new Rectangle(0, 0, bitMapa.Width, bitMapa.Height),
                 ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int[, ,] pole = new int[bitMapa.Width, bitMapa.Height, 3];
            //int[, ,] bitmapArray = new byte[bitMapa.Width, bitMapa.Height, 3];

            //-------------------------------------------------

            for (int y = 0; y < bitMapa.Height; ++y)
            {
                int* posPrvni = (int*)((int)data.Scan0 + (y * data.Stride));

                for (int x = 0; x < bitMapa.Width; ++x)
                {
                    Color c_prvni = Color.FromArgb(*posPrvni);

                    int alpha = c_prvni.A;
                    int cervena = c_prvni.R; // Math.Abs(c_cela_cerna.R - c_zdrojove.R);
                    int zelena = c_prvni.G; //Math.Abs(c_cela_cerna.G - c_zdrojove.G);
                    int modra = c_prvni.B;

                    
                    pole[x, y, 0] = c_prvni.R;
                    pole[x, y, 1] = c_prvni.G;
                    pole[x, y, 2] = c_prvni.B;
                    
                    posPrvni++;
                }

              
                               
            }

            bitMapa.UnlockBits(data);
            return pole;
        }

        //---------------------ULOZENI DO BITMAPY
        private unsafe Bitmap UlozBitmapPole(int [, ,] bitmapArray)       // VYTVORENI BITMAPY z RGB matice
        
        {

            Bitmap dst = new Bitmap(bitmapArray.GetLength(0), bitmapArray.GetLength(1));

            BitmapData dstData = dst.LockBits(
             new Rectangle(0, 0, bitmapArray.GetLength(0),bitmapArray.GetLength(1)),
             ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            
            //----------------------------------------------------------

            for (int y = 0; y < bitmapArray.GetLength(1); ++y)
            {
                int* dstPos = (int*)((int)dstData.Scan0 + (y * dstData.Stride));

                for (int x = 0; x < bitmapArray.GetLength(0); ++x)
                {

                    
                    *dstPos = Color.FromArgb(bitmapArray[x, y, 0], bitmapArray[x, y, 1], bitmapArray[x, y, 2]).ToArgb();

                    dstPos++;
                }
            }




            dst.UnlockBits(dstData);  
            return dst;
        }






        



        //private unsafe Bitmap 
        public int[, ,] OdectiDva(int[, ,] bitmapArray1, int[, ,] bitmapArray2)   //ODECTENI HODNOT
        {

            int[, ,] odecet = new int[bitmapArray1.GetLength(0), bitmapArray1.GetLength(1), 3];


            for (int y = 0; y < bitmapArray1.GetLength(1); ++y)
            {
                
                for (int x = 0; x < bitmapArray1.GetLength(0); ++x)
                {


                    //rozdil 1 - 2

                    odecet[x, y, 0] = bitmapArray1[x, y, 0] - bitmapArray2[x, y, 0]; //MUSI BYT OBA OBRAZKY O STEJNYCH ROZMERECH
                    int intenzita = 0;
                    intenzita = bitmapArray1[x, y, 0] + bitmapArray1[x, y, 1] + bitmapArray1[x, y, 2];


                    if (odecet[x, y, 0] < 5 && odecet[x, y, 0] > -5)  //FILTRACE POZADI
                    {

                        odecet[x, y, 0] = 0;
                        odecet[x, y, 1] = 0;
                        odecet[x, y, 2] = 0;
                    }

                    
                    if (odecet[x, y, 0] > 0)  //pro cervenou jen delam, zbytek je stejnej
                    {
                        //odecet[x, y, 0] = odecet[x, y, 0];  //CERVENA ZAJIMAVE
                        odecet[x, y, 0] = bitmapArray1[x, y, 0]^2/intenzita;
                        odecet[x, y, 1] = 0;   //ZELENA
                        odecet[x, y, 2] = 0;   // MODRA 
                     
                    }
                    else if (odecet[x, y, 0] < 0)
                    {
                        odecet[x, y, 0] = 0;
                        odecet[x, y, 1] = bitmapArray1[x, y, 1];
                        //  odecet[x, y, 1] = bitmapArray1[x, y, 1] ^ 2 / intenzita; //VYRESIT DELENI NULOU 
                        odecet[x, y, 2] = 0;
                    }




                   
                }
            }
            bitmapArray1 = null;
            bitmapArray2 = null;
                      
            return odecet;

        }

        //----------------------- JEJICH ZAPIS



        public int[, ,] OdectiDvaJejich(int[, ,] bitmapArray1, int[, ,] bitmapArray2)   //ODECTENI HODNOT
        {

            int[, ,] odecet = new int[bitmapArray1.GetLength(0), bitmapArray1.GetLength(1), 3];



            for (int y = 0; y < bitmapArray1.GetLength(1); ++y)
            {
                for (int x = 0; x < bitmapArray1.GetLength(0); ++x)
                {


                    //rozdil 1 - 2

                    odecet[x, y, 0] = bitmapArray1[x, y, 0] - bitmapArray2[x, y, 0]; //MUSI BYT OBA OBRAZKY O STEJNYCH ROZMERECH
                    int intenzita = 0;
                    intenzita = bitmapArray1[x, y, 0] + bitmapArray1[x, y, 1] + bitmapArray1[x, y, 2];


                    if (odecet[x, y, 0] < 5 && odecet[x, y, 0] > -5)  //FILTRACE POZADI
                    {

                        odecet[x, y, 0] = 0;
                        odecet[x, y, 1] = 0;
                        odecet[x, y, 2] = 0;
                    }


                    if (odecet[x, y, 0] > 0)  //pro cervenou jen delam, zbytek je stejnej
                    {
                        //odecet[x, y, 0] = odecet[x, y, 0];  //CERVENA ZAJIMAVE
                        odecet[x, y, 0] = bitmapArray1[x, y, 0] ^ 2 / intenzita;
                        odecet[x, y, 1] = 0;   //ZELENA
                        odecet[x, y, 2] = 0;   // MODRA 

                    }
                    else if (odecet[x, y, 0] < 0)
                    {
                        odecet[x, y, 0] = 0;
                        odecet[x, y, 1] = bitmapArray1[x, y, 1];
                        //odecet[x, y, 1] = bitmapArray1[x, y, 1] ^ 2 / intenzita; //VYRESIT DELENI NULOU 
                        odecet[x, y, 2] = 0;
                    }

                                        
                }
            }
            bitmapArray1 = null;
            bitmapArray2 = null;

            return odecet;

        }


        public float getAvailableRAM()
        {
            return ramCounter.NextValue();
        } 



        public void button4_Click(object sender, EventArgs e) //KLIKNUTO: OTEVRIT 
        {
            
            MakeSelection(1);  //funkce na oznaceni okna Zdroj cervenym rameckem
            progressBar1.Value = 0; // vynulovani progress baru 
            Cursor.Current = Cursors.WaitCursor; //zmena ikony kurzoru
            statusBarPanel1.Text = "Pracuji";
            nastaveni_souboru dlg = new nastaveni_souboru();  //inicializace dialogu vyberu souboru
            
            
           

            if (dlg.ShowDialog(this) == DialogResult.OK)  //pokud uzivatel stiskne v dialogu OK
            {

                try //pokus
                {
                    //Vycisti listView1
                    listView1.Clear();
                    imageList1.Images.Clear();      
                    listView2.Clear();
                    imageList2.Images.Clear();
                    
                    poleSouboru = dlg.GetFileNames(); //naplni globalni promennou obsahem Listboxu ze souboroveho dialogu
                    
                    //----------------------ZMENA PROSTREDI
                    //---------ZMENA PROSTREDI
                    button3.Enabled = false; // zpristupni tlacitko Ulozit
                    button2.Enabled = false;  // zpristupni tlacitko Nahled
                    náhledToolStripMenuItem.Enabled = false; // zpristupni v menu polozku ulozit
                    uložitToolStripMenuItem.Enabled = false; // zpristupni v menu polozku nahled
                    //button7.Enabled = false;  // zpristupni tlacitko DPD
                    //dPDToolStripMenuItem.Enabled = false; // zpristupni v menu polozku DPD
                    //------------------------------
                    trackBar1.Enabled = false;
                    button7.Enabled = true;  // zpristupni tlacitko DPD
                    dPDToolStripMenuItem.Enabled = true; // zpristupni v menu polozku DPD
                    //------------------------------
                   
                    //rozdílToolStripMenuItem.Enabled = true;  //zpristupni polozky v menu DPD 
                   // videoToolStripMenuItem.Enabled = true;   //zpristupni polozky v menu Ulozit
                    Zobrazovat = dlg.GetZobrazovat();

                    ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 

                    if (Zobrazovat == 1)
                    {


                        for (int i = 0; i < poleSouboru.GetLength(0); i++)
                        {
                            //tady to pada
                            //if ((procesAplikace.WorkingSet64 / 1024) < 1000000)
                            //{
                                
                            //    imageList1.Images.Add(Image.FromFile(poleSouboru[i]));
                                
                            //}
                            //else
                            //{
                            //    MessageBox.Show("Nedostatek pameti");
                            //    button7.Enabled = false;  // znepristupni tlacitko DPD
                            //    dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                            //    return;
                            //}
                             //fyzicky naplni imagelist1 obrazky, omezeni pameti ?

                            //if ( Convert.ToInt16(getAvailableRAM()) < 100) 
                            //if (getAvailableRAM() < 1000)
                            //{
                            //    MessageBox.Show("Nedostatek pameti" + getAvailableRAM());
                            //    button7.Enabled = false;  // znepristupni tlacitko DPD
                            //    dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD

                            //    return;
                            //}

                            try
                            {
                                imageList1.Images.Add(Image.FromFile(poleSouboru[i]));
                            }
                            catch
                            {
                                //MessageBox.Show("Nedostatek pameti" + getAvailableRAM());
                                MessageBox.Show("Nedostatek paměti pro zobrazení zdrojových obrazů. Zkuste v dialogu výběru zdrojových dat odškrtnout volbu: Zobrazit obrazy na hlavní ploše.",
                                "Chyba",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                                listView1.Clear();
                                imageList1.Images.Clear();
                                GC.Collect();
                                
                                button7.Enabled = false;  // znepristupni tlacitko DPD
                                dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                                return;
                                
                            }
                            
                            
                            
                            



                        }
                        //MessageBox.Show("" + getAvailableRAM());
                        //MessageBox.Show("Pamet" + procesAplikace.WorkingSet64 / 1024 + " Kb");  




                        listView1.View = View.LargeIcon;   //velke obrazky v listview
                        imageList1.ImageSize = new Size(256, 204); //velikost obrazku v listview, muze byt na pevno - Dialog nastaveni programu
                        listView1.LargeImageList = imageList1; //preda odkaz na imageList


                        for (int j = 0; j < imageList1.Images.Count; j++)
                        {

                            ListViewItem item = new ListViewItem(); //inicializuje novou polozku ve sloupci Zdroj
                            //                        yListView.Items[0].BackColor = Color.Red;
                            
                            item.ImageIndex = j;  //spravne prirazeni indexu k obrazku

                            progressBar1.Value = (((j + 1) * 100) / imageList1.Images.Count); //vypocet prubehu nacitani
                            try
                            {
                                listView1.Items.Add(item);  //naplni sloupec Zdroj obrazky    
                            }
                                                        
                            catch
                            {
                                //MessageBox.Show("Nedostatek pameti" + getAvailableRAM());
                                MessageBox.Show("Nedostatek paměti. Snižte prosím rozlišení obrazů nebo jejich celkový počet.",
                                "Chyba",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);

                                button7.Enabled = false;  // znepristupni tlacitko DPD
                                dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                                listView1.Clear();
                                imageList1.Images.Clear();
                                GC.Collect();
                                return;

                            }
                            
                        }

                        

                        //label1.Text = "" + Image.FromFile(poleSouboru[1]).Width;

                    }

                    try
                    {
                        statusBarPanel3.Text = "" + Image.FromFile(poleSouboru[0]).Width + " × " + Image.FromFile(poleSouboru[0]).Height + " × " + Image.FromFile(poleSouboru[0]).PixelFormat;
                        // statusBarPanel3.Text = "" + imageList1.Images[1].Width + " × " + imageList1.Images[1].Height + " × " + imageList1.Images[1].PixelFormat;
                        statusBarPanel2.Text = "" + poleSouboru.GetLength(0);
                    }
                    catch
                    {
                        MessageBox.Show("Nebyly vybrány obrazy ke zpracování.",
                                   "Chyba",
                                   MessageBoxButtons.OK,
                                   MessageBoxIcon.Exclamation,
                                   MessageBoxDefaultButton.Button1);
                    
                    }
                }

                finally //to co se ma vykonat vzdycky
                {
                    
                }
                
                progressBar1.Value = 0; //vynuluje progressbar
                Cursor.Current = Cursors.Default; //zmeni opet na sipku
                statusBarPanel1.Text = "Připraven";
                //statusBar1.
                GC.Collect();
                this.listView1.Refresh(); 
            }






        }



        //private void button5_Click(object sender, EventArgs e) //ZPRACOVANI ADRESARE 
        //{
            
        //    string nazev1,nazev2;
        //    Bitmap m_Bitmap1 = null; 
        //    Bitmap m_Bitmap2 = null;
        //    //m_Bitmap2 = new Bitmap(textBox2.Text);
        //    int[, ,] vysledek = null;
        //    Bitmap pomocnaBitmapa = null;
        //    int i=0;
        //    //int[, ,] Pha = null;

        //    for (i = 0; i < poleSouboru.GetLength(0); i++)
        //    {
        //        if (i == poleSouboru.GetLength(0)-1)
        //            break;

        //        nazev1 = poleSouboru[i];
        //        nazev2 = poleSouboru[i + 1];  
                
        //        //listBox2.Items.Add(nazev1 + " |" + nazev2);
        //        //listBox2.Items.Add("dalsi dvojice");

        //        m_Bitmap1 = new Bitmap(nazev1);
        //        m_Bitmap2 = new Bitmap(nazev2);

        //        //int[, ,] m_Pole1 = null;
        //        //m_Pole1 = ZiskejBitmapPole(m_Bitmap1);

        //        //int[, ,] m_Pole2 = null;
        //        //m_Pole2 = ZiskejBitmapPole(m_Bitmap2);

        //       // int[, ,] vysledek = null;
        //        vysledek = OdectiDvaJejich(ZiskejBitmapPole(m_Bitmap1), ZiskejBitmapPole(m_Bitmap2));
               
        //        //pictureBox1.Image = UlozBitmapPole(vysledek);
        //        //pictureBox1.Image.Save("vysledek" + i + ".tif", ImageFormat.Tiff);


        //        pomocnaBitmapa = new Bitmap(UlozBitmapPole(vysledek));
        //        pomocnaBitmapa.Save("vysledky/vysledek" + i + ".tif", ImageFormat.Tiff);
                

        //        m_Bitmap1 = null;
        //        m_Bitmap2 = null;    

        //    }

        //    MessageBox.Show("Hotovo " + i + " souboru");
                                   
        //}



        //---------------ULOZENI DO POLE INTENZIT [x,y,cislo obrazku]

        unsafe public static int[,] PoleIntenzit(Bitmap bitMapa)   //NACTENI RGB MATICE
        {

            BitmapData data = bitMapa.LockBits(
                 new Rectangle(0, 0, bitMapa.Width, bitMapa.Height),
                 ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int[,] pole = new int[bitMapa.Width, bitMapa.Height];
            //int[, ,] bitmapArray = new byte[bitMapa.Width, bitMapa.Height, 3];

            //-------------------------------------------------

            for (int y = 0; y < bitMapa.Height; ++y)
            {
                int* posPrvni = (int*)((int)data.Scan0 + (y * data.Stride));

                for (int x = 0; x < bitMapa.Width; ++x)
                {
                    Color c_prvni = Color.FromArgb(*posPrvni);
                    int nc = (114 * c_prvni.R + 587 * c_prvni.G + 299 * c_prvni.B) / 1000;
                    
                    pole[x, y] = nc;
                    posPrvni++;
                }



            }

            bitMapa.UnlockBits(data);
            return pole;
        }



        
        

        unsafe public static double[,] PoleIntenzitDouble(Bitmap bitMapa)   //Prevod barevneho obrazku na pole intenzit
        {

            BitmapData data = bitMapa.LockBits(                           //pristup k jednotlivym pixelum bitmapy
                 new Rectangle(0, 0, bitMapa.Width, bitMapa.Height),
                 ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); 
            
            double[,] pole = new double[bitMapa.Width, bitMapa.Height];  //deklarace noveho pole pro ukladani hodnot intenzit
            
            for (int y = 0; y < bitMapa.Height; ++y) //vertikalne
            {
                int* posPrvni = (int*)((int)data.Scan0 + (y * data.Stride)); //ukazatel

                for (int x = 0; x < bitMapa.Width; ++x) //horizontalne
                {
                    Color c_prvni = Color.FromArgb(*posPrvni); //naplni strukturu Color slozkami jednotlivych barev
                    double nc = (0.114 * c_prvni.R + 0.587 * c_prvni.G + 0.299 * c_prvni.B); //prevod na intenzitu (vychazi z fyziologie lidskeho oka
                    //double nc = c_prvni.B; //prevod na intenzitu (vychazi z fyziologie lidskeho oka
                    pole[x, y] = nc; // zapise intenzitu
                    posPrvni++; //posune ukazatel
                }

            }

            bitMapa.UnlockBits(data); //uvolni nactene pixely z pameti
            return pole; //vrati jeden cernobily obrazek v podobe dvourozmerne matice
            GC.Collect();
        }




        //---------------------ULOZENI POLE INTENZIT DO BITMAPY
        private unsafe Bitmap UlozIntenzitu(int[,] bitmapArray)       // VYTVORENI BITMAPY z RGB matice
        {
            
            Bitmap dst = new Bitmap(bitmapArray.GetLength(0), bitmapArray.GetLength(1));

            BitmapData dstData = dst.LockBits(
             new Rectangle(0, 0, bitmapArray.GetLength(0), bitmapArray.GetLength(1)),
             ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            //----------------------------------------------------------

            for (int y = 0; y < bitmapArray.GetLength(1); ++y)
            {
                int* dstPos = (int*)((int)dstData.Scan0 + (y * dstData.Stride));

                for (int x = 0; x < bitmapArray.GetLength(0); ++x)
                {


                    *dstPos = Color.FromArgb(bitmapArray[x, y], bitmapArray[x, y], bitmapArray[x, y]).ToArgb();
                    
                    dstPos++;
                }
            }

            GC.Collect();
            dst.UnlockBits(dstData);
            return dst;
        }

        
        public void CreatePha() //FUNKCE NACTE VSECHNY OBRAZKY DO [sirka, vyska, pocet obrazku]-rozmerne matice
        {
           
           
           //int n = 0;                  //DEKLARACE lokalnich promennych  
           double[,] m_Pole1 = null;
           
           //string maticka = null;
           
           Bitmap m_Bitmap1 = null;
           Bitmap m_Bitmap2 = null;
           Pha = null;
           
           Pha = new double[(m_Bitmap2 = new Bitmap(poleSouboru[0])).Width, (m_Bitmap2 = new Bitmap(poleSouboru[0])).Height, poleSouboru.GetLength(0)];     //POZOR NA VELIKOST JEDNOTLIVYCH POLI   

           
            for (int i = 0; i < poleSouboru.GetLength(0); ++i) //pro jednotlive soubory
               {
                   m_Bitmap1 = new Bitmap(poleSouboru[i]);  //nacte jeden i-ty soubor do promenne Bitmap1
                   m_Pole1 = PoleIntenzitDouble(m_Bitmap1);  // nacte pole inzenzit jednoho obrazku do m_Pole1
                   
                   for (int y = 0; y < m_Pole1.GetLength(1); ++y)
                   {
                       
                       for (int x = 0; x < m_Pole1.GetLength(0); ++x)
                       {

                           
                           Pha[x, y, i] = m_Pole1[x, y];  // !!! MUSI BYT STEJNE VELKE OBRAZKY
                           progressBar1.Value = ( ((i + 1) * 100) / (poleSouboru.GetLength(0)+200));
                           


                           //GC.Collect();
                     }//endfor x

                   }//endfor y
                
                }//endfor i
          
            //GC.Collect();
        }

        private void MakeSelection(int WindowNumber) //zobrazeni konfiguracnich nabidek a podbarveni spravne sekce
        {

           switch (WindowNumber) //podle zvoleneho typu
            {
                case 1: //KLIKNUTO: Otevrit                          
                    ZdrojMarker.Visible = true;
                    VideoMaker.Visible = false;
                    DPDMarker.Visible = false;
                    groupBox1.Visible = false;
                    groupBox2.Visible = false;

                    break;
                case 2: //KLIKNUTO: DPD                          
                    groupBox1.Visible = false;
                    groupBox2.Location = new Point(597, 362);
                    groupBox2.Visible = true;

                    ZdrojMarker.Visible = false;
                    VideoMaker.Visible = false;
                    DPDMarker.Visible = true;
                    break;
                case 3: //KLIKNUTO: Nahled
                    groupBox1.Visible = true;
                    //groupBox2.Location = new Point(597, 362);
                    groupBox2.Visible = false;

                    ZdrojMarker.Visible = false;
                    VideoMaker.Visible = true;
                    DPDMarker.Visible = false;
                    break;
                    
                default:
                    break;
            }
        }
        



        private void button7_Click(object sender, EventArgs e) //KLIKNUTO DPD
        {

            MakeSelection(2); //nastavi konfigurační okno a označí sloupec DPD
            
           
        }

        //------------------------------ MAXIMUM INTENZITY ------------------------------
        public double urciMaximumMatice(double[, ,] maticeA)
        {

            //int[,] A = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
            double[, ,] A = new double[maticeA.GetLength(0), maticeA.GetLength(1), maticeA.GetLength(2)];

            A = maticeA;
            double maximum = 0;
            

            for (int b = 0; b < A.GetLength(2); ++b)
            {
                for (int y = 0; y < A.GetLength(1); ++y)
                {

                    for (int x = 0; x < A.GetLength(0); ++x)
                    {
                       // textBox4.Text = textBox4.Text + (A[x, y, b] + " ");
                        if (A[x, y, b] > maximum)
                            maximum = A[x, y, b];


                    } //end FOR x

                  //  textBox4.Text = (textBox4.Text + "\r\n");
                } //end FOR y
                //textBox4.Text = textBox4.Text + ("Maximum je:" + maximum);
            }//end FOR b

            return maximum;
        }


        private void button8_Click(object sender, EventArgs e)
        {

            /*
            int nc = (145 * 144) / 1000;
            double ncDouble = (145 * 148)/1000;

            int mysint = System.Convert.ToInt32(ncDouble);

            //printf("Value 1.3lf", value);
            //textBox4.Text = ("nc je:  " + nc + "ncDouble 1.3lf:  " +  Convert.ToInt32(ncDouble));
              
            textBox4.Text = ncDouble.ToString();

            */
        }

        private void konecToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form1.ActiveForm.Close(); //ZAVRE APLIKACI
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {


            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; //nastaveni zakladni slozky
            if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
            {

                try
                {

                    //nazevSlozky = "E:\\Hell\\VUT";
                    nazevSlozky = folderBrowserDialog1.SelectedPath;
                    //label1.Text = nazevSlozky;
                    poleSouboru = System.IO.Directory.GetFiles(nazevSlozky);

                    int k = poleSouboru.GetLength(0);
                    //label1.Text = "Velikost = " + k;


                    for (int i = 0; i < k; i++)
                    {

                        //listBox1.Items.Add(poleSouboru[i]);
                    }

                }

                finally
                {

                }
            }

      }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click_1(object sender, EventArgs e) //KLIKNUTO ULOZIT
        {
            
            //Ulozeni videosouboru
            uint pocet_snimku = 8;  //default

            nataveni_videa dlg = new nataveni_videa();
            dlg.NastavKrokUlozeni(trackBar2.Value); 
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                nahled = false;
                nazev_videa = dlg.GetCesta();
                pocet_snimku = dlg.GetFrames();
                Cursor.Current = Cursors.WaitCursor;
                progressBar1.Value = 0;
                //int w = 284;
                //int h = 214;

                int w = Image.FromFile(poleSouboru[0]).Width;
                int h = Image.FromFile(poleSouboru[0]).Height;
                /*int w = 600;
                int h = 600;*/

                AviWriter aw = new AviWriter();
                //Bitmap bmp = aw.Open("test.avi", 15, w, h);
              //  pocet_snimku = Convert.ToUInt16(trackBar2.Value);
                aw.Open(nazev_videa, pocet_snimku, w, h);
                aw.NastavNahled(0);
                Bitmap pokus = null; 
                
                //  progressBar1.Value = 20;
                int pocetsouboru = 0;
                

                for (int i = 0; i < imageList2.Images.Count; ++i)
                {
                    
                    pocetsouboru = i;
                    //bmp_ = new Bitmap(poleSouboru[i]);

                    progressBar1.Value = (((pocetsouboru + 1) * 100) / poleSouboru.GetLength(0));

                                        
                    aw.AddFrame(poleSouboru_poOdectu[i]);
                }   



                /*
                for (int i = 0; i < poleSouboru.GetLength(0); ++i)
                {
                    
                    pocetsouboru = i;
                    //bmp_ = new Bitmap(poleSouboru[i]);

                    progressBar1.Value = (((pocetsouboru + 1) * 100) / poleSouboru.GetLength(0));

                    // progressBar1.Value = progressBar1.Value+1;

                    aw.AddFrame(poleSouboru[i]);
                }
                */
                //MessageBox.Show("Hotovo " + pocetsouboru + " souborů");

                aw.Close();
                Cursor.Current = Cursors.Default;
                progressBar1.Value = 0;
                /*
                if (dlg.GetPrehrat()) {
                    
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.EnableRaisingEvents=false;
                    proc.StartInfo.FileName="wmplayer";
                    proc.StartInfo.Arguments = nazev_videa; 
                    proc.Start();
                    //proc.WaitForExit(); //CEKA NA UKONCENI MEDIA PLAYERU
                    
                    }
                */
            }

        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }


        private void PlayVideo(string videofile)
        {
            
            //-HLAVNI FUNKCE VIDEOPREHRAVANI
            string nazev_videa = videofile; //vstupni data
                        
            if (nazev_videa != null)
            {

                if (checkBox1.Checked != true)
                {
                    //CleanUp();  //Vynuluje promenne

                    m_objFilterGraph = new FilgraphManager();
                    m_objFilterGraph.RenderFile(nazev_videa);  //SPADNE POKUD SOUBOR NEEXSTUJE



                    //m_objBasicAudio = m_objFilterGraph as IBasicAudio;

                    try
                    {
                        m_objVideoWindow = m_objFilterGraph as IVideoWindow;
                        m_objVideoWindow.Owner = (int)panel7.Handle;
                        m_objVideoWindow.WindowStyle = WS_CHILD | WS_CLIPCHILDREN;
                        m_objVideoWindow.SetWindowPosition(panel7.ClientRectangle.Left,
                            panel7.ClientRectangle.Top,
                            panel7.ClientRectangle.Width,
                            panel7.ClientRectangle.Height);

                    }

                    catch (Exception)
                    {
                        m_objVideoWindow = null;
                    }




                    m_objMediaEvent = m_objFilterGraph as IMediaEvent;

                    m_objMediaEventEx = m_objFilterGraph as IMediaEventEx;
                    m_objMediaEventEx.SetNotifyWindow((int)this.Handle, WM_GRAPHNOTIFY, 0);

                    m_objMediaPosition = m_objFilterGraph as IMediaPosition;

                    m_objMediaControl = m_objFilterGraph as IMediaControl;

                    m_objMediaControl.Run();
                    m_CurrentStatus = MediaStatus.Running;

                    UpdateStatusBar();
                }
                else
                {
                    nahled_videa dlg = new nahled_videa();
                    if (dlg.ShowDialog(this) == DialogResult.OK);
                }
                //m_objFilterGraph.Stop();


                
            }
            

        
        }
        

        private void UpdateStatusBar()
        {
           /* switch (m_CurrentStatus)
            {
               // case MediaStatus.None: statusBarPanel1.Text = "Zastaveno"; break;
               // case MediaStatus.Paused: statusBarPanel1.Text = "Pauza"; break;
               // case MediaStatus.Running: statusBarPanel1.Text = "Přehrávání"; break;
               // case MediaStatus.Stopped: statusBarPanel1.Text = "Zastaveno"; break;
            }  */

            if (m_objMediaPosition != null)
            {
                int s = (int)m_objMediaPosition.Duration;
                int h = s / 3600;
                int m = (s - (h * 3600)) / 60;
                s = s - (h * 3600 + m * 60);

              //  statusBarPanel2.Text = String.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s);

                s = (int)m_objMediaPosition.CurrentPosition;
                h = s / 3600;
                m = (s - (h * 3600)) / 60;
                s = s - (h * 3600 + m * 60);

                trackBar1.Maximum = (int)m_objMediaPosition.Duration;
                trackBar1.Value = (int)m_objMediaPosition.CurrentPosition;
               // statusBarPanel3.Text = String.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s);


            }
            else
            {
               // statusBarPanel2.Text = "00:00:00";
                //statusBarPanel3.Text = "00:00:00";
            }
        }

        

        private void načístAdresářToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button4_Click(0, e);
        }

        private void nataveníOdečtuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button7_Click(0, e);
        }

        private void nastaveníVideaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button3_Click_1(0, e);
        }

        private void rozdílToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


        
        
        private void button2_Click_2(object sender, EventArgs e)
        {

            MakeSelection(3);
           
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (m_CurrentStatus == MediaStatus.Running)
            {
                UpdateStatusBar();
            }

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            m_objMediaPosition.CurrentPosition = trackBar1.Value; 
        }

        private void trackBar2_Scroll(object sender, EventArgs e)
        {
            label9.Text = Convert.ToString(trackBar2.Value); 
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private int PreviewCounter()
        {

            PreviewCount = PreviewCount+1; 


            return PreviewCount;
        }
        
        
        //private void DeleteTempFile(int _Counter)
        //{

        //    if (File.Exists("temp" + (_Counter - 1) + ".avi"))
        //    {
        //        File.Delete("temp" + (_Counter - 1) + ".avi");
        //    }       
        //}
        public int GetNahled()
        {

            return Convert.ToInt16(label9.Text);
        }
               

        public void button5_Click_1(object sender, EventArgs e) //KLIKNUTO OK v NAHLEDU
        {
            //label14.Text = "1";
                //nahled = true;
                //if (imageList2.Images.Count=0)
                if (poleSouboru_poOdectu.GetLength(0)==1)
                {


                    MessageBox.Show("Nejsou vypočteny žádné DPD.",
                    "Chyba",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1);
                    return;
                }

                 
                statusBarPanel1.Text = "Pracuji";
                trackBar1.Enabled = true;
                CleanUpVideoPreview(); //VLASTNI FUNKCE NA UKLIZENI po QuartzLib a metode RenderFile

                //
                //TODO: Pri klikani na generovani nahledu se zvesuje velikost v pameti, vyresit mazani tempsouboru
                //Druhorade: Zkusit dat bokem moznost vyberu kodeku a kvality


                uint pocet_snimku;   //promenna pro pocet snimku


                nazev_videa = "tempVid.avi";  //nazev pomocneho souboru s videem
                
               

                pocet_snimku = Convert.ToUInt16(trackBar2.Value);
                Cursor.Current = Cursors.WaitCursor;
                progressBar1.Value = 0;


                int w = Image.FromFile(poleSouboru[0]).Width;
                int h = Image.FromFile(poleSouboru[0]).Height;


                //byte[] bpic;
                //MemoryStream ms = new MemoryStream();
                //pictureBox_snapshot.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bpic = ms.ToArray();

                //if (bpic.Length < 5001 && bpic.Length > 800)
                //     m_VideoSocket.Send(bpic);

                //ms.Close();
                //ms.Dispose();



                AviWriter aw = new AviWriter();

                aw.NastavNahled(1);
                aw.Open(nazev_videa, pocet_snimku, w, h);

                //poleSouboru_poOdectu.GetLength(0)
                int pocetsouboru = 0;
               
                //for (int i = 0; i < imageList2.Images.Count; ++i)
                for (int i = 0; i < poleSouboru_poOdectu.GetLength(0)-n; ++i)
                {

                    pocetsouboru = i;


                    progressBar1.Value = (((pocetsouboru + 1) * 100) / poleSouboru.GetLength(0));


                    aw.AddFrame(poleSouboru_poOdectu[i]);
                }

                aw.Close();
                aw = null;
                Cursor.Current = Cursors.Default;
                statusBarPanel1.Text = "Připraven";
                progressBar1.Value = 0;


                //FileStream fs = File.OpenRead(nazev_videa);
                //byte[] b = new byte[fs.Length];
                //fs.Read(b, 0, b.Length);

                //fs.Read(b, 0, b.Length);
                //fs.Close();


                PlayVideo(nazev_videa);
            
            
                
                



            
            
            
        }


        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_GRAPHNOTIFY)
            {
                int lEventCode;
                int lParam1, lParam2;

                while (true)
                {
                    try
                    {
                        m_objMediaEventEx.GetEvent(out lEventCode,
                            out lParam1,
                            out lParam2,
                            0);

                        m_objMediaEventEx.FreeEventParams(lEventCode, lParam1, lParam2);

                        if (lEventCode == EC_COMPLETE)
                        {
                            m_objMediaControl.Stop();
                            m_objMediaPosition.CurrentPosition = 0;
                            m_CurrentStatus = MediaStatus.Stopped;
                            UpdateStatusBar();
                            //System.Runtime.InteropServices.Marshal.ReleaseComObject();
                            

                        }
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
            }

            base.WndProc(ref m);
        }


        //private void CleanUp()
        //{
        //    if (m_objMediaControl != null)
        //        m_objMediaControl.Stop();

        //    m_CurrentStatus = MediaStatus.Stopped;

        //    if (m_objMediaEventEx != null)
        //        m_objMediaEventEx.SetNotifyWindow(0, 0, 0);

        //    if (m_objVideoWindow != null)
        //    {
        //        m_objVideoWindow.Visible = 0;
        //        m_objVideoWindow.Owner = 0;
        //    }

        //    if (m_objMediaControl != null) m_objMediaControl = null;
        //    if (m_objMediaPosition != null) m_objMediaPosition = null;
        //    if (m_objMediaEventEx != null) m_objMediaEventEx = null;
        //    if (m_objMediaEvent != null) m_objMediaEvent = null;
        //    if (m_objVideoWindow != null) m_objVideoWindow = null;
        //    if (m_objBasicAudio != null) m_objBasicAudio = null;
        //    if (m_objFilterGraph != null) m_objFilterGraph = null;
        //    m_objFilterGraph = null;
           
        //}



        private void CleanUp()
        {
            if (this.m_objMediaControl != null)
                this.m_objMediaControl.Stop();

            this.m_CurrentStatus = MediaStatus.Stopped;

            if (this.m_objMediaEventEx != null)
                this.m_objMediaEventEx.SetNotifyWindow(0, 0, 0);

            if (this.m_objVideoWindow != null)
            {
                this.m_objVideoWindow.Visible = 0;
                this.m_objVideoWindow.Owner = 0;
            }

            if (this.m_objMediaControl != null) this.m_objMediaControl = null;
            if (this.m_objMediaPosition != null) this.m_objMediaPosition = null;
            if (this.m_objMediaEventEx != null) this.m_objMediaEventEx = null;
            if (this.m_objMediaEvent != null) this.m_objMediaEvent = null;
            if (this.m_objVideoWindow != null) this.m_objVideoWindow = null;
           // if (this.m_objBasicAudio != null) this.m_objBasicAudio = null;
            if (this.m_objFilterGraph != null) this.m_objFilterGraph = null;
            this.m_objFilterGraph = null;

            if (m_objFilterGraph != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph);
            if (m_objMediaControl != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaControl);
            if (m_objVideoWindow != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objVideoWindow);
            if (m_objMediaEventEx != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);
            if (m_objMediaPosition != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaPosition);
            if (m_objMediaEvent != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEvent);
            
            //while (System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph) > 0);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaControl);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objVideoWindow);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);

            //m_objMediaPosition
            
        }



        private void CleanUpVideoPreview()
        {
            if (m_objFilterGraph != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph);
                m_objFilterGraph = null;
            }

            if (m_objMediaControl != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaControl);
                m_objMediaControl = null;
            }


            if (m_objVideoWindow != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objVideoWindow);
                m_objVideoWindow = null;
            }



            if (m_objMediaEventEx != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);
                m_objMediaEventEx = null;
            }


            if (m_objMediaPosition != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaPosition);
                m_objMediaPosition = null;
            }


            if (m_objMediaEvent != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEvent);
                m_objMediaEvent = null;
            }
               
        
        }

      


        private void button6_Click_1(object sender, EventArgs e)
        {



            trackBar1.Enabled = false;
            trackBar1.Value = 0;

            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaControl);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objVideoWindow);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaPosition);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEvent);
            //label14.Text = PreviewCounter().ToString();
            //PreviewCounter();

            //if (this.m_objMediaControl != null) this.m_objMediaControl = null;
            //if (this.m_objMediaPosition != null) this.m_objMediaPosition = null;
            //if (this.m_objMediaEventEx != null) this.m_objMediaEventEx = null;
            //if (this.m_objMediaEvent != null) this.m_objMediaEvent = null;
            //if (this.m_objVideoWindow != null) this.m_objVideoWindow = null;
            //// if (this.m_objBasicAudio != null) this.m_objBasicAudio = null;
            //if (this.m_objFilterGraph != null) this.m_objFilterGraph = null;
            //this.m_objFilterGraph = null;


            if (m_objFilterGraph != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objFilterGraph);
                m_objFilterGraph = null;
            }

            if (m_objMediaControl != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaControl);
                m_objMediaControl = null;
            }


            if (m_objVideoWindow != null)
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objVideoWindow);
                m_objVideoWindow = null;
            }



            if (m_objMediaEventEx != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEventEx);
                m_objMediaEventEx = null;
            }


            if (m_objMediaPosition != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaPosition);
                m_objMediaPosition = null;
            }


            if (m_objMediaEvent != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objMediaEvent);
                m_objMediaEvent = null;
            }


            

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
             nahled_videa dlg = new nahled_videa ();
             if (dlg.ShowDialog(this) == DialogResult.OK)
             {
             }
        }

        public int GetKrokNahled()
        {

            //return trackBar2.Value;
            return Convert.ToInt16(label9.Text);
        }

        private void button9_Click(object sender, EventArgs e) //KLIKNUTO DELEJ DPD
        {


           
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            listView2.Clear(); //Vycisti listView
            imageList2.Images.Clear(); //Vycisti imageList2
            poleSouboru_poOdectu = null; 
            
                progressBar1.Value = 0;  //inicializuje progressbar
                Cursor.Current = Cursors.WaitCursor;  //zmena kurzoru na presypaci hodiny
                statusBarPanel1.Text = "Pracuji";
                
                n = trackBar4.Value;  //ziskame pozadovany krok


                try
                {
                    CreatePha();     //VYTVORENI matice faze, osahujici vsechny soubory a inzenzity, drive bylo zvlast
                }
                catch
                {
                    //MessageBox.Show("Nedostatek pameti" + getAvailableRAM());
                    MessageBox.Show("Nedostatek paměti. Snižte prosím rozlišení obrazů nebo jejich celkový počet. ",
                    "Chyba",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation,
                    MessageBoxDefaultButton.Button1);
                    listView1.Clear();
                    imageList1.Images.Clear();
                    button7.Enabled = false;  // znepristupni tlacitko DPD
                    dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                    Pha = null;
                    DPDMarker.Visible = false;
                    button7.Enabled = false;  // znepristupni tlacitko DPD
                    dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD

                    GC.Collect();



                    return;

                }
                
           

                
                //button6_Click();
                string nazev_souboru;
                poleSouboru_poOdectu = new string[poleSouboru.GetLength(0)];

                //ROZDIL OBRAZKU ZACINA TADY ---------------------------

                int pocetsouboru = 0;
                
                //double[, ,] maticeA = null;
                //maticeA = new double[Pha.GetLength(0), Pha.GetLength(1), 3];


                double[, ,] PoleDPD = null;
                PoleDPD = new double[Pha.GetLength(0), Pha.GetLength(1), 3];

                int[, ,] PoleDPDB = null;
                PoleDPDB = new int[Pha.GetLength(0), Pha.GetLength(1), 3];

                //double[] maticeAmax = null;
                //maticeAmax = new double[Pha.GetLength(2)];
               //if (File.Exists("tempVid.avi"))
                              
               //{
               //    File.Delete("tempVid.avi");

               //}


                
                if (Directory.Exists("phaD" + n))  //smazene slozku s predchazejicimi daty
                {
                    string[] files = Directory.GetFiles("phaD" + n);
                    foreach (string file in files)
                        File.Delete(file);
                }



                //VYTVORI ADRESAR PRO phaD ---------------
                if (!Directory.Exists("phaD" + n))
                {
                    //MessageBox.Show("Adresar neexistoal vytvarim...");
                    
                    Directory.CreateDirectory("phaD" + n);

                }
                //----------------


                
                
                double Amaxik = trackBar5.Value/10.0;

                //---------
                // double Amaxik = 1;


                string nazev = null;
                //int sx = Pha.GetLength(0);
                int sy = Pha.GetLength(1);



                progressBar1.Value = 50;
                for (int i = 0; i < Pha.GetLength(2) - n; ++i) //pres jednotlive obrazky
                {

                    for (int y = 0; y < Pha.GetLength(1); ++y)
                    {
                        //if (i == 1) textBox4.Text = "ahoj";
                        for (int x = 0; x < Pha.GetLength(0); ++x)
                        {
                            //textBox4.Text = (" " + Pha.GetLength(2));
                            
                            if (!checkBox3.Checked){  //DPD postupne
                                PoleDPD[x, y, 0] = Pha[x, y, i + n] - Pha[x, y, i]; //cervena prirustek
                                PoleDPD[x, y, 2] = 0;
                                PoleDPD[x, y, 1] = Pha[x, y, i] - Pha[x, y, i + n]; //zelena ubytek
                            }
                            else //DPD vzhledem k pocatku
                            {
                                PoleDPD[x, y, 0] = Pha[x, y, i + n] - Pha[x, y, 0]; //cervena prirustek
                                PoleDPD[x, y, 2] = 0;
                                PoleDPD[x, y, 1] = Pha[x, y, 0] - Pha[x, y, i + n]; //zelena ubytek
                               
                                //progressBar1.Value = 100;

                            }

                            
                        }//endfor x

                    }//endfor y
                    //-----------------------------------------------------

                    progressBar1.Value = 50 + (((i) * 100) / (Pha.GetLength(2) + 250));
                    

                    for (int b = 0; b < 3; ++b)
                    {
                        for (int j = 0; j < Pha.GetLength(0); ++j)
                        {
                            for (int k = 0; k < Pha.GetLength(1); ++k)
                            {
                                if (PoleDPD[j, k, b] <= 0)
                                {
                                    PoleDPD[j, k, b] = 0;
                                    PoleDPDB[j, k, b] = 0;
                                }
                                else if (PoleDPD[j, k, b] > 0)
                                {
                                    // PoleDPD[j, k, b] = (PoleDPD[j, k, b]*Amax);

                                    if ((Convert.ToInt32(PoleDPD[j, k, b] / Amaxik)) > 255)
                                    {
                                        PoleDPDB[j, k, b] = 255;

                                    }
                                    else
                                        
                                        PoleDPDB[j, k, b] = Convert.ToInt32(Math.Round(PoleDPD[j, k, b] / Amaxik)); //                Convert.ToInt32(PoleDPD[j, k, b]*Amax);


                                }


                            }



                        }

                        
                    }

                    nazev = poleSouboru[i];
                    






                    //UlozBitmapPole(PoleDPDB).Save("phad1/vysledek" + i + ".jpg", ImageFormat.Jpeg);
                    //UlozBitmapPole(PoleDPDB).Save("phad1/" + Path.GetFileName(poleSouboru[i]), ImageFormat.Tiff);

                    //UlozBitmapPole(PoleDPDB).Save("phad1/" +  (Path.GetFileName(poleSouboru[i]).Remove( (Path.GetFileName(poleSouboru[i]).Length-4), 4)) + ".jpg", ImageFormat.Jpeg);

                    
                    nazev_souboru = ("phaD" + n + "/" + (Path.GetFileName(poleSouboru[i]).Remove((Path.GetFileName(poleSouboru[i]).Length - 4), 4)) + ".Tif");

                    try
                    {
                        UlozBitmapPole(PoleDPDB).Save(nazev_souboru, ImageFormat.Tiff);
                    }

                    catch
                    {
                        MessageBox.Show("Nemohu zapisovat do svého adresáře. Nelze pokračovat.",
                     "Chyba",
                     MessageBoxButtons.OK,
                     MessageBoxIcon.Exclamation,
                     MessageBoxDefaultButton.Button1);
                        listView1.Clear();
                        imageList1.Images.Clear();
                        listView2.Clear();
                        imageList2.Images.Clear();
                        button7.Enabled = false;  // znepristupni tlacitko DPD
                        dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                        poleSouboru_poOdectu = null;
                        Pha = null;
                        PoleDPDB = null;
                        DPDMarker.Visible = false;
                        PoleDPD = null;
                        button7.Enabled = false;  // znepristupni tlacitko DPD
                        dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD

                        GC.Collect();
                        return;
                    }
                    //imageList2.Images.Add(Image.FromFile(nazev_souboru)); //ODKOMENTOVAT
                    if (Zobrazovat == 1)
                    {
                        
                        try
                        {
                            imageList2.Images.Add(Image.FromFile(nazev_souboru)); //ODKOMENTOVAT
                        }

                        catch
                        {
                            MessageBox.Show("Nedostatek paměti pro zobrazení DPD. Zkuste v dialogu výběru zdrojových dat odškrtnout volbu: Zobrazit obrazy na hlavní ploše.",
                             "Chyba",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Exclamation,
                            MessageBoxDefaultButton.Button1);
                            listView1.Clear();
                            imageList1.Images.Clear();
                            listView2.Clear();
                            imageList2.Images.Clear();
                            button7.Enabled = false;  // znepristupni tlacitko DPD
                            dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                            poleSouboru_poOdectu = null;
                            Pha = null;
                            PoleDPDB = null;
                            DPDMarker.Visible = false;
                            PoleDPD = null;
                            button7.Enabled = false;  // znepristupni tlacitko DPD
                            dPDToolStripMenuItem.Enabled = false; // znepristupni v menu polozku DPD
                            GC.Collect();
                            return;
                        }

                    }

                    poleSouboru_poOdectu[i] = nazev_souboru;
                    //progressBar1.Value = 88;

                    //UlozBitmapPole(PoleDPDB).Save("phaD" + n + "/" +  (Path.GetFileName(poleSouboru[i]).Remove( (Path.GetFileName(poleSouboru[i]).Length-4), 4)) + ".jpg", ImageFormat.Jpeg);
                    pocetsouboru = i + 1;
                    GC.Collect();
                }//endfor i
                
                
                
                MessageBox.Show("Zpracováno: " + pocetsouboru + " obraz(ů).");

                button3.Enabled = true;  // zpristupni tlacitko Ulozit
                button2.Enabled = true;  // zpristupni tlacitko Nahled
                náhledToolStripMenuItem.Enabled = true; // zpristupni v menu polozku ulozit
                uložitToolStripMenuItem.Enabled = true; // zpristupni v menu polozku nahled








                if (Zobrazovat == 1)
                {
                    // NAPLNENI OKNA VYSTUPU -------------------------------------------------------

                    listView2.View = View.LargeIcon;
                    imageList2.ImageSize = new Size(256, 204);
                    listView2.LargeImageList = imageList2;

                    //or

                    //this.listView1.View = View.SmallIcon;

                    //this.listView1.SmallImageList = this.imageList1;



                    for (int j = 0; j < imageList2.Images.Count; j++)
                    {

                        ListViewItem item = new ListViewItem();

                        item.ImageIndex = j;

                        // progressBar1.Value = (((j + 1) * 100) / imageList2.Images.Count);

                        listView2.Items.Add(item);

                    }
                }
           
            progressBar1.Value = 100;
            Cursor.Current = Cursors.Default;
            statusBarPanel1.Text = "Připraven";
            progressBar1.Value = 0;
            //sw.Stop(); //stopky
            //long cas = sw.ElapsedMilliseconds;
            //MessageBox.Show("Vypocet DPD trval:" + cas.ToString() + "ms");
            GC.Collect();
                      


        }

        private void trackBar4_Scroll(object sender, EventArgs e)
        {
            label10.Text = Convert.ToString(trackBar4.Value); 
        }

        private void trackBar5_Scroll(object sender, EventArgs e)
        {
            label13.Text = "" + trackBar5.Value / 10.0;

        }

        private void panel7_Click(object sender, EventArgs e)
        {

        }

        private void ZdrojNadpis_Click(object sender, EventArgs e)
        {
            button4_Click(0, e);
        }

        private void DPDNadpis_Click(object sender, EventArgs e)
        {
            if (button7.Enabled == true)
            {
                MakeSelection(2);
            }

            
        }

        private void NáhledNadpis_Click(object sender, EventArgs e)
        {

            if (button2.Enabled == true)
            {
                MakeSelection(3);
            }
            
        }

        
        private void UpdateStatus()
        {
            switch (m_CurrentStatus)
            {
                case MediaStatus.None: statusBarPanel1.Text = "Připraven"; break;
                case MediaStatus.Paused: statusBarPanel1.Text = "Paused "; break;
                case MediaStatus.Running: statusBarPanel1.Text = "Pracuji"; break;
                case MediaStatus.Stopped: statusBarPanel1.Text = "Stopped"; break;
            }
                        
            if (m_objMediaPosition != null)
            {

                //statusBarPanel2.Text = "214* 450"; 
                //statusBarPanel3.Text = 
            }
            else
            {
              //  statusBarPanel2.Text = "00:00:00";
               // statusBarPanel3.Text = "00:00:00";
            }
        }

        private void panel7_MouseClick(object sender, MouseEventArgs e)
        {
            //nahled_videa dlg = new nahled_videa();
            //if (dlg.ShowDialog(this) == DialogResult.OK)
            //{

            //}
        }

        private void panel7_ControlAdded(object sender, ControlEventArgs e)
        {

        }

        private void vyčistitToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void dPDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MakeSelection(2);
        }

        private void náhledToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MakeSelection(3);
        }

        private void uložitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button3_Click_1(0, e);
        }

        private void panel7_Paint(object sender, PaintEventArgs e)
        {

        }

        private void oAplikaciToolStripMenuItem_Click(object sender, EventArgs e)
        {

            About dlg = new About();
            dlg.ShowDialog();
        }

        private void DPDNadpis_Paint(object sender, PaintEventArgs e)
        {
            
        }

        private void oAplikaciToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            About dlg = new About();
            dlg.ShowDialog();
        }
    }
}
