using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WIA;
using System.Runtime.InteropServices;

using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.CvEnum;
using Emgu.CV.UI;
using System.Threading;

namespace Foto_Scanner_New
{
    /// <summary>
    /// Main Class of application.
    /// </summary>
    public partial class Form1 : Form
    {
        //------------------------------------------------------------
        // Properties 
        //------------------------------------------------------------
        
        public string working_sir_path = "NONE";
        MainFormPropertiescs mainProps = null;

        // Images
        Image<Bgr, Byte> imgOriginal = null;
        Image<Bgr, Byte> imgOriginalProcessing = null;
        Image<Gray, Byte> imgGray = null;
        Image<Gray, Byte> imgBin = null;
        Image<Bgr, Byte> imgBinRGB = null;

        // List of images
        List <DetectedRectangles> list = null;

        // Dictionary for detected images
        Dictionary<int, DetectedRectangles> myList = null;

        // Helpers
        bool porcent_50 = false;
        int oldThresh = -1;
        string dir_name_num = "";
        int perimeter = 0;
        bool perimeterBool = false;
        int _dpi = 300;

        /// <summary>
        /// Initialize components and load properties.
        /// </summary>
        public Form1()
        {
            // Load properties
            mainProps = new MainFormPropertiescs();
            InitializeComponent();
            InitCheckBoxes();
        }

        /// <summary>
        /// Eventhandler - Create new album or open existing album.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void albumÖffnenErstellenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            open_create_Dir();
        }

        /// <summary>
        /// Eventhandler - Icon: Scan image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void scannenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // ----------------------------------------------------------------------
            // 1 - Scan image 
            // ----------------------------------------------------------------------
            string pathToScannedImage = null;
            pathToScannedImage = scan_image(_dpi);

            //just for tests
            //pathToScannedImage = "E:\\Tmp\\1.jpeg";

            if (pathToScannedImage == null || pathToScannedImage.Equals(""))
            {
                MessageBox.Show("Can't load scanned image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // ----------------------------------------------------------------------
                // 2 - Segment image
                // ----------------------------------------------------------------------
                segmentImage(pathToScannedImage);
            }
        }

        /// <summary>
        /// Eventhandler - Exit.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void beendenToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
            System.Environment.Exit(1);
        }
        
        /// <summary>
        /// Eventhandler - Show help.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hilfeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Show help
            Help h = new Help();
            h.ShowDialog();
        }

        /// <summary>
        /// Load main form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            // Set status text
            mainProps.StatusText = MainFormPropertiescs.getDirAlbums();
            this.toolStripStatusLabel1.Text = "Arbeitsverzeichnis: " + mainProps.StatusText;

            // Controls deactivate
            enable_true(true);
        }

        /// <summary>
        /// Eventhandler - Menue: Open.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonOpen_Click(object sender, EventArgs e)
        {
            open_create_Dir();
        }

        /// <summary>
        /// Eventhandler - TrackBar for Trahsolding.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trackBarThreshold_Scroll(object sender, EventArgs e)
        {
            this.label1.Text = "Threshold: " + trackBarThreshold.Value;
            int threshValue = trackBarThreshold.Value;
            
            // Segment image
            
            CvInvoke.cvThreshold(imgGray, imgBin, threshValue, 255, THRESH.CV_THRESH_BINARY);
           
            imgBinRGB = imgOriginal.CopyBlank();
            imgBinRGB[0] = imgBin;
            imgBinRGB[1] = imgBin;
            imgBinRGB[2] = imgBin;

            // Display binary image
            this.pictureBoxSegmentation.Image = imgBinRGB.ToBitmap();

            // Filter Image
            
            // Get list with detected rectangles
            myList = CVUtils.detectRectangles(imgBin, threshValue, myList, porcent_50, this.perimeter, perimeterBool);

            foreach (KeyValuePair<int, DetectedRectangles> pair in myList)
            {
                int key = pair.Key;
                DetectedRectangles dr = pair.Value;

                if (dr!=null) {

                    int[] positions = getPosForDraw(dr.Rect);
                
                    MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                    CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                
                    if (dr != null)
                    {
                        enableCheckBoxes(key, true);
                        imgBinRGB.Draw(dr.Rect, new Bgr(Color.Red), 15);
                        imgBinRGB.Draw("Foto_" + dr.Number, ref font, new Point(positions[0], positions[1]), new Bgr(Color.Red));
                        this.pictureBoxSegmentation.Image = imgBinRGB.ToBitmap();
                    }
                }
            }
        }

        /// <summary>
        /// EventHandler - Scan Image Icon
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonScan_Click(object sender, EventArgs e)
        {
            bool ok = false;
            // ----------------------------------------------------------------------
            // 1 - Scan image 
            // ----------------------------------------------------------------------
            string pathToScannedImage = null;
            try
            {
                pathToScannedImage = scan_image(_dpi);
                if (pathToScannedImage.Equals("fail"))
                    ok = false;
                else
                    ok = true;
            }
            catch (NullReferenceException) { 
            }
            catch (Exception e1)
            {
                MessageBox.Show("Foto wurde nich gescannt!.\nDetails: " + e1.Message + "", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ok = false;
            }
            

            this.label2.Text = "Dateiname: " + "";

            //just for tests
            //pathToScannedImage = "E:\\Tmp\\1.jpeg";
            if (ok)
            {
                if (pathToScannedImage == null || pathToScannedImage.Equals(""))
                {
                    MessageBox.Show("Can't load scanned image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    // ----------------------------------------------------------------------
                    // 2 - Segment image
                    // ----------------------------------------------------------------------
                    segmentImage(pathToScannedImage);

                }
            }
        }


        /// <summary>
        /// Eventhandler - Send detected images to next form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCut_Click(object sender, EventArgs e)
        {
            // Gets all detected rectanlges (red and green)
            //myList.ToList()
            List<Image<Bgr, Byte>> imgs = CVUtils.getDetectedImagesFromInput(myList, imgOriginalProcessing);
            if (imgs != null && imgs.Count > 0) {
                int a = 1;
                FotoDetail detaisl = new FotoDetail(imgs, mainProps.StatusText, this.dir_name_num);
                detaisl.ShowDialog();
            }
        }

        /// <summary>
        /// Eventhandler - Import existing image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fotoImportierenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*enable_true(true);
            
            perimeter = 0;

            // Initial CheckBox Dictionary

            myList = new Dictionary<int, DetectedRectangles>();
            myList.Add(1, null);
            myList.Add(2, null);
            myList.Add(3, null);
            myList.Add(4, null);
            myList.Add(5, null);
            myList.Add(6, null);
            myList.Add(7, null);
            myList.Add(8, null);
            myList.Add(9, null);
            myList.Add(10, null);

            string Pfad = string.Empty;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            string newPath = mainProps.StatusText.Replace('/', '\\');
            openFileDialog1.InitialDirectory = newPath;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Filter = "All files (*.*)|*.*|jpg files (*.jpg)|*.jpg|jpeg files (*.jpeg)|*.jpeg|png files (*.png)|*.png";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                Pfad = openFileDialog1.FileName;

            if (!Pfad.Equals("")) {
                string f_name = "";
                try
                {
                    FileInfo f = new FileInfo(Pfad);
                    f_name = f.Name;
                    f_name = f_name.Substring(0, f_name.IndexOf("."));

                    
                }
                catch (Exception e1) {
                    f_name = "Image_Import";
                }

                this.dir_name_num = f_name;
               
                segmentImage(Pfad);
            }*/

            import();
        }

        /// <summary>
        /// Changes the background color of a checkbox.
        /// </summary>
        /// <param name="sender">CheckBox</param>
        /// <param name="type">Color</param>
        private void changeColor(object sender, string type)
        {
            CheckBox chk = (CheckBox)sender;
            Console.Out.WriteLine(chk.BackColor);
            if (type.Equals("GREEN"))
            {
                chk.BackColor = Color.Green;
            }
            else
            {
                chk.BackColor = Control.DefaultBackColor;
            }

            chk.Update();
        }

        // ----------------------------------------------------------------------------------------
        // - Methods ------------------------------------------------------------------------------
        //-----------------------------------------------------------------------------------------

        /// <summary>
        /// Open or create a working directory.
        /// </summary>
        private void open_create_Dir()
        {
            list = null;

            // File dialog
            folderBrowserDialog1.Description = "Bitte im Verzeichnis Fotoalben ein Album auswählen oder ein neues Album erstellen.";
            string path = MainFormPropertiescs.getDirAlbums();
            string pathNew = path.Replace('/', '\\');
            folderBrowserDialog1.SelectedPath = pathNew;
            folderBrowserDialog1.ShowDialog();
            
            // Set status text
            mainProps.StatusText = this.folderBrowserDialog1.SelectedPath + "/";
            this.toolStripStatusLabel1.Text = "Arbeitsverzeichnis: " + mainProps.StatusText;
            mainProps.StatusText = this.folderBrowserDialog1.SelectedPath + "/";
        }

        /// <summary>
        /// Returns file path of the scanned image. 
        /// </summary>
        /// <returns>Path of scanned image</returns>
        private string scan_image(int dpi)
        {
            ScanMODE2 mode = new ScanMODE2(dpi);
            mode.ShowDialog();

            int _modus = ScanMODE2.Mod;
            dpi = ScanMODE2.DPI;
            double HH = ScanMODE2._ho;
            double BB = ScanMODE2._br;
            Console.Out.WriteLine("----------------------------------");
            Console.Out.WriteLine("Selected MODUS: " + _modus);
            Console.Out.WriteLine("DPI           : " + dpi);
            Console.Out.WriteLine("Hoehe         : " + HH);
            Console.Out.WriteLine("Breite        : " + BB);
            Console.Out.WriteLine("----------------------------------");

            if (ScanMODE2.buttonOK)
            {

                enable_true(true);
                list = null;
                string file_path = null;
                perimeter = 0;

                int dirNum = MainFormPropertiescs.getNumberOfScansInDir(this.mainProps.StatusText) + 1;
                string dirName = "scan_" + dirNum;
                this.dir_name_num = dirName;
                string tmpScanDir = this.mainProps.StatusText + dirName;
                string fileName1 = tmpScanDir + "/" + dirName + ".jpg";

                // Initial CheckBox Dictionary

                myList = new Dictionary<int, DetectedRectangles>();
                myList.Add(1, null);
                myList.Add(2, null);
                myList.Add(3, null);
                myList.Add(4, null);
                myList.Add(5, null);
                myList.Add(6, null);
                myList.Add(7, null);
                myList.Add(8, null);
                myList.Add(9, null);
                myList.Add(10, null);

                //----------------------------------------------------------------------------------
                // Scan image
                //----------------------------------------------------------------------------------

                //const string tmp_path_scan = "/scan_tmp.png";

                if (_modus != 5)
                {
                    CommonDialogClass commonDialogClass = null;
                    try
                    {
                        commonDialogClass = new CommonDialogClass();

                    }
                    catch
                    {
                        throw new Exception();
                    }

                    // Create scanner device
                    Device scannerDevice = null;
                    try
                    {

                        scannerDevice = commonDialogClass.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);

                    }
                    catch (COMException e1)
                    {
                        MessageBox.Show("No scanner device found!\n" + "Details: " + e1.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        scannerDevice = null;
                        file_path = null;
                        return "fail";
                    }

                    // Scanner device found
                    if (scannerDevice != null)
                    {
                        DeviceManager manager = new DeviceManagerClass();
                        Device d = null;
                        foreach (DeviceInfo info in manager.DeviceInfos)
                        {
                            if (info.DeviceID == scannerDevice.DeviceID)
                            {
                                d = info.Connect();
                                break;
                            }
                        }

                        // Scanner item
                        Item scannnerItem = scannerDevice.Items[1];
                        Console.Out.WriteLine(scannnerItem.Formats.ToString());
                        // Ajdust scanner settings

                        foreach (Property prop in scannnerItem.Properties)
                        {
                            var temp = prop.Name + " " + prop.PropertyID + " " + prop.get_Value();
                            Console.Out.WriteLine(temp);
                        }
                        int MODE = _modus;
                        ScanUtils.SetSannerSettings(scannnerItem, dpi, 0, 0, 0, 0, 0, 0, MODE, BB, HH);

                        // Get scan result
                        object scanResult = commonDialogClass.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false);
                        /*object scanResult  = commonDialogClass.ShowAcquireImage(
                             WiaDeviceType.ScannerDeviceType,
                             WiaImageIntent.UnspecifiedIntent,
                             WiaImageBias.MaximizeQuality,
                             FormatID.wiaFormatPNG,
                             true, true, false);*/

                        bool imageSaved = false;
                        if (scanResult != null)
                        {
                            Directory.CreateDirectory(tmpScanDir);
                            ImageFile image = (ImageFile)scanResult;
                            string currentPath = Directory.GetCurrentDirectory();
                            //string fileName = currentPath + tmp_path_scan;
                            string fileName = fileName1;
                            //Save scanned image
                            imageSaved = ScanUtils.SaveImageToPNGFile(image, fileName);
                        }

                        // If scan was successful
                        if (!imageSaved)
                        {
                            MessageBox.Show("Image wasn't scanned!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            file_path = null;
                        }
                        else if (imageSaved)
                        {
                            //TODO
                            //MessageBox.Show("Image scanned!", "Scannen", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            file_path = fileName1;
                        }

                        return file_path;
                    }
                }
                else if (_modus == 5)
                {
                    Console.Out.WriteLine("USE IV");
                    //i_view32.exe /dpi = (300,300) /scanhidden /convert
                    //Save scanned image
                    bool imageSaved2 = false;

                    string fileName = fileName1;
                    string imageSavedString = "";

                    //CVUtils.runIVScan(fileName);
                    //string imageSavedString = CVUtils.runIVScan(fileName);

                    if (!fileName.Equals(""))
                    {
                        Directory.CreateDirectory(tmpScanDir);
                        string currentPath = Directory.GetCurrentDirectory();
                        //string fileName = currentPath + tmp_path_scan;
                        fileName = fileName1;
                        //Save scanned image
                        imageSavedString = CVUtils.runIVScan(fileName, dpi, false);
                    }

                    if (imageSavedString.Equals("")) imageSaved2 = false;
                    else imageSaved2 = true;

                    // If scan was successful
                    if (!imageSaved2)
                    {
                        MessageBox.Show("Image wasn't scanned!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        file_path = null;
                    }
                    else if (imageSaved2)
                    {
                        //TODO
                        //MessageBox.Show("Image scanned!", "Scannen", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        fileName1 = fileName1.Replace("/", "\\");
                        Console.Out.WriteLine(fileName1);
                        file_path = fileName1;
                    }

                    return file_path;


                }
            }
            return null;
        }

        /// <summary>
        /// Converts original image to grayscale image and creats a binary image.
        /// Threshold for segmentation is calculated with the Otsu method.
        /// </summary>
        /// <param name="pathToScannedImage">Path to the original image</param>
        private void segmentImage(string pathToScannedImage) 
        {
            del();
            // Image loaded OK
            if (File.Exists(pathToScannedImage))
            {
                
                imgOriginal = new Image<Bgr, Byte>(pathToScannedImage);
                imgOriginalProcessing = new Image<Bgr, Byte>(pathToScannedImage);
                 
                //Show Original image
                this.pictureBoxOroginal.Image = imgOriginal.ToBitmap();
                if (imgOriginal != null)
                {
                    enable_false();
                        
                    // Convert to gray
                    imgGray = imgOriginal.Convert<Gray, Byte>();
                    //imgGray = imgGray.PyrUp().PyrDown();
                    imgBin = imgGray.CopyBlank();
                    double threshValue = CvInvoke.cvThreshold(imgGray, imgBin, 0.0, 255.0, THRESH.CV_THRESH_OTSU);
                    if (oldThresh == -1) {
                        oldThresh = trackBarThreshold.Value = Convert.ToInt32(threshValue);
                    }
                        
                    // Set threshold value
                    trackBarThreshold.Value = Convert.ToInt32(threshValue);
                    label1.Text += threshValue;
                        
                    // Display binary image
                    imgBinRGB = imgOriginal.CopyBlank();
                    imgBinRGB[0] = imgBin;
                    imgBinRGB[1] = imgBin;
                    imgBinRGB[2] = imgBin;

                    this.pictureBoxSegmentation.Image = imgBinRGB.ToBitmap();
                    this.pictureBoxSegmentation.Image = imgOriginal.ToBitmap();

                }
            }
            // Cant load image
            else if (!File.Exists(pathToScannedImage))
            {
                MessageBox.Show("Can't load scanned image, or no Scanner detected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Disables main controls.
        /// </summary>
        private void enable_true(bool all)
        {
            if (all)
            {
                this.groupBoxRects.Enabled = false;
                this.trackBarThreshold.Enabled = false;
                this.label1.Enabled = false;
                this.pictureBoxOroginal.Image = null;
                this.pictureBoxSegmentation.Image = null;
                this.label1.Text = "Threshold: ";
                this.trackBarThreshold.Value = 0;
                
            }
            this.checkBoxRect1.Checked = false;
            this.checkBoxRect1.Visible = false;

            this.checkBoxRect2.Checked = false;
            this.checkBoxRect2.Visible = false;

            this.checkBoxRect3.Checked = false;
            this.checkBoxRect3.Visible = false;

            this.checkBoxRect4.Checked = false;
            this.checkBoxRect4.Visible = false;

            this.checkBoxRect5.Checked = false;
            this.checkBoxRect5.Visible = false;

            this.checkBoxRect6.Checked = false;
            this.checkBoxRect6.Visible = false;

            this.checkBoxRect7.Checked = false;
            this.checkBoxRect7.Visible = false;

            this.checkBoxRect8.Checked = false;
            this.checkBoxRect8.Visible = false;

            this.checkBoxRect9.Checked = false;
            this.checkBoxRect9.Visible = false;

            this.checkBoxRect10.Checked = false;
            this.checkBoxRect10.Visible = false;
        }

        /// <summary>
        /// Enables main controls.
        /// </summary>
        private void enable_false()
        {
            this.groupBoxRects.Enabled = true;
            this.trackBarThreshold.Enabled = true;
            this.label1.Enabled = true;
            this.checkBox1.Enabled = true;
        }

        /// <summary>
        /// Enable / Disable check boxes.
        /// </summary>
        /// <param name="number">Number of check box</param>
        /// <param name="status">True or false : enable or disable</param>
        public void enableCheckBoxes(int number, bool status)
        {
            switch (number) 
            {
                case 1: this.checkBoxRect1.Visible = status; break;
                case 2: this.checkBoxRect2.Visible = status; break;
                case 3: this.checkBoxRect3.Visible = status; break;
                case 4: this.checkBoxRect4.Visible = status; break;
                case 5: this.checkBoxRect5.Visible = status; break;
                case 6: this.checkBoxRect6.Visible = status; break;
                case 7: this.checkBoxRect7.Visible = status; break;
                case 8: this.checkBoxRect8.Visible = status; break;
                case 9: this.checkBoxRect9.Visible = status; break;
                case 10: this.checkBoxRect10.Visible = status; break;
            }
        }
            
        /// <summary>
        /// Gets size for drawing text
        /// </summary>
        /// <param name="dr">Rectangles</param>
        /// <returns>Size of text</returns>
        private int[] getPosForDraw(Rectangle dr) 
        {
            int x = dr.Width;
            x = (int)(x / 200);
            
            int w = (dr.Left + (dr.Width / 2)) - x * 50;
            int h = (dr.Top + (dr.Height / 2)) + x;

            //if (x <= 5) x = 5;

            return new int[] {w, h, x};
        }

        /// <summary>
        /// Initialize check bocex
        /// </summary>
        private void InitCheckBoxes()
        {
            this.checkBoxRect1.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect2.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect3.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect4.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect5.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect6.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect7.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect8.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect9.CheckedChanged += chkCheckedChanged;
            this.checkBoxRect10.CheckedChanged += chkCheckedChanged;
        }

        /// <summary>
        /// Import existing image method. 
        /// </summary>
        private void import()
        {
            del();

            enable_true(true);

            perimeter = 0;

            // Initial CheckBox Dictionary

            myList = new Dictionary<int, DetectedRectangles>();
            myList.Add(1, null);
            myList.Add(2, null);
            myList.Add(3, null);
            myList.Add(4, null);
            myList.Add(5, null);
            myList.Add(6, null);
            myList.Add(7, null);
            myList.Add(8, null);
            myList.Add(9, null);
            myList.Add(10, null);

            string Pfad = string.Empty;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            string newPath = mainProps.StatusText.Replace('/', '\\');
            openFileDialog1.InitialDirectory = newPath;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Filter = "All files (*.*)|*.*|jpg files (*.jpg)|*.jpg|jpeg files (*.jpeg)|*.jpeg|png files (*.png)|*.png";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                Pfad = openFileDialog1.FileName;

            if (!Pfad.Equals(""))
            {
                string f_name = "";
                try
                {
                    FileInfo f = new FileInfo(Pfad);
                    f_name = f.Name;
                    f_name = f_name.Substring(0, f_name.IndexOf("."));

                    this.label2.Text = "Dateiname: " + f_name;

                }
                catch (Exception e1)
                {
                    f_name = "Image_Import";
                }

                this.dir_name_num = f_name;

                segmentImage(Pfad);
            }
        }

        // ----------------------------------------------------------------------------------------
        // - Methods end --------------------------------------------------------------------------
        //-----------------------------------------------------------------------------------------

        /// <summary>
        /// Eventhander check boxes: Draw rectangles in original image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkCheckedChanged(object sender, EventArgs e)
        {
            if (imgOriginal != null)
            {
                Image<Bgr, Byte> imgOriginalForDrawing = null;

                try
                {  

                    imgOriginalForDrawing = imgOriginal.Copy();
                    this.pictureBoxOroginal.Image = imgOriginalForDrawing.ToBitmap();

                    Thread.Sleep(50);

                    this.pictureBoxOroginal.Update();
                }
                catch (Exception boxError){ 
                    // Just to console
                    //this.pictureBoxOroginal.Image = null;
                    this.pictureBoxOroginal.Image = imgOriginalForDrawing.ToBitmap();
                    Thread.Sleep(100);
                    Console.Out.WriteLine("Exception: " + boxError.ToString());  
                }
 
                if (myList != null && imgOriginalForDrawing != null)
                {
                    int index = -1;
                    CheckBox chk = (CheckBox)sender;

                    switch (chk.Name)
                    {
                        case MainFormPropertiescs.CH1: index = 1; break;
                        case MainFormPropertiescs.CH2: index = 2; break;
                        case MainFormPropertiescs.CH3: index = 3; break;
                        case MainFormPropertiescs.CH4: index = 4; break;
                        case MainFormPropertiescs.CH5: index = 5; break;
                        case MainFormPropertiescs.CH6: index = 6; break;
                        case MainFormPropertiescs.CH7: index = 7; break;
                        case MainFormPropertiescs.CH8: index = 8; break;
                        case MainFormPropertiescs.CH9: index = 9; break;
                        case MainFormPropertiescs.CH10: index = 10; break;
                    }

                    foreach (KeyValuePair<int, DetectedRectangles> pair in myList)
                    {

                        DetectedRectangles tmpRect = pair.Value;

                        if (tmpRect != null)
                        {

                            DetectedRectangles tmp = null;
                            if (tmpRect.Number == index) tmp = tmpRect;

                            if (tmp != null)
                            {
                                bool check = chk.Checked;
                                if (check)
                                {
                                    tmpRect.Use = true;
                                }
                                else
                                {
                                    tmpRect.Use = false;
                                }
                            }
                        }
                    }

                    // Draw selected rectangles
                    Rectangle r;
                    Bgr color = new Bgr(Color.Green);
                    MCvFont font;
                    int[] positions;
                    if (this.checkBoxRect1.Checked)
                    {
                        r = myList[1].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 15);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "1", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect2.Checked)
                    {
                        r = myList[2].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 15);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect3.Checked)
                    {
                        r = myList[3].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect4.Checked)
                    {
                        r = myList[4].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect5.Checked)
                    {
                        r = myList[5].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect6.Checked)
                    {
                        r = myList[6].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect7.Checked)
                    {
                        r = myList[7].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect8.Checked)
                    {
                        r = myList[8].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect9.Checked)
                    {
                        r = myList[9].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }
                    if (this.checkBoxRect10.Checked)
                    {
                        r = myList[10].Rect;
                        positions = getPosForDraw(r);
                        imgOriginalForDrawing.Draw(r, color, 5);
                        font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2]);
                        CvInvoke.cvInitFont(ref font, FONT.CV_FONT_HERSHEY_SIMPLEX, positions[2], positions[2], 0, positions[2] * 3, LINE_TYPE.CV_AA);
                        imgOriginalForDrawing.Draw("Foto_" + "2", ref font, new Point(positions[0], positions[1]), new Bgr(Color.Green));
                    }

                }

                this.pictureBoxOroginal.Image = imgOriginalForDrawing.ToBitmap();
                this.pictureBoxOroginal.Update();
            }
        }

        /// <summary>
        /// Eventhandler - Check box cahanges
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                this.porcent_50 = true;
            else if (!checkBox1.Checked)
                this.porcent_50 = false;

            myList = new Dictionary<int, DetectedRectangles>();
            myList.Add(1, null);
            myList.Add(2, null);
            myList.Add(3, null);
            myList.Add(4, null);
            myList.Add(5, null);
            myList.Add(6, null);
            myList.Add(7, null);
            myList.Add(8, null);
            myList.Add(9, null);
            myList.Add(10, null);

            this.pictureBoxSegmentation.Image = this.imgBinRGB.ToBitmap();
            this.pictureBoxSegmentation.Update();

            enable_true(false);
            this.trackBarThreshold.Value = oldThresh;
        }

      
        /// <summary>
        /// Eventhandler - Open extras dialog.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (imgOriginal == null)
            {
                MessageBox.Show("Keine Datei geöffnet... !", "Warnung", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                int faktor = 1;
                int biggerSize = 0;
                Image<Bgr, Byte> imgScale = imgOriginal.Copy();
                int ww = imgScale.Width;
                int hh = imgScale.Height;
                if (ww >= hh) biggerSize = ww;
                else biggerSize = hh;

                while (biggerSize >= 1200)
                {
                    imgScale = imgScale.Resize(0.5, INTER.CV_INTER_LINEAR);
                    faktor = faktor * 2;
                    int w = imgScale.Width;
                    int h = imgScale.Height;

                    if (w >= h) biggerSize = w;
                    else biggerSize = h;
                }

                Extras extra = new Extras(imgScale, faktor);

                if (extra.ShowDialog(this) == DialogResult.OK)
                {
                    // Read the contents of testDialog's TextBox.
                    int tmp = extra.ergebnis * faktor;
                    this.perimeter = Convert.ToInt32(extra.ergebnis);
                    this.checkBoxPerim.Enabled = true;
                    this.checkBoxPerim.Checked = true;
                    this.checkBoxPerim.Text = "Foto-Umfang: " + this.perimeter;
                }
                else
                {
                    this.perimeter = 0;
                }
                extra.Dispose();

            }
        }

        /// <summary>
        /// Eventhandler - Use perimeter function.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            enable_true(true);

            myList = new Dictionary<int, DetectedRectangles>();
            myList.Add(1, null);
            myList.Add(2, null);
            myList.Add(3, null);
            myList.Add(4, null);
            myList.Add(5, null);
            myList.Add(6, null);
            myList.Add(7, null);
            myList.Add(8, null);
            myList.Add(9, null);
            myList.Add(10, null);

            if (this.checkBoxPerim.Checked)
            {
                perimeterBool = true;
            }
            else {
                perimeterBool = false;
            }
        }

        /// <summary>
        /// Eventhanlder - Import existing image (Icon).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            import();
        }

        /// <summary>
        /// Delets objects.
        /// </summary>
        private void del()
        {
            imgOriginal = null;
            imgOriginalProcessing = null;
            imgGray = null;
            imgBin = null;
            imgBinRGB = null;
        }

        /// <summary>
        /// Handler - Settings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void einstellungenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings s = new Settings(_dpi);
            if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //Console.Out.WriteLine("OK click");
                _dpi = s.getDPI();
            }
        }
      
    }
}
