using System;
using System.IO;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using MetroFramework.Components;
using MetroFramework.Forms;
using System.Collections.Generic;

namespace BulkTap3
{
    public partial class Main_frm : MetroForm
    {
        public object lb_item = null;

        /// <summary>
        ///  intionat the froms
        /// </summary>
        Filterbyevent Event_filterfrm = new Filterbyevent();
        FilterIMEI filterfrm = new FilterIMEI();
        FilterIMEI IMEI_filterfrm = new FilterIMEI();
        Filter_Duration Duration_filterfrm = new Filter_Duration();
        FilrerbyDate Date_filterfrm = new FilrerbyDate();
        Find Findfrm = new Find();
        Goto Gotofrm = new Goto();
        InsertFrm insertfrm = new InsertFrm();
        Insert_Seq insertSeqfrm = new Insert_Seq();

        public Main_frm()
        {
            InitializeComponent();
            MainSplit.SplitterWidth = 20;
            FunctionSplit.SplitterWidth = 20;
            Tools_sliters.SplitterWidth = 20;
        }

        private void Main_frm_Load(object sender, EventArgs e)
        {

        }

        private void metroButton1_Click(object sender, EventArgs e)
        {
            System.Drawing.Graphics graphics = this.CreateGraphics();
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
                50, 100, 150, 150);
            //graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
            graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
        }

        private void FunctionSplit_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }





        private void Hideall()
        {
            FATgrp.Visible = false;
            findreplacegrp.Visible = false;
            Filter_grp.Visible = false;
            Split_grp.Visible = false;
            Notification_File_grp.Visible = false;
            merge_grp.Visible = false;
        }

        private void Filter_cb_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void Split_rb1_CheckedChanged(object sender, EventArgs e)
        {
            if (Split_rb1.Checked)
            {
                Split_DGV.Columns[2].HeaderText = "Parts";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 32767;

            }
            else
            {
                Split_DGV.Columns[2].HeaderText = "Timestamp";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 14;
            }
        }

        private void Split_rb2_CheckedChanged(object sender, EventArgs e)
        {
            if (Split_rb1.Checked)
            {
                Split_DGV.Columns[2].HeaderText = "Parts";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 32767;

            }
            else
            {
                Split_DGV.Columns[2].HeaderText = "Timestamp";
                ((DataGridViewTextBoxColumn)Split_DGV.Columns[2]).MaxInputLength = 14;
            }
        }



        private void merge_clear_btn_Click(object sender, EventArgs e)
        {
            merge_tree.Nodes.Clear();
            /* if (filenamelist.Items.Count > 0)
             {
                 for (int counter = 0; counter < filenamelist.Items.Count; counter++)
                 {
                     merge_tree.Nodes.Add(filenamelist.Items[counter].ToString());
                 }
             }*/
        }

        private void FunctionSplit_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Notificaton_file_op2_CheckedChanged(object sender, EventArgs e)
        {
            Note_pnl.Enabled = true;
        }

        private void Notificaton_file_op1_CheckedChanged(object sender, EventArgs e)
        {
            Note_pnl.Enabled = false;
        }

        private void Note_create_btn_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            string filename;
            int seq_from, seq_to;
            if (Note_Type_op1.Checked == true)
                filename = "CD";
            else
                filename = "TD";
            filename += Note_sender_txt.Text;
            filename += Note_recip_txt.Text;
            if (!int.TryParse(Note_seq_from_txt.Text, out seq_from))
                MessageBox.Show("Error in Sequance");
            if (!int.TryParse(Note_seq_to_txt.Text, out seq_to))
                MessageBox.Show("Error in Sequance");

            DateTime LTS;// to get past tow days
            LTS = DateTime.Now.AddDays(-2);
            TotalProcessBar.Maximum = seq_to - seq_from + 1;
            TotalProcessBar.Value = 0;
            for (int count = seq_from; count <= seq_to; count++)
            {
                //ProcessBar.Value = 0;
                string seq = String.Format("{0:D5}", count);
                functions.Create_Notifications(fldbd.SelectedPath + "\\" + filename + seq, Note_sender_txt.Text, Note_recip_txt.Text, seq, LTS.ToString("yyyyMMddHHmmss"), Note_ver_txt1.Text, Note_ver_txt2.Text);
                //ProcessBar.Value = 100;
                TotalProcessBar.Value += 1;
            }
            //ProcessBar.Value = 0;
            MessageBox.Show("Done!");
        }
        private void Split_DGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            TextBox tb = e.Control as TextBox;
            if (Split_DGV.CurrentCell.ColumnIndex == 2) //Desired Column
            {

                e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress);

                if (tb != null)
                {
                    tb.KeyPress -= new KeyPressEventHandler(Column2_KeyPress);
                    tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);

                }
                e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
            }
            if (Split_DGV.CurrentCell.ColumnIndex == 3)
            {

                e.Control.KeyPress += new KeyPressEventHandler(Column2_KeyPress);
                TextBox tb1 = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
                    tb.KeyPress += new KeyPressEventHandler(Column2_KeyPress);

                }
                e.Control.KeyPress -= new KeyPressEventHandler(Column2_KeyPress);
            }

        }
        private void Column1_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

        }
        private void Column2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != ',')
            {
                e.Handled = true;
            }
            int count = 0;
            foreach (char comma in (sender as TextBox).Text)
                if (comma == ',')
                    count++;

            int part = 0;
            if (Split_rb1.Checked)
                part = int.Parse(Split_DGV.CurrentRow.Cells[2].Value.ToString());
            else
                part = 2;


            if ((sender as TextBox).Text.Length > 0)
            {
                if ((sender as TextBox).Text[(sender as TextBox).Text.Length - 1].ToString() == "," && e.KeyChar == ',')
                {
                    e.Handled = true;
                }
            }
            if (e.KeyChar == ',' && count == part - 1)
            {
                e.Handled = true;
            }
        }

        private void Split_DGV_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (Split_DGV.Columns[e.ColumnIndex].Name == "Parts")
            {
                if (String.IsNullOrEmpty(Split_DGV.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString()))
                {
                    Split_DGV.Rows[e.RowIndex].ErrorText =
                        "Company Name must not be empty";
                    //Split_DGV.Rows[e.RowIndex].Cells[e.ColumnIndex] = "";
                }
            }
        }

        private void merge_tree_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;


        }

        private void merge_tree_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            // dropnode=treeView2.GetNodeAt(e.X, e.Y);
            Point pt = new Point(e.X, e.Y);

            // Convert to a point in the TreeView's coordinate system.
            pt = merge_tree.PointToClient(pt);
            merge_tree.SelectedNode = merge_tree.GetNodeAt(pt);
            if (merge_tree.SelectedNode != null)
            {
                for (i = 0; i < s.Length; i++)
                    merge_tree.SelectedNode.Nodes.Add(s[i]).Checked = true;
                merge_tree.SelectedNode.Checked = true;
            }
            //treeView2.Nodes.Add( dropnode  );
        }
        private void Notificaton_file_op3_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            OFD.ShowDialog();

            if (File.Exists(OFD.FileName))
            {
                using (StreamReader sr = File.OpenText(OFD.FileName))
                {
                    string line = "";
                    string TC = "";
                    string Sender = "";
                    string Recipiant = "";
                    string Seq = "";
                    string ver = "";
                    string res = "";
                    //TotalProcessBar.Maximum = sr.
                    while ((line = sr.ReadLine()) != null)
                    {

                        string[] split = line.Split(',');
                        if (split[0].Length == 17)
                        {
                            TC = split[0].Substring(0, 2);
                            Sender = split[0].Substring(2, 5);
                            Recipiant = split[0].Substring(7, 5);
                            Seq = split[0].Substring(12, 5);
                        }
                        if (split[1].Length == 1)
                        {
                            ver = split[1];
                        }
                        if (split[2].Length >= 1)
                        {
                            res = split[2];
                        }
                        DateTime LTS;// to get past tow days
                        LTS = DateTime.Now.AddDays(-2);
                        functions.Create_Notifications(fldbd.SelectedPath + "\\" + split[0], Sender, Recipiant, Seq, LTS.ToString("yyyyMMddHHmmss"), ver, res);
                        //TotalProcessBar.Value += 1;
                    }
                }
            }


            MessageBox.Show("Done!");
        }

        private void Input_LV_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;
        }
        private void Input_LV_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            for (i = 0; i < s.Length; i++)
            {

                string filename = Path.GetFileName(s[i]);
                FileInfo fileinfo = new FileInfo(s[i]);
                long Size = 0;
                FileAttributes attr = File.GetAttributes(s[i]);

                //detect whether its a directory or file
                if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
                {
                    if (fileinfo.Length > 0)
                        Size = fileinfo.Length / 1024;
                    string lastFolder = Path.GetDirectoryName(s[i]);

                    string[] row = { filename, lastFolder, Size.ToString() + " Kb" };
                    var listViewItem = new ListViewItem(row);
                    listViewItem.Checked = true;
                    Input_LV.Items.Add(listViewItem);



                    merge_tree.Nodes.Add(s[i]);
                    Split_DGV.Rows.Add(new object[] { false, s[i], "", "" });

                    File_count_lbl.Text = "File(s) Count: " + s.Length.ToString();
                }
            }
        }

        private void NoteFile_cb_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void Mirge_cb_CheckedChanged(object sender, EventArgs e)
        {
            

        }

        private void Singletap_btn_Click(object sender, EventArgs e)
        {
            //change btn style
            Singletap_btn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Singletap_btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            Singletap_btn.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Singletap_btn.FlatAppearance.BorderSize = 0;
            Singletap_btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            //change btn style
            Masstab_btn.BackColor = System.Drawing.Color.White;
            Masstab_btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            Masstab_btn.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Masstab_btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            Masstab_btn.FlatAppearance.BorderSize = 1;

            Single_tab.Visible = true;
            Mass_tab.Visible = false;
            invdualFileEditorToolStripMenuItem.Checked = true;
            massFilesToolStripMenuItem.Checked = false;
        }

        private void Masstab_btn_Click(object sender, EventArgs e)
        {
            //change btn style
            Masstab_btn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Masstab_btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            Masstab_btn.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Masstab_btn.FlatAppearance.BorderSize = 0;
            Masstab_btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            //change btn style
            Singletap_btn.BackColor = System.Drawing.Color.White;
            Singletap_btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            Singletap_btn.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(81)))), ((int)(((byte)(81)))), ((int)(((byte)(81)))));
            Singletap_btn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            Singletap_btn.FlatAppearance.BorderSize = 1;

            Mass_tab.Visible = true;
            Single_tab.Visible = false;
            invdualFileEditorToolStripMenuItem.Checked = false;
            massFilesToolStripMenuItem.Checked = true;
        }

        private void metroButton1_Click_1(object sender, EventArgs e)
        {
            Input_LV.Items.Clear();
            merge_tree.Nodes.Clear();
            Split_DGV.Rows.Clear();
        }



        private void Filelist_clear_btn_Click(object sender, EventArgs e)
        {
            Input_LV.Items.Clear();
            merge_tree.Nodes.Clear();
            Split_DGV.Rows.Clear();
            File_count_lbl.Text = "";
        }

        private void Filelist_selection_btn_Click(object sender, EventArgs e)
        {
            if (Filelist_selection_btn.Text == "Uncheck all")
            {

                foreach (ListViewItem listItem in Input_LV.Items)
                {
                    listItem.Checked = false;
                }

                Filelist_selection_btn.Text = "Check all";
            }
            else if (Filelist_selection_btn.Text == "Check all")
            {
                foreach (ListViewItem listItem in Input_LV.Items)
                {
                    listItem.Checked = true;
                }
                Filelist_selection_btn.Text = "Uncheck all";
            }
        }

        private void Process_Click(object sender, EventArgs e)
        {

            StatusLbl.Text = "Status:Processing..";
            List<string> str = new List<string>();

            foreach (ListViewItem item in Input_LV.CheckedItems)
            {
                str.Add(item.SubItems[1].Text + "\\" + item.Text);
            }
            bulkprocessing.RunWorkerAsync(str);
        }

        private void bulkprocessing_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            double precentage;
            Boolean FR_change = false;//find and replace
            Boolean Fat_change = false;
            // Boolean Merge_change = false;
            Boolean Bearked = false;
            string ok_To_var_length = ""; // change are made correctly

            List<string> input_file = (List<string>)e.Argument;
            //ListViewItem[] j = e.Argument as ListViewItem[];

            double count = input_file.Count; // Input_LV.Items.Count; //for process bar calculations
            double current = 0; //for process bar calculations

            foreach (String file in input_file)// go through all files
            {
                string filename = Path.GetFileName(file);
                string lastFolder = Path.GetDirectoryName(file);
                // foreach (String str in optionlist.CheckedItems)// go through all option
                // {
                if (FAT_cb.Checked && !Split_cb.Checked && !Mirge_cb.Checked)
                {
                    if (LTStxt.Text == "" || LTStxt.Text.Length != 14)
                    {
                        MessageBox.Show("Erorr in entering FAT");
                        return;
                    }
                    bulkprocessing.ReportProgress(10, "process");
                    Boolean ok_FAT;
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");
                    ok_FAT = functions.FAT(file, LTStxt.Text, lastFolder + "\\Result\\" + filename);
                    Fat_change = true;
                    bulkprocessing.ReportProgress(100, "process");
                }
                if (FR_cb.Checked)
                {
                    if (child_Iden_cb_index == -1)
                    {
                        MessageBox.Show("Please Select Field");
                        return;
                    }
                    if (find_txt.Text == "")
                    {
                        MessageBox.Show("Please enter value for Search");
                        return;
                    }
                    if (replace_txt.Text == "")
                    {
                        MessageBox.Show("Please enter value for replace");
                        return;
                    }
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");

                    if (!Fat_change)
                    {
                        ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                    }
                    else
                    {
                        ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                    }
                    string time;

                    if (ok_To_var_length == "done")

                        time = functions.Find_and_replace(child_Iden_cb_index, find_txt.Text, replace_txt.Text, lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                    else if (ok_To_var_length == "no change")
                        time = functions.Find_and_replace(child_Iden_cb_index, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                    else
                    {
                        MessageBox.Show("File is corrupted!");
                        Bearked = true;
                        break;
                    }
                    FR_change = true;

                    //     if (!Directory.Exists(lastFolder + "\\Result"))
                    //         Directory.CreateDirectory(lastFolder + "\\Result");
                    //     time = functions.Find_and_replace(child_Iden_cb.SelectedIndex, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                    //     many_change = true;
                    bulkprocessing.ReportProgress(100, "process");

                }
                if (NoteFile_cb.Checked && Notificaton_file_op1.Checked == true)
                {
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");
                    functions.Create_Notifications_from_file(file, lastFolder + "\\Result\\" + filename);
                    bulkprocessing.ReportProgress(100, "process");
                }
                if (Mirge_cb.Checked)
                {
                    bool first_file = true;
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");
                    TreeNodeCollection nodes = merge_tree.Nodes;
                    foreach (TreeNode parent in nodes)
                    {
                        if (parent.Parent == null)
                        {
                            //MessageBox.Show(n.Text);
                            if (parent.Checked == true)
                            {
                                foreach (TreeNode child in parent.Nodes)
                                {
                                    if (child.Checked == true)
                                    {
                                        string merge_filename = Path.GetFileName(parent.Text);
                                        if ((!FR_change && first_file) && (!Fat_change && first_file))
                                        {
                                            ok_To_var_length = functions.To_variable_lenth(parent.Text, lastFolder + "\\Result\\" + merge_filename);
                                        }
                                        else
                                        {
                                            if (Fat_change && first_file)
                                                ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + merge_filename, lastFolder + "\\Result\\" + merge_filename);
                                        }
                                        //MessageBox.Show(k.Text);
                                        if (ok_To_var_length == "done")
                                            functions.Merge_file(lastFolder + "\\Result\\" + merge_filename, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                        else if (ok_To_var_length == "no change")
                                            if (first_file)
                                            {
                                                functions.Merge_file(parent.Text, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                                first_file = false;
                                            }
                                            else
                                                functions.Merge_file(lastFolder + "\\Result\\" + merge_filename, child.Text, lastFolder + "\\Result\\" + merge_filename);
                                        else
                                        {
                                            MessageBox.Show("File is corrupted!");
                                            Bearked = true;
                                            break;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    bulkprocessing.ReportProgress(100, "process");
                }
                if (Split_cb.Checked)
                {
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");
                    foreach (DataGridViewRow row in Split_DGV.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            if (row.Cells[0].GetType() == typeof(DataGridViewCheckBoxCell))
                            {
                                if (Convert.ToString(row.Cells[0].Value).Contains("True"))
                                {
                                    if (row.Cells[3].Value == null || row.Cells[2].Value == null)
                                    {
                                        MessageBox.Show("Field is Missing");
                                        return;
                                    }
                                    if (!FR_change && !Fat_change)
                                    {
                                        ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                                    }
                                    else
                                    {
                                        if (Fat_change)
                                            ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                                    }
                                    string splitfilename = Path.GetFileName(row.Cells[1].Value.ToString());
                                    //ok_To_var_length = functions.To_variable_lenth(row.Cells[1].Value.ToString(), lastFolder + "\\Result\\" + splitfilename);

                                    if (Split_rb1.Checked)
                                    {
                                        if (ok_To_var_length == "done")
                                            functions.Split_file(lastFolder + "\\Result\\" + splitfilename, lastFolder + "\\Result", row.Cells[3].Value.ToString(), int.Parse(row.Cells[2].Value.ToString()));
                                        else if (ok_To_var_length == "no change")
                                            functions.Split_file(row.Cells[1].Value.ToString(), lastFolder + "\\Result", row.Cells[3].Value.ToString(), int.Parse(row.Cells[2].Value.ToString()));
                                        else
                                        {
                                            MessageBox.Show("File is corrupted!");
                                            Bearked = true;
                                            break;
                                        }

                                    }
                                    else
                                    {
                                        byte[] date = Encoding.ASCII.GetBytes(row.Cells[2].Value.ToString());
                                        if (ok_To_var_length == "done")
                                            functions.Split_file_Date(lastFolder + "\\Result\\" + splitfilename, lastFolder + "\\Result", row.Cells[3].Value.ToString(), date);
                                        else if (To_var_length == "no change")
                                            functions.Split_file_Date(row.Cells[1].Value.ToString(), lastFolder + "\\Result", row.Cells[3].Value.ToString(), date);
                                        else
                                        {
                                            MessageBox.Show("File is corrupted!");
                                            Bearked = true;
                                            break;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    bulkprocessing.ReportProgress(100, "process");
                }
                if (Filter_cb.Checked)
                {
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");

                    if (!FR_change && !Fat_change)
                    {
                        ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                    }
                    else
                    {
                        if (Fat_change)
                            ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                    }



                    bool[] call_event_type = new bool[9];
                    call_event_type[0] = Filter_cb1.Checked;//MobileOriginatedCall
                    call_event_type[1] = Filter_cb2.Checked;//MobileTerminatedCall
                    call_event_type[2] = Filter_cb3.Checked;//SupplServiceEvent
                    call_event_type[3] = Filter_cb4.Checked;//ServiceCentreUsage
                    call_event_type[4] = Filter_cb5.Checked;//GprsCall
                    call_event_type[5] = Filter_cb6.Checked;//ContentTransaction
                    call_event_type[6] = Filter_cb7.Checked;//LocationService
                    call_event_type[7] = Filter_cb8.Checked;//MessagingEvent
                    call_event_type[8] = Filter_cb9.Checked;//MobileSession
                    if (ok_To_var_length == "done" || FR_change)
                        functions.Filter_Records(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename, call_event_type);
                    else if (ok_To_var_length == "no change")
                        if (Fat_change)
                            functions.Filter_Records(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename, call_event_type);
                        else
                            functions.Filter_Records(file, lastFolder + "\\Result\\" + filename, call_event_type);
                    else
                    {
                        MessageBox.Show("File is corrupted!");
                        Bearked = true;
                        break;
                    }
                    // many_change = true;

                    //     if (!Directory.Exists(lastFolder + "\\Result"))
                    //         Directory.CreateDirectory(lastFolder + "\\Result");
                    //     time = functions.Find_and_replace(child_Iden_cb.SelectedIndex, find_txt.Text, replace_txt.Text, file, lastFolder + "\\Result\\" + filename);
                    //     many_change = true;
                    bulkprocessing.ReportProgress(100, "process");
                }

                if (CalcAudit_cb.Checked && !Filter_cb.Checked && !Split_cb.Checked && !Mirge_cb.Checked)
                {
                    bulkprocessing.ReportProgress(10, "process");
                    if (!Directory.Exists(lastFolder + "\\Result"))
                        Directory.CreateDirectory(lastFolder + "\\Result");

                    if (!FAT_cb.Checked && !FR_cb.Checked )
                    {
                        ok_To_var_length = functions.To_variable_lenth(file, lastFolder + "\\Result\\" + filename);
                    }
                    else
                    {
                        if (FAT_cb.Checked)
                            ok_To_var_length = functions.To_variable_lenth(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                    }
                    functions.Audit audit1 = new functions.Audit();




                    if (ok_To_var_length == "done" || FR_change)
                        audit1 = functions.Calc_Audit(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                    else if (ok_To_var_length == "no change")
                        if (Fat_change)
                            audit1 = functions.Calc_Audit(lastFolder + "\\Result\\" + filename, lastFolder + "\\Result\\" + filename);
                        else
                           audit1 = functions.Calc_Audit(file, lastFolder + "\\Result\\" + filename); 
                    else
                    {
                        MessageBox.Show("File is corrupted!");
                        Bearked = true;
                        break;
                    }
                
                }

                current++;
                precentage = (current / count) * 100;
                bulkprocessing.ReportProgress((int)precentage, "totalprocess");
                if (Bearked)
                {
                    Bearked = false;
                    continue;
                }
            }

        }


        public delegate int ListViewcheckedcount();
        public int ListViewcount()
        {
            return Input_LV.CheckedItems.Count;
        }


        private void bulkprocessing_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {

            String str = e.UserState as String;
            int process = e.ProgressPercentage;


            //if (str == "process")
            //ProcessBar.Value = process;
            //else
            if (str != "process")
                TotalProcessBar.Value = process;
        }

        private void bulkprocessing_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            StatusLbl.Text = "Status:Done";
            TotalProcessBar.Value = 0;
            List<string> str = new List<string>();

            foreach (ListViewItem item in Input_LV.CheckedItems)
            {
                str.Add(item.SubItems[1].Text + "\\");
            }

            List<string> noDupes = str.Distinct().ToList();
            Result_LV.Items.Clear();

            for (int count = 0; count < noDupes.Count; count++)
            {
                if (Directory.Exists(noDupes[count] + "Result"))
                {
                    string[] filePaths = Directory.GetFiles(noDupes[count] + "Result");
                    for (int filecount = 0; filecount < filePaths.Length; filecount++)
                    {
                        string filename = Path.GetFileName(filePaths[filecount]);
                        FileInfo fileinfo = new FileInfo(filePaths[filecount]);
                        long Size = fileinfo.Length / 1024;
                        string lastFolder = Path.GetDirectoryName(filePaths[filecount]);

                        string[] row = { filename, lastFolder, Size.ToString() + " Kb" };
                        var listViewItem = new ListViewItem(row);
                        listViewItem.Checked = true;
                        Result_LV.Items.Add(listViewItem);
                    }
                }
            }
            //ProcessBar.Value = 0;
        }
        public string To_var_length;
        public string Opend_Filename;
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {

            // StatusLbl.Text = "Status:Processing...";
            TreeNode t = new TreeNode();
            backgroundWorker1.ReportProgress(1);
            To_var_length = functions.To_variable_lenth(Opend_Filename, Opend_Filename + ".tmp");
            if (To_var_length == "done")
            {
                t = functions.OpenFile_tree(Opend_Filename + ".tmp", M_branch_tree, backgroundWorker1);
                Opend_Filename += ".tmp";
            }
            else if (To_var_length == "no change")
                t = functions.OpenFile_tree(Opend_Filename, M_branch_tree, backgroundWorker1);
            else
                MessageBox.Show("File is corrupted!");


            e.Result = t;

        }


        public int child_Iden_cb_index = -1;
        private void child_Iden_cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            child_Iden_cb_index = child_Iden_cb.SelectedIndex;
        }

        private void TSOpenbtn_Click(object sender, EventArgs e)
        {
            StatusLbl.Text = "Status:Open";

            if (OFD.ShowDialog() != DialogResult.Cancel)
            {
                if (OFD.FileName != "")
                {
                    ChangesList.Clear();
                    M_branch_tree.Nodes.Clear();
                    B_tree.Nodes.Clear();
                    Opend_Filename = OFD.FileName;
                    string filename = Path.GetFileName(Opend_Filename);
                    this.Text = "Gio - " + filename;
                    backgroundWorker1.RunWorkerAsync();
                }
            }
        }

        private void TSSaveBtn_Click(object sender, EventArgs e)
        {

            // SFD.ShowDialog();
            if (Opend_Filename != "")
            {

                functions.Save_identifier_tree(Opend_Filename, ChangesList, OFD.FileName);

            }
        }
        List<functions.Changes> ChangesList = new List<functions.Changes>();
        bool Text_edit_change = false;
        private void Edittxt_Leave(object sender, EventArgs e)
        {
            Edittxt.Visible = false;
            Text_edit_change = false;
        }

        private void Edittxt_TextChanged(object sender, EventArgs e)
        {
            Text_edit_change = true;
        }

        private void Edittxt_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (Text_edit_change == true && B_tree.SelectedNode != null)
                {
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');
                    B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                    functions.Changes New_Edit;
                    string Node_tag = B_tree.SelectedNode.Tag.ToString();
                    string[] str = Node_tag.Split(',');
                    New_Edit.identifer = int.Parse(str[0]);
                    New_Edit.identifer_start = int.Parse(str[1]);
                    New_Edit.identifer_end = int.Parse(str[2]);
                    New_Edit.type = 0;
                    New_Edit.Parent = false;
                    New_Edit.Node_index = B_tree.SelectedNode.Index;
                    New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);
                    New_Edit.New_Value = Edittxt.Text;
                    //if (New_Edit.identifer_end != 0)
                    //{
                    if (Edittxt.Text != nodename[1].TrimStart())
                        ChangesList.Add(New_Edit);
                    //}
                    //else
                    //{
                    //int Found_index= Insert_List.FindIndex(x => x.identifer_start == New_Edit.identifer_start && x.identifer == New_Edit.identifer && x.Node_index == B_tree.SelectedNode.Index );
                    //if (Found_index >0)
                    //{
                    //Insert_List[Found_index].New_Value = Edittxt.Text;

                    //}
                    //}
                    Text_edit_change = false;
                    Edittxt.Visible = false;
                    B_tree.Focus();
                }
            }
            if (e.KeyCode == Keys.Escape)
            {
                Edittxt.Text = "";
                Edittxt.Visible = false;
                Text_edit_change = false;
                B_tree.Focus();
            }
        }

        private void Edittxt_Leave_1(object sender, EventArgs e)
        {
            Edittxt.Visible = false;
            Text_edit_change = false;
        }

        private void M_branch_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            {
                if (M_branch_tree.SelectedNode.Tag != null)
                {
                    B_tree.Nodes.Clear();
                    int End_of_Identifier;
                    string TagStr = M_branch_tree.SelectedNode.Tag.ToString();
                    if (TagStr.IndexOf(',') == -1)
                    {
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(M_branch_tree.SelectedNode.Tag), B_tree);
                        M_branch_tree.SelectedNode.Tag += "," + End_of_Identifier.ToString();
                    }
                    else
                    {
                        string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(',');
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(str[0]), B_tree);
                    }
                    functions.Update_Changes_on_tree(B_tree.TopNode, ChangesList);
                    B_tree.ExpandAll();
                    B_tree.SelectedNode = B_tree.Nodes[0];
                }
            }
        }

        private void M_branch_tree_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 1)
            {
                e.Node.ImageIndex = 0;
                e.Node.SelectedImageIndex = 0;
            }
        }

        private void M_branch_tree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.ImageIndex == 0)
            {
                e.Node.ImageIndex = 1;
                e.Node.SelectedImageIndex = 1;
            }
        }
        TreeNode mySelectedNode;
        private void B_tree_MouseClick(object sender, MouseEventArgs e)
        {
            if (Text_edit_change == true && B_tree.SelectedNode != null && B_tree.SelectedNode.ImageIndex != 1 && B_tree.SelectedNode.ImageIndex != 2)
            {
                string[] nodename = B_tree.SelectedNode.Text.Split(':');
                B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                functions.Changes New_Edit;
                string Node_tag = B_tree.SelectedNode.Tag.ToString();
                string[] str = Node_tag.Split(',');
                New_Edit.identifer = int.Parse(str[0]);
                New_Edit.identifer_start = int.Parse(str[1]);
                New_Edit.identifer_end = int.Parse(str[2]);
                New_Edit.type = 0;
                New_Edit.Parent = false;
                New_Edit.Node_index = B_tree.SelectedNode.Index;
                New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]); ;
                New_Edit.New_Value = Edittxt.Text;
                if (Edittxt.Text != nodename[1].TrimStart())
                    ChangesList.Add(New_Edit);
                Text_edit_change = false;
            }
            mySelectedNode = B_tree.GetNodeAt(e.X, e.Y);
            // Edittxt.Visible = false;
        }

        private void B_tree_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (mySelectedNode != null && mySelectedNode.Parent != null && mySelectedNode.Nodes.Count == 0 && mySelectedNode.ImageIndex != 0)
            {
                B_tree.SelectedNode = mySelectedNode;
                //Treeview1.LabelEdit = true;
                if (!mySelectedNode.IsEditing)
                {
                    // mySelectedNode.BeginEdit();
                    Point pt = new Point(e.X, e.Y);

                    // Convert to a point in the TreeView's coordinate system.
                    pt = B_tree.PointToClient(pt);
                    //textBox5.Top = Treeview1.Top + pt.Y;
                    //textBox5.Left = Treeview1.Left + pt.X;
                    //B_tree.SelectedNode = B_tree.GetNodeAt(pt);
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');

                    var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                    // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                    Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0] + "        ", font).Width,
        B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width + 20, Edittxt.Height);

                    Edittxt.Text = nodename[1].TrimStart();
                    Edittxt.Visible = true;
                    Edittxt.Focus();
                }
            }
            /*  else
              {
                  MessageBox.Show("No tree node selected or selected node is a root node.\n" +
                     "Editing of root nodes is not allowed.", "Invalid selection");
              }*/
        }

        private void B_tree_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            ChangesList.Clear();
            M_branch_tree.Nodes.Clear();
            B_tree.Nodes.Clear();
            Opend_Filename = s[0];
            OFD.FileName = Opend_Filename;
            string filename = Path.GetFileName(Opend_Filename);
            this.Text = "Gio - " + filename;
            backgroundWorker1.RunWorkerAsync();
        }

        private void B_tree_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.C))
            {
                if (B_tree.SelectedNode != null)
                {
                    Clipboard.SetText(B_tree.SelectedNode.Text + "\r\n" + functions.tree_to_text(B_tree.SelectedNode, B_tree.SelectedNode.Level));
                }
                e.SuppressKeyPress = true;
            }
            if (e.KeyData == (Keys.Control | Keys.V))
            {
                int linenumber = 1; //should start with one because of the first line [0] is not counted
                string clipb = Clipboard.GetText();
                if (B_tree.SelectedNode != null)
                    functions.Paste(B_tree.SelectedNode, B_tree.SelectedNode, clipb, ref linenumber, ChangesList);
            }
            if (e.KeyData == Keys.Enter)
            {
                if (B_tree.SelectedNode != null && B_tree.SelectedNode.Parent != null && B_tree.SelectedNode.Nodes.Count == 0 && B_tree.SelectedNode.ImageIndex != 0)
                {



                    // Convert to a point in the TreeView's coordinate system.

                    //textBox5.Top = Treeview1.Top + pt.Y;
                    //textBox5.Left = Treeview1.Left + pt.X;
                    //B_tree.SelectedNode = B_tree.
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');

                    var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                    // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                    Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0] + "        ", font).Width,
        B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width + 20, Edittxt.Height);

                    Edittxt.Text = nodename[1].TrimStart();
                    Edittxt.Visible = true;
                    Edittxt.Focus();

                }
            }
        }

        private void B_tree_MouseDown(object sender, MouseEventArgs e)
        {
            if (Text_edit_change == true && B_tree.SelectedNode != null && B_tree.SelectedNode.ImageIndex != 1 && B_tree.SelectedNode.ImageIndex != 2)
            {
                string[] nodename = B_tree.SelectedNode.Text.Split(':');
                B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                functions.Changes New_Edit;
                string Node_tag = B_tree.SelectedNode.Tag.ToString();
                string[] str = Node_tag.Split(',');
                New_Edit.identifer = int.Parse(str[0]);
                New_Edit.identifer_start = int.Parse(str[1]);
                New_Edit.identifer_end = int.Parse(str[2]);
                New_Edit.type = 0;
                New_Edit.Parent = false;
                New_Edit.Node_index = B_tree.SelectedNode.Index;
                New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]); ;
                New_Edit.New_Value = Edittxt.Text;
                if (Edittxt.Text != nodename[1].TrimStart())
                    ChangesList.Add(New_Edit);
                Text_edit_change = false;
            }
            mySelectedNode = B_tree.GetNodeAt(e.X, e.Y);
            // Edittxt.Visible = false;
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            TotalProcessBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            StatusLbl.Text = "Status:Done";
            TreeNode j = e.Result as TreeNode;
            TotalProcessBar.Value = 0;
            //MessageBox.Show(j.Nodes[0].Text);
            M_branch_tree.Nodes.Add(j);

            for (int count = 1; count < toolStrip1.Items.Count; count++)
                toolStrip1.Items[count].Enabled = true;
            editToolStripMenuItem.Enabled = true;

            //MessageBox.Show(M_branch_tree.Nodes[0].Nodes[0].Tag.ToString());
        }

        private void TSGotoBtn_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            Gotofrm.Set_tree(M_branch_tree);


            Gotofrm.TopLevel = false;
            Gotofrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(Gotofrm);
            Gotofrm.Show();
        }

        private void TSInsert_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            if (B_tree.Focused && B_tree.SelectedNode != null)
            {
                // getting the indentifier number form the tag
                bool SeqIden = false;
                string[] Tag = B_tree.SelectedNode.Tag.ToString().Split(',');
                int iden=int.Parse(Tag[0]);
                //checking if it is one of SEQ. indentifier
                for (int count = 0; count < functions.indefinder_SEQUENCE.Length;count++ )
                {
                    if (iden==functions.indefinder_SEQUENCE[count])
                    {
                        SeqIden = true;
                        break;
                    }
                }
                // if it is not one of SEQ. Identifier then show the normal insert.
                if (!SeqIden)
                {
                    insertfrm.get_missing_identifier(B_tree.SelectedNode, B_tree, ChangesList, Opend_Filename);
                    insertfrm.TopLevel = false;
                    insertfrm.AutoScroll = true;
                    Tools_sliters.Panel2.Controls.Add(insertfrm);
                    insertfrm.Show();
                }
                    // show the insert for the SEQ. indentifier.
                else
                {
                    insertSeqfrm.get_missing_identifier(B_tree.SelectedNode, B_tree, ChangesList, Opend_Filename);
                    insertSeqfrm.TopLevel = false;
                    insertSeqfrm.AutoScroll = true;
                    Tools_sliters.Panel2.Controls.Add(insertSeqfrm);
                    insertSeqfrm.Show();
                }
            }
        }

        private void TSCopybtn_Click(object sender, EventArgs e)
        {
            if (B_tree.SelectedNode != null)
                Clipboard.SetText(B_tree.SelectedNode.Text + "\r\n" + functions.tree_to_text(B_tree.SelectedNode, B_tree.SelectedNode.Level));
        }

        private void TSPastebtn_Click(object sender, EventArgs e)
        {
            int linenumber = 1; //should start with one because of the first line [0] is not counted
            string clipb = Clipboard.GetText();
            if (B_tree.SelectedNode != null)
                functions.Paste(B_tree.SelectedNode, B_tree.SelectedNode, clipb, ref linenumber, ChangesList);
        }

        private void TSDelete_Click(object sender, EventArgs e)
        {
            functions.Changes Deleted_Item = new functions.Changes();
            if (M_branch_tree.Focused && M_branch_tree.SelectedNode != null)
            {
                if (M_branch_tree.SelectedNode.Tag != null)
                {
                    string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(','); ;
                    Deleted_Item.identifer = 0;
                    Deleted_Item.identifer_start = int.Parse(str[0]);
                    Deleted_Item.identifer_end = int.Parse(str[1]);
                    Deleted_Item.Parent = true;
                    Deleted_Item.type = 1;
                    Deleted_Item.Node_index = M_branch_tree.SelectedNode.Index;
                    if (M_branch_tree.SelectedNode.Parent.Tag != null)
                        Deleted_Item.Parent_Name = int.Parse(M_branch_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);
                    else
                        Deleted_Item.Parent_Name = 1;
                    ChangesList.Add(Deleted_Item);
                    M_branch_tree.SelectedNode.Remove();
                }

            }
            if (B_tree.Focused && B_tree.SelectedNode != null)
            {
                if (B_tree.SelectedNode.Tag != null)
                {
                    string[] str = B_tree.SelectedNode.Tag.ToString().Split(','); ;
                    Deleted_Item.identifer = int.Parse(str[0]);
                    Deleted_Item.identifer_start = int.Parse(str[1]);
                    Deleted_Item.identifer_end = int.Parse(str[2]);
                    Deleted_Item.Node_index = B_tree.SelectedNode.Index;
                    Deleted_Item.type = 1;
                    Deleted_Item.Parent = (B_tree.SelectedNode.GetNodeCount(false) > 0) ? true : false;
                    Deleted_Item.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);

                    ChangesList.Add(Deleted_Item);
                    if (B_tree.SelectedNode.Parent != null)
                        B_tree.SelectedNode.Remove();
                    else
                    {
                        B_tree.SelectedNode.Remove();
                        M_branch_tree.SelectedNode.Remove();
                    }
                }
            }
        }

        private void TSUndo_Click(object sender, EventArgs e)
        {
            if (ChangesList.Count > 0)
            {
                ChangesList.RemoveAt(ChangesList.Count - 1);
                if (M_branch_tree.SelectedNode.Tag != null)
                {
                    B_tree.Nodes.Clear();
                    int End_of_Identifier;
                    string TagStr = M_branch_tree.SelectedNode.Tag.ToString();
                    if (TagStr.IndexOf(',') == -1)
                    {
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(M_branch_tree.SelectedNode.Tag), B_tree);
                        M_branch_tree.SelectedNode.Tag += "," + End_of_Identifier.ToString();
                    }
                    else
                    {
                        string[] str = M_branch_tree.SelectedNode.Tag.ToString().Split(',');
                        End_of_Identifier = functions.Open_identifier_tree(Opend_Filename, Convert.ToInt32(str[0]), B_tree);
                    }
                    functions.Update_Changes_on_tree(B_tree.TopNode, ChangesList);
                    B_tree.ExpandAll();
                    B_tree.SelectedNode = B_tree.Nodes[0];
                }
            }
        }

        TreeNode clonedNode;
        bool Filtered = false;
        private void TSFilterDisable_Click(object sender, EventArgs e)
        {
            if (clonedNode != null)
            {
                Filtered = false;
                M_branch_tree.Nodes.Clear();
                M_branch_tree.Nodes.Add(clonedNode);
            }
        }

        private void TSFilterByEvent_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            //FilterTree.Nodes.Clear();
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
            /*       else
                   {
                       M_branch_tree.Nodes.Clear();
                       M_branch_tree.Nodes.Add(clonedNode);
                   }*/
            Filtered = true;
            //FilterTree.Nodes.Add(clonedNode);
            /*indlenV == 9  ||
            indlenV == 10 ||
            indlenV == 11 ||
            indlenV == 12 ||
            indlenV == 14 ||
            indlenV == 17 ||
            indlenV == 297||
            indlenV == 433||
            indlenV == 434*/


            M_branch_tree.Nodes[0].Expand();

            Event_filterfrm.TreeNode(M_branch_tree, clonedNode);
            Event_filterfrm.TopLevel = false;
            Event_filterfrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(Event_filterfrm);
            Event_filterfrm.Show();

        }

        private void TSFitlerIMSI_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
          
            Filtered = true;



            M_branch_tree.Nodes[0].Expand();

            IMEI_filterfrm.TreeNode(M_branch_tree, Opend_Filename, ChangesList);
            IMEI_filterfrm.TopLevel = false;
            IMEI_filterfrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(IMEI_filterfrm);
            IMEI_filterfrm.Show();
        }

        private void TSFilterDuration_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
            /*  else
              {
                  M_branch_tree.Nodes.Clear();
                  M_branch_tree.Nodes.Add(clonedNode);
              }*/
            Filtered = true;



            M_branch_tree.Nodes[0].Expand();

            Duration_filterfrm.TreeNode(M_branch_tree, Opend_Filename, ChangesList);
            Duration_filterfrm.TopLevel = false;
            Duration_filterfrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(Duration_filterfrm);
            Duration_filterfrm.Show();
        }

        private void TSFilterDate_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            B_tree.Nodes.Clear();
            if (!Filtered)
            {
                clonedNode = (TreeNode)M_branch_tree.Nodes[0].Clone();
            }
            /*     else
                 {
                     M_branch_tree.Nodes.Clear();
                     M_branch_tree.Nodes.Add(clonedNode);
                 }*/
            Filtered = true;



            M_branch_tree.Nodes[0].Expand();

            Date_filterfrm.TreeNode(M_branch_tree, Opend_Filename);
            Date_filterfrm.TopLevel = false;
            Date_filterfrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(Date_filterfrm);
            Date_filterfrm.Show();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Hide_all_frm();
            M_branch_tree.Nodes[0].Expand();

            Findfrm.TreeNode(M_branch_tree, B_tree, Opend_Filename, ChangesList);
            Findfrm.TopLevel = false;
            Findfrm.AutoScroll = true;
            Tools_sliters.Panel2.Controls.Add(Findfrm);
            Findfrm.Show();
        }
        
        private void Hide_all_frm()
        {
            Event_filterfrm.Hide();
            filterfrm.Hide();
            IMEI_filterfrm.Hide();
            Duration_filterfrm.Hide();
            Date_filterfrm.Hide();
            Findfrm.Hide();
            Gotofrm.Hide();
            insertfrm.Hide();
        }

        private void Result_LV_DoubleClick(object sender, EventArgs e)
        {
            if (Result_LV.SelectedItems.Count > 0)
            {
                ChangesList.Clear();
                M_branch_tree.Nodes.Clear();
                B_tree.Nodes.Clear();
                Opend_Filename = Result_LV.SelectedItems[0].SubItems[1].Text + "\\" + Result_LV.SelectedItems[0].Text;
                
                string filename = Path.GetFileName(Opend_Filename);
                
                backgroundWorker1.RunWorkerAsync();
                //this.Text = "Geo - " + Result_LV.SelectedItems[0].Text;
                Singletap_btn.PerformClick();
                this.Text = "Gio - " + filename;
                this.Refresh();
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (SFD.ShowDialog() != DialogResult.Cancel)
            {
                if (SFD.FileName != "")
                {

                    functions.Save_identifier_tree(Opend_Filename, ChangesList, SFD.FileName);

                }
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangesList.Clear();
            M_branch_tree.Nodes.Clear();
            B_tree.Nodes.Clear();
            if (backgroundWorker1.IsBusy)
                backgroundWorker1.CancelAsync();
            for (int count = 1; count < toolStrip1.Items.Count; count++)
                toolStrip1.Items[count].Enabled = false;
            editToolStripMenuItem.Enabled = false;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void B_tree_MouseClick_1(object sender, MouseEventArgs e)
        {
            if (Text_edit_change == true && B_tree.SelectedNode != null && B_tree.SelectedNode.ImageIndex != 1 && B_tree.SelectedNode.ImageIndex != 2)
            {
                string[] nodename = B_tree.SelectedNode.Text.Split(':');
                B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                functions.Changes New_Edit;
                string Node_tag = B_tree.SelectedNode.Tag.ToString();
                string[] str = Node_tag.Split(',');
                New_Edit.identifer = int.Parse(str[0]);
                New_Edit.identifer_start = int.Parse(str[1]);
                New_Edit.identifer_end = int.Parse(str[2]);
                New_Edit.type = 0;
                New_Edit.Parent = false;
                New_Edit.Node_index = B_tree.SelectedNode.Index;
                New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]); ;
                New_Edit.New_Value = Edittxt.Text;
                if (Edittxt.Text != nodename[1].TrimStart())
                    ChangesList.Add(New_Edit);
                Text_edit_change = false;
            }
            mySelectedNode = B_tree.GetNodeAt(e.X, e.Y);
            // Edittxt.Visible = false;
        }


        private void B_tree_MouseDoubleClick_1(object sender, MouseEventArgs e)
        {
            if (mySelectedNode != null && mySelectedNode.Parent != null && mySelectedNode.Nodes.Count == 0 && mySelectedNode.ImageIndex != 0)
            {
                B_tree.SelectedNode = mySelectedNode;
                //Treeview1.LabelEdit = true;
                if (!mySelectedNode.IsEditing)
                {
                    // mySelectedNode.BeginEdit();
                    Point pt = new Point(e.X, e.Y);

                    // Convert to a point in the TreeView's coordinate system.
                    pt = B_tree.PointToClient(pt);
                    //textBox5.Top = Treeview1.Top + pt.Y;
                    //textBox5.Left = Treeview1.Left + pt.X;
                    //B_tree.SelectedNode = B_tree.GetNodeAt(pt);
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');

                    var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                    // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                    Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0] + "        ", font).Width,
        B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width + 20, Edittxt.Height);

                    Edittxt.Text = nodename[1].TrimStart();
                    Edittxt.Visible = true;
                    Edittxt.Focus();
                }
            }
            /*  else
              {
                  MessageBox.Show("No tree node selected or selected node is a root node.\n" +
                     "Editing of root nodes is not allowed.", "Invalid selection");
              }*/
        }

        private void Edittxt_TextChanged_1(object sender, EventArgs e)
        {
            var font = new Font(Edittxt.Font.Name, Edittxt.Font.Size, Edittxt.Font.Style);
            Edittxt.Width = TextRenderer.MeasureText(Edittxt.Text, font).Width + 20;
            Text_edit_change = true;
        }

        private void Edittxt_Leave_2(object sender, EventArgs e)
        {
            Edittxt.Visible = false;
            Text_edit_change = false;
        }

        private void Edittxt_KeyDown_1(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (Text_edit_change == true && B_tree.SelectedNode != null)
                {
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');
                    B_tree.SelectedNode.Text = nodename[0] + ":        " + Edittxt.Text;
                    functions.Changes New_Edit;
                    string Node_tag = B_tree.SelectedNode.Tag.ToString();
                    string[] str = Node_tag.Split(',');
                    New_Edit.identifer = int.Parse(str[0]);
                    New_Edit.identifer_start = int.Parse(str[1]);
                    New_Edit.identifer_end = int.Parse(str[2]);
                    New_Edit.type = 0;
                    New_Edit.Parent = false;
                    New_Edit.Node_index = B_tree.SelectedNode.Index;
                    New_Edit.Parent_Name = int.Parse(B_tree.SelectedNode.Parent.Tag.ToString().Split(',')[0]);
                    New_Edit.New_Value = Edittxt.Text;
                    //if (New_Edit.identifer_end != 0)
                    //{
                    if (Edittxt.Text != nodename[1].TrimStart())
                        ChangesList.Add(New_Edit);
                    //}
                    //else
                    //{
                    //int Found_index= Insert_List.FindIndex(x => x.identifer_start == New_Edit.identifer_start && x.identifer == New_Edit.identifer && x.Node_index == B_tree.SelectedNode.Index );
                    //if (Found_index >0)
                    //{
                    //Insert_List[Found_index].New_Value = Edittxt.Text;

                    //}
                    //}
                    Text_edit_change = false;
                    Edittxt.Visible = false;
                    B_tree.Focus();
                }
            }
            if (e.KeyCode == Keys.Escape)
            {
                Edittxt.Text = "";
                Edittxt.Visible = false;
                Text_edit_change = false;
                B_tree.Focus();
            }
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (Edittxt.Focused)
                toolStrip1.Focus();
        }

        private void menuStrip1_MenuActivate(object sender, EventArgs e)
        {
            menuStrip1.Focus();
        }

        private void FAT_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "File Availabe Time Stamp";
            FATgrp.Visible = true;
            DateTime LTS;// to get past tow days
            LTS = DateTime.Now.AddDays(-2);
            LTStxt.Text = LTS.ToString("yyyyMMddHHmmss"); ;

            if (FAT_cb.Checked)
            {

                NoteFile_cb.Enabled = false;
                NoteFile_cb.Checked = false;

            }
            else
            {
                Enable_all_CB();
            }

        }

        private void FR_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "Find / Replace";
            findreplacegrp.Visible = true;
            if (FR_cb.Checked)
            {

                NoteFile_cb.Enabled = false;
                NoteFile_cb.Checked = false;

            }
            else
            {
                Enable_all_CB();
            }
        }

        private void NoteFile_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "Notification File";
            Notification_File_grp.Visible = true;
            if (NoteFile_cb.Checked)
            {
                FAT_cb.Enabled = false;
                FAT_cb.Checked = false;

                FR_cb.Enabled = false;
                FR_cb.Checked = false;

                CalcAudit_cb.Enabled = false;
                CalcAudit_cb.Checked = false;

                Split_cb.Enabled = false;
                Split_cb.Checked = false;

                Mirge_cb.Enabled = false;
                Mirge_cb.Checked = false;

                Filter_cb.Enabled = false;
                Filter_cb.Checked = false;
            }
            else
            {
                Enable_all_CB();
            }
        }

        public void Enable_all_CB()
        {
            FAT_cb.Enabled = true;
            FR_cb.Enabled = true;
            NoteFile_cb.Enabled = true;
            CalcAudit_cb.Enabled = true;
            Split_cb.Enabled = true;
            Mirge_cb.Enabled = true;
            Filter_cb.Enabled = true;
        }

        private void Mirge_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "Mirge File";
            merge_grp.Visible = true;
            if (Mirge_cb.Checked == true)
            {
                FAT_cb.Enabled = false;
                FAT_cb.Checked = true;

                CalcAudit_cb.Enabled = false;
                CalcAudit_cb.Checked = true;

                NoteFile_cb.Enabled = false;
                NoteFile_cb.Checked = false;

                Split_cb.Enabled = false;
                Split_cb.Checked = false;
            }
            else
            {
                Enable_all_CB();
            }
        }

        private void Split_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "Split";
            Split_grp.Visible = true;


            if (Split_cb.Checked == true)
            {
                FAT_cb.Enabled = false;
                FAT_cb.Checked = true;

                CalcAudit_cb.Enabled = false;
                CalcAudit_cb.Checked = true;

                NoteFile_cb.Enabled = false;
                NoteFile_cb.Checked = false;

                Mirge_cb.Enabled = false;
                Mirge_cb.Checked = false;

                Filter_cb.Enabled = false;
                Filter_cb.Checked = false;
            }
            else
            {
                Enable_all_CB();
            }
        }

        private void Filter_cb_Click(object sender, EventArgs e)
        {
            Hideall();
            ToolTittle.Text = "Filter Event";
            Filter_grp.Visible = true;
            if (Filter_cb.Checked == true)
            {


                CalcAudit_cb.Enabled = false;
                CalcAudit_cb.Checked = true;

                NoteFile_cb.Enabled = false;
                NoteFile_cb.Checked = false;



            }
            else
            {
                Enable_all_CB();
            }
        }

        private void multiOpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fldbd.ShowDialog();
            if (fldbd.SelectedPath != "")
            {
                string[] filePaths = Directory.GetFiles(fldbd.SelectedPath, "CD*",
                    SearchOption.AllDirectories);
                for (int i = 0; i < filePaths.Length; i++)
                {
                    string filename = Path.GetFileName(filePaths[i]);
                    FileInfo fileinfo = new FileInfo(filePaths[i]);
                    long Size = fileinfo.Length / 1024;
                    string lastFolder = Path.GetDirectoryName(filePaths[i]);

                    string[] row = { filename, lastFolder, Size.ToString() + " Kb" };
                    var listViewItem = new ListViewItem(row);
                    listViewItem.Checked = true;
                    Input_LV.Items.Add(listViewItem);
                }
                File_count_lbl.Text = "File(s) Count: " + filePaths.Length.ToString();
            }
           
        }

        private void B_tree_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.C))
            {
                if (B_tree.SelectedNode != null)
                {
                    Clipboard.SetText(B_tree.SelectedNode.Text + "\r\n" + functions.tree_to_text(B_tree.SelectedNode, B_tree.SelectedNode.Level));
                }
                e.SuppressKeyPress = true;
            }
            if (e.KeyData == (Keys.Control | Keys.V))
            {
                int linenumber = 1; //should start with one because of the first line [0] is not counted
                string clipb = Clipboard.GetText();
                if (B_tree.SelectedNode != null)
                    functions.Paste(B_tree.SelectedNode, B_tree.SelectedNode, clipb, ref linenumber, ChangesList);
            }
            if (e.KeyData == Keys.Enter)
            {
                if (B_tree.SelectedNode != null && B_tree.SelectedNode.Parent != null && B_tree.SelectedNode.Nodes.Count == 0 && B_tree.SelectedNode.ImageIndex != 0)
                {



                    // Convert to a point in the TreeView's coordinate system.

                    //textBox5.Top = Treeview1.Top + pt.Y;
                    //textBox5.Left = Treeview1.Left + pt.X;
                    //B_tree.SelectedNode = B_tree.
                    string[] nodename = B_tree.SelectedNode.Text.Split(':');

                    var font = new Font(B_tree.Font.Name, B_tree.Font.Size, B_tree.Font.Style);
                    // x=TextRenderer.MeasureText(mySelectedNode.Text, font);
                    Edittxt.SetBounds(B_tree.Left + B_tree.SelectedNode.Bounds.X + TextRenderer.MeasureText(nodename[0] + "        ", font).Width,
        B_tree.Top + B_tree.SelectedNode.Bounds.Y, TextRenderer.MeasureText(nodename[1].TrimStart(), font).Width + 20, Edittxt.Height);

                    Edittxt.Text = nodename[1].TrimStart();
                    Edittxt.Visible = true;
                    Edittxt.Focus();

                }
            }
        }
    }
}