using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.Data.OleDb;
using System.Windows;
using System.Runtime.InteropServices;
using System.IO;
using System.Speech;
using System.Speech.Synthesis;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Concatenation_Waves;
using System.Collections;
using System.Diagnostics;


namespace ParsKhan
{


    public partial class Form1 : Form
    {
        ////////////////////////////////////////////////////////Global Vars
        private static OleDbConnection con;
        static int speed = 100;
        static int start = 0;
        static int selectionStart = 0;
        static bool check = false;
        static int i = 0;
        static bool record = false;
        static string format = "";
        static string saveoutput = "c:\\output.wav";
        static int ReaderIndex = 0;
        static ArrayList files = new ArrayList();
        ///////////////////////////////////////////////////////////////////
        public static OleDbCommand myCommand = new OleDbCommand();


        public Form1()
        {
            con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=audio.mdb;Persist Security Info=False");
            con.Open();
            myCommand.Connection = con;


            //("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=audio.accdb;Persist Security Info=False");

            InitializeComponent();
            comboBox1.SelectedIndex = 1;
            comboBox2.SelectedIndex = 0;
            backgroundWorker1.DoWork +=
                new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(
            backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.ProgressChanged +=
                new ProgressChangedEventHandler(
            backgroundWorker1_ProgressChanged);
            button2.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            textBox1.ReadOnly = true;
            record = false;
            check = false;
            button3.Enabled = true;
            button2.Enabled = true;
            button1.Enabled = false;
            button4.Enabled = false;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    speed = 0;
                    break;
                case 1:
                    speed = 100;
                    break;
                case 2:
                    speed = 200;
                    break;
                case 3:
                    speed = 500;
                    break;
            }
            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }

        }
        private void button2_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            comboBox1.Enabled = true;
            comboBox2.Enabled = true;
        }


        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            MessageBox.Show("Hi");
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (start == 0)
            {
                label1.Invoke(new Action(() =>
                {
                    label1.Text = "";
                }));
                label1.BorderStyle = BorderStyle.None;
                selectionStart = 0;
            }
            textBox1.ReadOnly = false;
            button1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = true;
            comboBox1.Enabled = true;
            comboBox2.Enabled = true;
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string s = textBox1.Text;
            string[] chars = new string[] { "-", "_", "—", "[", "]", "}", "{", "<", ">", ",", "*", "«", "»", "؛", ";", "\"", "/", "\\", "\'", "(", ")", "?", "‘", "”", "“", "#", "&" };
            string[] chars2 = new string[] { "ً", "ٌ", "ٍ", "َ", "ُ", "ّ" };
            string[] end1 = new string[] { "م", "ی", "د", "ه", "ت", "ش", "ن" };
            string[] end2 = new string[] { "یم", "ید", "ند", "ست", "ات", "ان", "ین", "تر", "یت", "یش", "ها" };
            string[] end3 = new string[] { "مان", "تان", "شان", "ییم", "یید", "یند", "انم", "انت", "انش", "تری" };

            //این موارد باید قبل از هر تغییری اعمال شود
            s = s.Replace("\n", "\r");
            s = s.Replace("\r\r\r\r", "\r");
            s = s.Replace("\r\r\r", "\r");
            s = s.Replace("\r\r", "\r");
            s = s.Replace("\r", " |||| ");
            s = s.Replace("ي", "ی");
            s = s.Replace("ي", "ی");
            s = s.Replace("ى", "ی");
            s = s.Replace("ك", "ک");
            s = s.Replace("ك", "ک");
            s = s.Replace("ئ", "ی");
            s = s.Replace("ؤ", "و");
            s = s.Replace("أ", "ا");
            //numbers
            s = s.Replace("۰", "0");
            s = s.Replace("۱", "1");
            s = s.Replace("۲", "2");
            s = s.Replace("۳", "3");
            s = s.Replace("۴", "4");
            s = s.Replace("۵", "5");
            s = s.Replace("۶", "6");
            s = s.Replace("۷", "7");
            s = s.Replace("۸", "8");
            s = s.Replace("۹", "9");


            s = s.Replace("(ره)", " ره^ ");
            s = s.Replace("(ص)", " ص^ ");
            s = s.Replace("(ع)", " ع^ ");
            s = s.Replace("(عج)", " عج^ ");
            s = s.Replace("(ق.م)", " قم^ ");
            s = s.Replace("(ه.ش)", " هش^ ");
            s = s.Replace("(ه.ق)", " هق^ ");
            s = s.Replace("بسم الله الرحمن الرحیم", "بسماللهالرحمنالرحیم");
            s = s.Replace(" را شکر", " راشکر");
            s = s.Replace("بُعد", "بوعد");


            s = s.Replace("@", " اتساین ");
            s = s.Replace("$", " دلار ");
            s = s.Replace("%", " درصد ");

            s = s.Replace("و...", " و غیره ");
            s = s.Replace("و…", " و غیره ");
            s = s.Replace("و …", " و غیره ");
            s = s.Replace("و ...", " و غیره ");
            s = s.Replace("...", ".");
            s = s.Replace("…", ".");

            s = s.Replace(".", " |||| ");
            s = s.Replace("؟", " |||| ");
            s = s.Replace("!", " ||| ");
            s = s.Replace(":", " ||| ");
            s = s.Replace("،", " ||| ");
            s = s.Replace("٬", " ||| ");


            foreach (string c in chars)
            {
                s = s.Replace(c, " ");
            }
            foreach (string c in chars2)
            {
                s = s.Replace(c, "");
            }
            //Adding Kasreh
            s = s.Replace("در حال ", "در حالِ ");
            s = s.Replace("در زمان ", "در زمانِ ");
            s = s.Replace("در هنگام ", "در هنگامِ ");
            s = s.Replace("نوش جان", "نوشِ جان");
            s = s.Replace("انمان ", "انِ مان ");
            s = s.Replace("انشان ", "انِ شان ");
            s = s.Replace("انتان ", "انِ تان ");


            s = s.Replace("هایم ", " هایم ");
            s = s.Replace("هایت ", " هایت ");
            s = s.Replace("هایش ", " هایش ");
            s = s.Replace("هایمان ", " هایمان ");
            s = s.Replace("هایتان ", " هایتان ");
            s = s.Replace("هایشان ", " هایشان ");
            s = s.Replace(" نمی", " نمی ");

            s = s.Replace("ترین ", " ترین ");
            s = s.Replace("‌", " ");
            s = s.Replace("­", " ");
            s = s.Replace("‏", " ");
            s = s.Replace("بکار", "به کار");
            s = s.Replace("بصورت", "به صورت");
            s = s.Replace("بدست", "به دست");
            s = s.Replace("بمعنی", "به معنی");
            s = s.Replace(" بین ", " بینهه ");
            s = s.Replace("قدر ", " قدر ");
            s = s.Replace(" غیر", " غیر ");
            s = s.Replace("های ", " های ");

            s = s.Replace("هایی ", " هایی ");
            s = s.Replace(" آنرا ", " آن را ");
            s = s.Replace("و گرنه ", "وگرنه ");
            s = s.Replace("می روم", "میروم");
            s = s.Replace("می روی", "میروی");
            s = s.Replace("می رود", "میرود");
            s = s.Replace("عکس العمل", "عکسالعمل");
            s = s.Replace("حق الزحم", "حقالزحم");
            s = s.Replace("فارغ التحصیل", "فارغالتحصیل");
            s = s.Replace("روبه رو", "رو به رو");
            s = s.Replace("لپ تاپ", "لپتاپ");
            s = s.Replace("انت های", "انتهای");

            s = s.Replace("ِ ", "ه ");
            s = s.Replace("ِ", "");

            s = s.Replace("  ", " ");

            string[] words = s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            if (record == true && words.Length > 5000)
            {
                MessageBox.Show("با توجه به حجم بالای فایل صوتی، متونی که بیش از 5000 لغت داشته باشند، برای ضبط، مجاز نمی‌باشند");
                backgroundWorker1.CancelAsync();
            }

            SoundPlayer simpleSound = new SoundPlayer();
            string pr = "", rem = "";

            for (i = start; i < words.Length; i++)
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                if (words[i] != "||||" && words[i] != "|||")
                {
                    textBox1.Invoke(new Action(() =>
                    {
                        int numberOfAttempt = 0;
                    Selection:
                        textBox1.Select(selectionStart, words[i].Length);
                        textBox1.ScrollToCaret();
                        if (textBox1.SelectedText.Length > 2 && words[i].Length > 2)
                        {
                            if (textBox1.SelectedText.Substring(0, 2) != words[i].Substring(0, 2))
                            {
                                if (numberOfAttempt <= 10 && i + numberOfAttempt < words.Length)
                                {
                                    selectionStart++;
                                    numberOfAttempt++;
                                    goto Selection;

                                }
                                else
                                {
                                    selectionStart -= numberOfAttempt;
                                }
                            }
                        }

                        selectionStart += textBox1.SelectedText.Length;
                    }));

                }
                else
                    selectionStart++;

            start: if (backgroundWorker1.CancellationPending == true)
                {
                    if (check == true)
                    {
                        start = 0;
                        selectionStart = 0;
                    }
                    else
                    {
                        start = i;
                    }
                    break;
                }

                if (words[i].Length == 0)
                    continue;



                //////اگر کلمه انگلیسی بود
                char[] alpha = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                if (alpha.Contains(Convert.ToChar(words[i].Substring(0, 1).ToLower())))
                {
                    comboBox2.Invoke(new Action(() =>
                {
                    ReaderIndex = comboBox2.SelectedIndex;

                }));

                    PlayEn(words[i], ReaderIndex);
                    continue;

                }

                ///////////اگر کلمه شامل عدد بود
                if (Regex.IsMatch(words[i], @"\d"))
                {
                    if (IsNumeric(words[i]))
                    {
                        if (i > 0 && i < words[i].Length && words.Length > 3)
                        {
                            if (alpha.Contains(Convert.ToChar(words[i - 1].Substring(0, 1).ToLower())) || alpha.Contains(Convert.ToChar(words[i + 1].Substring(0, 1).ToLower())))
                            {
                                comboBox2.Invoke(new Action(() =>
                                {
                                    ReaderIndex = comboBox2.SelectedIndex;

                                }));
                                PlayEn(words[i], ReaderIndex);
                                continue;
                            }
                        }
                        else
                        {
                            playNum(words[i]);
                            continue;
                        }
                    }
                    else
                    {
                        var m = Regex.Match(words[i], "([0-9]+|[ا-ی]+)");
                        while (m.Success)
                        {
                            if (IsNumeric(m))
                            {

                                playNum(m.ToString());
                                words[i] = words[i].Remove(0, m.Length);
                                goto start;
                            }
                            else
                            {

                                rem = words[i].Substring(m.Length, words[i].Length - m.Length);
                                words[i] = m.ToString();
                                break;
                            }
                            //m = m.NextMatch();
                        }
                    }
                }

                if (words[i] == "||||")
                {
                    if (record == true)
                    {
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                    }
                    else
                        System.Threading.Thread.Sleep(800);
                    continue;
                }
                if (words[i] == "|||")
                {
                    if (record == true)
                    {
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                        files.Add(@"audio\sp.wav");
                    }
                    else
                        System.Threading.Thread.Sleep(600);
                    continue;
                }

                if (words[i].Length == 1)
                {
                    if (words[i] == "و")
                        playLetter(204);
                    else if (words[i] == "ی")
                        playLetter(219);
                    else
                        playLetterByLetter(words[i]);
                    if (rem != "")
                    {
                        words[i] = rem;
                        rem = "";
                        goto start;
                    }
                    continue;
                }




            L:
                if (checkSpell(words[i]))
                    playPr(words[i]);
                else
                {
                    if (words[i].Length > 3 && checkSpell(words[i].Substring(0, words[i].Length - 3)) && end3.Contains(words[i].Substring(words[i].Length - 3, 3)))
                    {
                        pr = getPr(words[i].Substring(0, words[i].Length - 3));

                        switch (words[i].Substring(words[i].Length - 3, 3))
                        {
                            case "مان":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " یe م@ ن^";
                                else if (pr.Substring(pr.Length - 1, 1) == "@")
                                    pr += " م@ ن^";
                                else
                                {
                                    pr = pr.Substring(0, pr.Length - 1);
                                    pr = pr + "e م@ ن^";
                                }
                                playPr2(pr);
                                break;
                            case "تان":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " یe ت@ ن^";
                                else if (pr.Substring(pr.Length - 1, 1) == "@")
                                    pr += " ت@ ن^";
                                else
                                {
                                    pr = pr.Substring(0, pr.Length - 1);
                                    pr = pr + "e ت@ ن^";
                                }
                                playPr2(pr);
                                break;
                            case "شان":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " یe ش@ ن^";
                                else if (pr.Substring(pr.Length - 1, 1) == "@")
                                    pr += " ش@ ن^";
                                else
                                {
                                    pr = pr.Substring(0, pr.Length - 1);
                                    pr = pr + "e ش@ ن^";
                                }
                                playPr2(pr);
                                break;
                            case "ییم":
                                pr = pr + " یi م^";
                                playPr2(pr);
                                break;
                            case "یید":
                                pr = pr + " یi د^";
                                playPr2(pr);
                                break;
                            case "یند":
                                pr = pr + " یa ن^ د^";
                                playPr2(pr);
                                break;
                            case "انم":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " ی@ نa م^";
                                else
                                {
                                    pr = pr.Substring(0, pr.Length - 1) + "@ نa م^";
                                }
                                playPr2(pr);
                                break;
                            case "انت":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " ی@ نa ت^";
                                else
                                {
                                    pr = getPr(words[i].Substring(0, words[i].Length - 3));
                                    pr = pr.Substring(0, pr.Length - 1) + "@ نa ت^";
                                }
                                playPr2(pr);
                                break;
                            case "انش":
                                if (pr.Substring(pr.Length - 1, 1) == "i")
                                    pr += " ی@ نa ش^";
                                else
                                {
                                    pr = getPr(words[i].Substring(0, words[i].Length - 3));
                                    pr = pr.Substring(0, pr.Length - 1) + "@ نa ش^";
                                }
                                playPr2(pr);
                                break;
                            case "تری":
                                pr += " تa رi";
                                playPr2(pr);
                                break;
                        }
                    }
                    else
                    {

                        if (checkSpell(words[i].Substring(0, words[i].Length - 2)) && end2.Contains(words[i].Substring(words[i].Length - 2, 2)))
                        {
                            //اگر انتهای آن یم یا ید یا ند بود

                            pr = getPr(words[i].Substring(0, words[i].Length - 2));
                            pr = pr.Substring(0, pr.Length - 1);
                            switch (words[i].Substring(words[i].Length - 2, 2))
                            {
                                case "یم":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));

                                    if (pr.Substring(pr.Length - 1, 1) == "@")
                                        pr = pr + " یa م^";
                                    else if (pr.Substring(pr.Length - 1, 1) == "u")
                                        pr = pr + " یa م^";
                                    else
                                    {
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "i م^";
                                    }
                                    playPr2(pr);
                                    break;
                                case "ید":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));

                                    if (pr.Substring(pr.Length - 1, 1) == "@")
                                        pr = pr + " یa د^";
                                    else if (pr.Substring(pr.Length - 1, 1) == "u")
                                        pr = pr + " یa د^";
                                    else
                                    {
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "i د^";
                                    }
                                    playPr2(pr);
                                    break;
                                case "ند":
                                    pr = pr + "a ن^ د^";
                                    playPr2(pr);
                                    break;
                                case "ست":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));
                                    pr = pr + " س^ ت^";
                                    playPr2(pr);
                                    break;
                                case "ات":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));

                                    if (pr.Substring(pr.Length - 1, 1) == "i")
                                        pr = pr + " ی@ ت^";
                                    else
                                    {
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "@ ت^";
                                    }
                                    playPr2(pr);
                                    break;
                                case "ان":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));

                                    if (pr.Substring(pr.Length - 1, 1) == "i")
                                        pr = pr + " ی@ ن^";
                                    else
                                    {
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "@ ن^";
                                    }
                                    playPr2(pr);
                                    break;
                                case "ین":
                                    pr = pr + "i ن^";
                                    playPr2(pr);
                                    break;
                                case "تر":
                                    pr = pr + "^ تa ر^";
                                    playPr2(pr);
                                    break;
                                case "یت":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));
                                    pr = pr + " یa ت^";
                                    playPr2(pr);
                                    break;
                                case "یش":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));
                                    pr = pr + " یa ش^";
                                    playPr2(pr);
                                    break;
                                case "ها":
                                    pr = getPr(words[i].Substring(0, words[i].Length - 2));
                                    pr = pr + " ه@";
                                    playPr2(pr);
                                    break;
                            }

                        }
                        else
                        {
                            if (checkSpell(words[i].Substring(0, words[i].Length - 1)) && end1.Contains(words[i].Substring(words[i].Length - 1, 1)))
                            {
                                //اگر انتهای کلمه ه یا م یا ی بود
                                pr = getPr(words[i].Substring(0, words[i].Length - 1));

                                switch (words[i].Substring(words[i].Length - 1, 1))
                                {
                                    case "م":
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "a م^";
                                        playPr2(pr);
                                        break;
                                    case "د":
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "a د^";
                                        playPr2(pr);
                                        break;
                                    case "ی":
                                        if (pr.Substring(pr.Length - 1, 1) == "u" || pr.Substring(pr.Length - 1, 1) == "@")
                                            pr = pr + " یe";
                                        else
                                        {
                                            pr = pr.Substring(0, pr.Length - 1);
                                            pr = pr + "i";
                                        }
                                        playPr2(pr);
                                        break;
                                    case "ه":
                                        if (pr.Substring(pr.Length - 1, 1) == "i")
                                            pr = pr + " یe";
                                        else
                                        {
                                            pr = pr.Substring(0, pr.Length - 1);
                                            pr = pr + "e";
                                        }
                                        playPr2(pr);
                                        break;
                                    case "ت":
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "a ت^";
                                        playPr2(pr);
                                        break;
                                    case "ش":
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "a ش^";
                                        playPr2(pr);
                                        break;
                                    case "ن":
                                        pr = pr.Substring(0, pr.Length - 1);
                                        pr = pr + "a ن^";
                                        playPr2(pr);
                                        break;
                                }
                            }
                            else if (words[i].Substring(0, 2) == "نا" && checkSpell(words[i].Substring(2, words[i].Length - 2)))
                            {
                                playLetter(200);
                                words[i] = words[i].Substring(2, words[i].Length - 2);
                                goto L;
                            }
                            else if (words[i].Substring(0, 1) == "ن")//بررسی فعل منفی آغاز شونده با ن
                            {
                                playLetter(197);
                                words[i] = words[i].Substring(1, words[i].Length - 1);
                                goto L;
                            }
                            else if (words[i].Substring(0, 1) == "ب")//بررسی فعل آغاز شونده با ب
                            {
                                playLetter(9);
                                words[i] = words[i].Substring(1, words[i].Length - 1);
                                goto L;
                            }
                            else if (words[i].Substring(0, 2) == "می")
                            {
                                playLetter(194);
                                words[i] = words[i].Substring(2, words[i].Length - 2);
                                goto L;
                            }

                            else
                                playLetterByLetter(words[i]);
                        }
                    }
                }

                if (record == true)
                {
                    int sp2 = speed;
                    while (sp2 > 1)
                    {
                        files.Add(@"audio\sp.wav");
                        sp2 -= 100;
                    }
                }
                else
                    System.Threading.Thread.Sleep(speed);
                if (rem != "")
                {
                    words[i] = rem;
                    rem = "";
                    goto start;
                }
                label1.Invoke(new Action(() =>
                {
                    label1.BorderStyle = BorderStyle.FixedSingle;
                    if (words.Length < label1.Width)
                    {
                        for (int l = 0; l < label1.Width / words.Length; )
                        {
                            label1.Text += "|";
                            l += 2;
                        }
                    }
                    else
                    {
                        int wl = words.Length, lw = label1.Width;
                        float m = (float)lw / (float)wl;

                        if (i % 10 == 0)
                            for (int n = 0; n < Convert.ToInt16(m.ToString().Substring(2, 1)); n++)
                                if (n % 2 == 0)
                                    label1.Text += "|";
                    }

                }));
            }
            if (record == true)
            {
                WaveIO wa = new WaveIO();
                wa.Merge(files, @saveoutput, format);
            }

            con.Close();
        }









        /////////////////////////////////////////توابع

        /// <summary>
        /// بررسی وجود یا عدم وجود اسپل
        /// </summary>
        /// <param name="pr"></param>
        public static Boolean checkSpell(string word)
        {
            SoundPlayer simpleSound = new SoundPlayer();
            string query = "select pr from Entries where word=\"" + word + "\"";
            myCommand.CommandText = query;
            OleDbDataReader reader = myCommand.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                string s = reader[0].ToString();
                reader.Close();

                if (s == "")
                {

                    return false;
                }
                else
                    return true;

            }
            else
            {
                reader.Close();
                return false;
            }
        }


        /// <summary>
        /// پیدا کردن تلفظ
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        public static string getPr(string word)
        {
            SoundPlayer simpleSound = new SoundPlayer();
            string query = "select pr from Entries where word=\"" + word + "\" order by Freq DESC";
            myCommand.CommandText = query;
            OleDbDataReader reader = myCommand.ExecuteReader();

            if (reader.HasRows)
            {
                reader.Read();
                string s = reader[0].ToString();
                reader.Close();
                return s;

            }
            else
            {
                reader.Close();
                return "";
            }
        }


        /// <summary>
        /// تلفظ با حرکات حروف
        /// </summary>
        /// <param name="pr"></param>

        public static void playPr(string pr)
        {
            SoundPlayer simpleSound = new SoundPlayer();
            string query = "select pr from Entries where word=\"" + pr + "\" order by Freq DESC";
            myCommand.CommandText = query;
            OleDbDataReader reader = myCommand.ExecuteReader();
            reader.Read();

            pr = reader[0].ToString();
            string query_to_letter;
            string[] pr_splited;
            pr_splited = pr.Split(' ');
            reader.Close();

            OleDbDataReader reader2 = null;

            foreach (string str in pr_splited)
            {
                query_to_letter = "select file_number from pr where letter=\"" + str + "\"";
                myCommand.CommandText = query_to_letter;
                reader2 = myCommand.ExecuteReader();

                if (reader2.HasRows)
                {
                    reader2.Read();
                    //UnmanagedMemoryStream ms = Properties.Resources.ResourceManager.GetStream("audio.Resource1._" + reader2[0]);
                    //simpleSound = new SoundPlayer(ms);
                    simpleSound.SoundLocation = @"audio\" + reader2[0] + ".wav";
                    if (record == true)
                        files.Add(@"audio\" + reader2[0] + ".wav");
                    else
                        simpleSound.Play();


                    if (record == true)
                    {
                        int sp2 = speed;
                        while (sp2 > 1)
                        {
                            files.Add(@"audio\sp.wav");
                            sp2 -= 100;
                        }
                    }
                    else
                    {
                        int x = SoundInfo.GetSoundLength(simpleSound.SoundLocation);
                        System.Threading.Thread.Sleep(x + speed / 10);
                    }
                }

                reader2.Close();
            }
            reader2.Close();

        }



        /// <summary>
        /// تابع تبدیل تلفظ به صوت
        /// </summary>
        /// <param name="pr"></param>
        public static void playPr2(string pr)
        {
            SoundPlayer simpleSound = new SoundPlayer();


            string query_to_letter;
            string[] pr_splited;
            pr_splited = pr.Split(' ');

            OleDbDataReader reader2 = null;
            foreach (string str in pr_splited)
            {
                query_to_letter = "select file_number from pr where letter=\"" + str + "\"";
                myCommand.CommandText = query_to_letter;
                reader2 = myCommand.ExecuteReader();
                if (reader2.HasRows)
                {
                    try
                    {
                        while (reader2.Read())
                        {
                            simpleSound.SoundLocation = @"audio\" + reader2[0] + ".wav";

                        }
                    }

                    finally
                    {
                        reader2.Close();
                    }
                    if (record == true)
                        files.Add(simpleSound.SoundLocation);
                    else
                        simpleSound.Play();


                    if (record == true)
                    {
                        int sp2 = speed;
                        while (sp2 > 1)
                        {
                            files.Add(@"audio\sp.wav");
                            sp2 -= 100;
                        }
                    }
                    else
                    {
                        int x = SoundInfo.GetSoundLength(simpleSound.SoundLocation);
                        System.Threading.Thread.Sleep(x + speed / 10);
                    }
                }
                reader2.Close();
            }
            reader2.Close();
        }

        /// <summary>
        /// خواندن اعداد
        /// </summary>
        /// <param name="str"></param>
        public static void playNum(string str)
        {
            string pr = null;
            if (str.Length < 13)
            {
                string num = ConvertRaghamToHorof(Int64.Parse(str));
                num = num.Replace("  ", " ");
                string[] nums = num.Split(' ');
                for (int j = 0; j < nums.Length; j++)
                {

                    pr += getPr(nums[j]) + " ";
                }
                pr = pr.Replace("^ وa", "o");
                pr = pr.Replace("i وa", "i یo");
            }
            playPr2(pr);
        }
        public static void playLetterByLetter(string str)
        {
            SoundPlayer simpleSound = new SoundPlayer();

            for (int j = 0; j < str.Length; j++)
            {
                switch (str.Substring(j, 1))
                {
                    case "1":
                        playPr("یک");
                        break;
                    case "2":
                        playPr("دو");
                        break;
                    case "3":
                        playPr("سه");
                        break;
                    case "4":
                        playPr("چهار");
                        break;
                    case "5":
                        playPr("پنج");
                        break;
                    case "6":
                        playPr("شش");
                        break;
                    case "7":
                        playPr("هفت");
                        break;
                    case "8":
                        playPr("هشت");
                        break;
                    case "9":
                        playNum("9");
                        break;
                    default:
                        if (j < str.Length - 1)
                        {
                            if (str.Substring(j + 1, 1) == "ا")
                            {
                                playPr2(str.Substring(j, 1) + "@ ");
                                j++;
                                break;
                            }
                            else
                                if (str.Substring(j + 1, 1) == "ی")
                                {
                                    playPr2(str.Substring(j, 1) + "i ");
                                    j++;
                                    break;
                                }
                                else
                                    if (str.Substring(j + 1, 1) == "و")
                                    {
                                        playPr2(str.Substring(j, 1) + "u ");
                                        j++;
                                        break;
                                    }
                        }

                        string query2 = "select file_number from Entries where word=\"" + str.Substring(j, 1) + "\" order by Freq DESC";

                        myCommand.CommandText = query2;

                        OleDbDataReader reader2 = myCommand.ExecuteReader();

                        if (reader2.HasRows)
                        {
                            try
                            {
                                while (reader2.Read())
                                {
                                    if (reader2[0].ToString() == "172")
                                        simpleSound.SoundLocation = @"audio\230.wav";
                                    else
                                        simpleSound.SoundLocation = @"audio\" + reader2[0] + ".wav";
                                }
                            }
                            finally
                            {
                                reader2.Close();
                            }
                            if (File.Exists(@simpleSound.SoundLocation))
                            {
                                if (record == true)
                                    files.Add(@simpleSound.SoundLocation);
                                else
                                {
                                    simpleSound.Play();

                                }
                            }
                            else
                            {
                                char[] alpha = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                                if (alpha.Contains(Convert.ToChar(str.Substring(j, 1).ToLower())))
                                {
                                    playPr(str.Substring(j, 1).ToLower());
                                }
                            }

                            if (record == true)
                            {
                                int sp2 = speed;
                                while (sp2 > 1)
                                {
                                    files.Add(@"audio\sp.wav");
                                    sp2 -= 100;
                                }
                            }
                            else
                            {
                                int x = SoundInfo.GetSoundLength(simpleSound.SoundLocation);
                                System.Threading.Thread.Sleep(x + speed / 10);
                            }
                        }
                        reader2.Close();
                        break;
                }
            }
        }




        public static void playLetter(int num)
        {

            SoundPlayer simpleSound = new SoundPlayer();
            simpleSound.SoundLocation = @"audio\" + num + ".wav";
            if (record == true)
            {
                files.Add(@"audio\" + num + ".wav");
            }
            else
            {
                simpleSound.Play();

                int x2 = SoundInfo.GetSoundLength(simpleSound.SoundLocation);
                System.Threading.Thread.Sleep(x2);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Control && (e.KeyCode == System.Windows.Forms.Keys.Space))
            {
                if (button1.Enabled == true)
                    button1_Click(sender, e);
            }
            else if (e.KeyCode == System.Windows.Forms.Keys.Space)
            {
                if (button1.Enabled == false)
                    button2_Click(sender, e);
            }
            else
                base.OnKeyDown(e);

        }

        #region ConvertRaghamToHorof
        /// <summary>
        /// عدد رادریافت وبه حروف تبدیل می کند 
        /// </summary>
        /// <param name="Ragham">رقم </param>
        /// <returns>به حروف عدد را برمی گرداند</returns>
        public static string ConvertRaghamToHorof(Int64 Ragham)
        {
            return ConvertRaghamToHorof(ConvertRaghamToJodaJoda(Ragham));
        }
        /// <summary>
        /// یک عدد به صورت سه رقم جدا را دریافت وبه حروف تبدیل می کند
        /// </summary>
        /// <param name="Ragham"></param>
        /// <returns></returns>
        public static string ConvertRaghamToHorof(string Ragham)
        {
            string horof = "";

            try
            {
                string[] AddJoda = Ragham.Split(',');
                for (int i = 0; i < AddJoda.Length; i++)
                {
                    //MessageBox.Show(AddJoda[i]);
                    string strh = pishConvertRaghamToHorof3(int.Parse(AddJoda[i]), AddJoda.Length - i);
                    if (horof == "")
                    {
                        horof = horof + strh;
                    }
                    else
                    {
                        if (strh != "") horof = horof + " و " + strh;
                    }

                }
                return horof;
            }
            catch (Exception e1)
            {
                return "error";
            }
            finally
            {
            }

        }
        /// <summary>
        /// اعداد از صفر تا 19 را به حروف تبدیل میکند
        /// </summary>
        /// <param name="Ragham">عدد بین 0 تا 19</param>
        /// <returns>حروف را برمی گرداند در صورت خطا -1  و درصورت عدد نامعتبر تهی برمی گرداند</returns>
        private static string ConvertRaghamToHorof0to19(int Ragham)
        {
            try
            {
                //اعداد صفر  تا بیست
                if (Ragham > 19) return "";
                switch (Ragham)
                {
                    case 0:
                        return "صفر ";
                    case 1:
                        return "یک ";
                    case 2:
                        return "دو";
                    case 3:
                        return "سه ";
                    case 4:
                        return "چهار";
                    case 5:
                        return "پنج ";
                    case 6:
                        return "شش ";
                    case 7:
                        return "هفت ";
                    case 8:
                        return "هشت ";
                    case 9:
                        return "نُه ";
                    case 10:
                        return "ده ";
                    case 11:
                        return "یازده ";
                    case 12:
                        return "دوازده ";
                    case 13:
                        return "سیزده ";
                    case 14:
                        return "چهارده ";
                    case 15:
                        return "پانزده ";
                    case 16:
                        return "شانزده ";
                    case 17:
                        return "هفده ";
                    case 18:
                        return "هیجده ";
                    case 19:
                        return "نوزده ";
                    //case 20:
                    //    return "بیست"; 

                }


                return "";
            }
            catch (Exception e)
            {
                return "-1";
            }
            finally
            {
            }
        }
        /// <summary>
        /// اعداد از بیست   تا نود نه را به حروف تبدیل میکند
        /// </summary>
        /// <param name="Ragham">عدد بین 20 تا 99</param>
        /// <returns>حروف را برمی گرداند در صورت خطا -1  و درصورت عدد نامعتبر تهی برمی گرداند</returns>
        private static string ConvertRaghamToHorof20to99(int Ragham)
        {
            try
            {
                //اعداد صفر  تا بیست
                if (!(Ragham > 19 && Ragham < 100)) return "";
                // برای تبدیل به حروف  رقم دوم
                string str = ConvertRaghamToHorof0to19(int.Parse(Ragham.ToString().Substring(1)));
                if (Ragham > 19 && Ragham < 30)
                {
                    if (Ragham == 20)
                    {
                        return "بیست";
                    }
                    else
                    {
                        return "بیست و " + str;
                    }

                }
                else if (Ragham > 29 && Ragham < 40)
                {
                    if (Ragham == 30)
                    {
                        return "سی";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "سی و " + str;
                    }
                }
                else if (Ragham > 39 && Ragham < 50)
                {
                    if (Ragham == 40)
                    {
                        return "چهل";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "چهل و " + str;
                    }
                }
                else if (Ragham > 49 && Ragham < 60)
                {
                    if (Ragham == 50)
                    {
                        return "پنجاه";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "پنجاه و " + str;
                    }
                }
                else if (Ragham > 59 && Ragham < 70)
                {
                    if (Ragham == 60)
                    {
                        return "شصت";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "شصت و " + str;
                    }
                }
                else if (Ragham > 69 && Ragham < 80)
                {
                    if (Ragham == 70)
                    {
                        return "هفتاد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "هفتاد و " + str;
                    }
                }
                else if (Ragham > 79 && Ragham < 90)
                {
                    if (Ragham == 80)
                    {
                        return "هشتاد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "هشتاد و " + str;
                    }
                }
                else if (Ragham > 89 && Ragham < 100)
                {
                    if (Ragham == 90)
                    {
                        return "نود";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "نود و " + str;
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                return "-1";
            }
            finally
            {
            }

        }
        /// <summary>
        /// اعداد از 0   تا نود نه را به حروف تبدیل میکند
        /// </summary>
        /// <param name="Ragham">عدد بین 0 تا 99</param>
        /// <returns>حروف را برمی گرداند در صورت خطا -1  و درصورت عدد نامعتبر تهی برمی گرداند</returns>
        private static string ConvertRaghamToHorof0to99(int Ragham)
        {
            try
            {
                if (Ragham > 99) return "";
                if (Ragham < 20)
                {
                    return ConvertRaghamToHorof0to19(Ragham);
                }
                else if (Ragham < 100)
                {
                    return ConvertRaghamToHorof20to99(Ragham);
                }
                return "";
            }
            catch (Exception e)
            {
                return "";
            }
            finally
            { }
        }
        /// <summary>
        /// اعداد از صد  تانهصدو نودو نه را به حروف تبدیل میکند
        /// </summary>
        /// <param name="Ragham">عدد بین 100 تا 999</param>
        /// <returns>حروف را برمی گرداند در صورت خطا -1  و درصورت عدد نامعتبر تهی برمی گرداند</returns>
        private static string ConvertRaghamToHorof100to999(int Ragham)
        {
            try
            {
                //اعداد 100  تا 999
                if (!(Ragham > 99 && Ragham < 1000)) return "";
                // برای تبدیل به حروف  رقم دوم

                string str = ConvertRaghamToHorof0to99(int.Parse(Ragham.ToString().Substring(1)));
                if (Ragham > 99 && Ragham < 200)
                {
                    if (Ragham == 100)
                    {
                        return "صد";
                    }
                    else
                    {
                        return "صد و " + str;
                    }

                }
                else if (Ragham > 199 && Ragham < 300)
                {
                    if (Ragham == 200)
                    {
                        return "دویست";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "دویست و " + str;
                    }
                }
                else if (Ragham > 299 && Ragham < 400)
                {
                    if (Ragham == 300)
                    {
                        return "سیصد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "سیصد و " + str;
                    }
                }
                else if (Ragham > 399 && Ragham < 500)
                {
                    if (Ragham == 400)
                    {
                        return "چهارصد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "چهارصد و " + str;
                    }
                }
                else if (Ragham > 499 && Ragham < 600)
                {
                    if (Ragham == 500)
                    {
                        return "پانصد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "پانصد و " + str;
                    }
                }
                else if (Ragham > 599 && Ragham < 700)
                {
                    if (Ragham == 600)
                    {
                        return "شش صد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "شش صد و " + str;
                    }
                }
                else if (Ragham > 699 && Ragham < 800)
                {
                    if (Ragham == 700)
                    {
                        return "هفت صد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "هفت صد و " + str;
                    }
                }
                else if (Ragham > 799 && Ragham < 900)
                {
                    if (Ragham == 800)
                    {
                        return "هشت صد ";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "هشت صد و " + str;
                    }
                }
                else if (Ragham > 899 && Ragham < 1000)
                {
                    if (Ragham == 900)
                    {
                        return "نُه صد";
                    }
                    else
                    {
                        //string str = ConvertRaghamToHorof0to20(Ragham.ToString().Substring(1));
                        return "نُه صد و " + str;
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                return "-1";
            }
            finally
            {
            }

        }
        /// <summary>
        /// اعداد از صفر تا 999 را به حروف تبدیل می کند
        /// </summary>
        /// <param name="Ragham"></param>
        /// <returns></returns>
        private static string ConvertRaghamToHorof0to999(int Ragham)
        {
            try
            {

                if (!(Ragham < 1000)) return "";

                if (Ragham < 20)
                {
                    return ConvertRaghamToHorof0to19(Ragham);
                }
                else if (Ragham > 19 && Ragham < 100)
                {
                    return ConvertRaghamToHorof20to99(Ragham);
                }
                else if (Ragham > 99 && Ragham < 1000)
                {
                    return ConvertRaghamToHorof100to999(Ragham);
                }
                else
                {
                    return "خطا برنامه نویسی";
                }

                return "";
            }
            catch (Exception e)
            {
                return "-1";
            }
            finally
            {
            }

        }
        /// <summary>
        /// یک عدد سه رقمی و موقعیت انرا دریافت و به حروف تبدیل می کند
        /// </summary>
        /// <param name="Ragham">عدد سه رقمی</param>
        /// <param name="LocationRagham"> موقیت عدد 2 =هزار 3== میلیون 4= میلیارد</param>
        /// <returns></returns>
        private static string pishConvertRaghamToHorof3(int Ragham, int LocationRagham)
        {
            try
            {   //اگر عدد صفر نیازبه پیش ندارد
                if (Ragham == 0) return "";
                if (Ragham > 1000) return "";

                //string str = ConvertRaghamToHorof0to999(Ragham);
                if (Ragham == 0) return "";
                switch (LocationRagham)
                {
                    case 1:
                        return ConvertRaghamToHorof0to999(Ragham);
                    case 2:
                        return ConvertRaghamToHorof0to999(Ragham) + " هزار ";
                    case 3:
                        return ConvertRaghamToHorof0to999(Ragham) + " میلیون ";
                    case 4:
                        return ConvertRaghamToHorof0to999(Ragham) + " میلیارد ";
                    case 5:
                        return ConvertRaghamToHorof0to999(Ragham) + " تریلیارد ";
                    case 6:

                        return ConvertRaghamToHorof0to999(Ragham) + " ??? ";
                    case 7:

                        return ConvertRaghamToHorof0to999(Ragham) + " ??? ";
                    case 8:

                        return ConvertRaghamToHorof0to999(Ragham) + " ??? ";
                    case 9:

                        return ConvertRaghamToHorof0to999(Ragham) + " ??? ";
                }

                return "";
            }
            catch (Exception e)
            {
                return "error";
            }
            finally
            {
            }

        }

        /// <summary>
        /// یک رقم را سه رقم سه رقم جدا می کند
        /// </summary>
        /// <param name="Ragham">رقم که باید حداکثر دوازده رقم باشد</param>
        /// <returns>جداشده سه رقم سه رقم را برمی گرداند</returns>
        public static string ConvertRaghamToJodaJoda(Int64 Ragham)
        {

            try
            {
                string Add = Ragham.ToString();
                Add = Add.Trim(); //فقط دوازده رقم را پشتیبانی می کند
                if (Add.Length > 15) Add = Add.Substring(0, 15);
                if (Add.Trim() == "")
                {

                    return "";
                }

                string j = "";

                if ((Add.Length > 3 && Add.Length < 6) || Add.Length == 6)
                {
                    //MessageBox.Show(i.Substring(3, 1));
                    Add = Add.Substring(0, Add.Length - 3) + "," + Add.Substring(Add.Length - 3, 3);
                }
                else if ((Add.Length > 6 && Add.Length < 9) || Add.Length == 9)
                {

                    Add = Add.Substring(0, Add.Length - 6) +
                           "," + Add.Substring(Add.Length - 6, 3) +
                           "," + Add.Substring(Add.Length - 3, 3);

                }
                else if ((Add.Length > 9 && Add.Length < 12) || Add.Length == 12)
                {
                    //MessageBox.Show(i.Substring(3, 1));
                    Add = Add.Substring(0, Add.Length - 9) +
                          "," + Add.Substring(Add.Length - 9, 3) +
                          "," + Add.Substring(Add.Length - 6, 3) +
                    "," + Add.Substring(Add.Length - 3, 3);
                    //Add = Add.Substring(0, 3) +
                    //       "," + Add.Substring(3, 3) +
                    //       "," + Add.Substring(6, 3) +
                    //       "," + Add.Substring(9, Add.Length - 9);
                }
                else if (Add.Length > 12 && Add.Length < 15)
                {
                    //MessageBox.Show(i.Substring(3, 1));
                    Add = Add.Substring(0, 3) +
                           "," + Add.Substring(3, 3) +
                           "," + Add.Substring(6, 3) +
                            "," + Add.Substring(9, 3) +
                           "," + Add.Substring(12, Add.Length - 12);
                }
                else if (Add.Length < 3)
                {

                }

                return Add;
            }


            catch (Exception e)
            {
                //ClsGlobalClass.ShowMessageErrorFarsi(e, "ConvertRaghamToJodaJoda(Int64 Ragham)");
                return "";

            }
            finally
            {
                //ObjBankPatern.SqlConnection.Close();
                //cmd.Dispose();
                //dap.Dispose();
            }
        }
        #endregion ConvertRaghamToHorof


        public static void PlayEn(string s, int ReaderIndex)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            if (ReaderIndex == 1)
                synth.SelectVoice("LH Michael");
            else
                if (ReaderIndex == 2)
                    synth.SelectVoice("LH Michelle");
            if (record == true)
            {
                System.Speech.AudioFormat.SpeechAudioFormatInfo formatInfo = new System.Speech.AudioFormat.SpeechAudioFormatInfo(22050,
System.Speech.AudioFormat.AudioBitsPerSample.Sixteen,
System.Speech.AudioFormat.AudioChannel.Stereo);
                synth.SetOutputToWaveFile("temp\\" + i + ".wav", formatInfo);
                files.Add("temp\\" + i + ".wav");
            }
            synth.Speak(s);

            synth.Dispose();

        }

        public static Boolean IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;

            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return true;
            }
            catch { } // just dismiss errors but return false
            return false;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            start = 0;
            selectionStart = 0;
            label1.Invoke(new Action(() =>
            {
                label1.Text = "";
            }));
            label1.BorderStyle = BorderStyle.None;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            check = true;
            backgroundWorker1.CancelAsync();
            comboBox1.Enabled = true;
            comboBox2.Enabled = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            bool recCancel = false;
            if (textBox1.Text == "")
            {
                MessageBox.Show("لطفاً متنی را در فیلد متنی برنامه درج و سپس اقدام به ضبط صدا نمایید");
                recCancel = true;
                textBox1.Focus();
                goto cancel;
            }
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Wav Files (*.WAV)|*.wav|MP3(*.mp3)|*.mp3";



            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                saveoutput = saveFileDialog1.FileName;
                if (saveFileDialog1.FilterIndex == 1)
                    format = "wav";
                else
                    format = "mp3";
                FileStream fs = null;
                try
                {
                    fs = new FileStream(saveoutput, FileMode.Create, FileAccess.Write);
                    fs.Close();
                }
                catch
                {
                    MessageBox.Show("به نظر می‌رسد فایل مورد نظر در برنامه دیگری باز است. ابتدا آن را ببندید و دوباره سعی کنید");
                    recCancel = true;
                    goto cancel;
                }
            }
            else
            {
                recCancel = true;
                goto cancel;
            }



            textBox1.ReadOnly = true;
            files.Clear();
            check = false;
            record = true;
            button4.Enabled = false;
            button3.Enabled = true;
            button2.Enabled = true;
            button1.Enabled = false;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    speed = 0;
                    break;
                case 1:
                    speed = 100;
                    break;
                case 2:
                    speed = 200;
                    break;
                case 3:
                    speed = 500;
                    break;
            }
            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }
        cancel:
            if (recCancel == true)
                MessageBox.Show("عملیات ضبط لغو شد");
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
        }

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

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

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

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 frm = new AboutBox1();
            frm.ShowDialog();
        }

        private void playToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button1_Click(sender, e);
        }

        private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button2_Click(sender, e);
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button3_Click(sender, e);
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("docs\\ParsKhan_Help.pdf");
        }

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

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);
            textBox1.SelectedText = "";
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectionIndex = textBox1.SelectionStart;
            textBox1.Text = textBox1.Text.Insert(textBox1.SelectionStart, Clipboard.GetText());
            textBox1.SelectionStart = selectionIndex + Clipboard.GetText().Length;
            textBox1.ScrollToCaret();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.SelectAll();
        }

        private void switchDirectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (textBox1.RightToLeft == System.Windows.Forms.RightToLeft.Yes)
                textBox1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            else
                textBox1.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        }

        private void runFarsiCorrectorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            text = text.Replace("ي", "ی");
            text = text.Replace("ى", "ی");
            text = text.Replace("ك", "ک");
            text = text.Replace(" ها ", "‌ها ");
            text = text.Replace(" های ", "‌های ");
            text = text.Replace(" می ", " می‌");

            text = text.Replace(" اند ", "‌اند ");
            text = text.Replace(" ای ", "‌ای ");
            text = text.Replace(" اش ", "‌اش ");
            text = text.Replace(" ات ", "‌ات ");
            text = text.Replace(" شان ", "‌شان ");
            text = text.Replace(" مان ", "‌مان ");
            text = text.Replace(" تان ", "‌تان ");
            text = text.Replace(" ام ", "‌ام ");
            text = text.Replace(" ایم ", "‌ایم ");
            text = text.Replace(" اید ", "‌اید ");
            text = text.Replace(" ی ", "‌ی ");
            text = text.Replace(" .", ".");
            text = text.Replace(". ", ".");
            text = text.Replace(".", ". ");
            text = text.Replace(". . . ", " ... ");
            text = text.Replace(" ،", "،");
            text = text.Replace("، ", "،");
            text = text.Replace("،", "، ");
            text = text.Replace(": ", ":");
            text = text.Replace(" :", ":");
            text = text.Replace(":", ": ");
            text = text.Replace("؛ ", "؛");
            text = text.Replace(" ؛", "؛");
            text = text.Replace("؛", "؛ ");
            text = text.Replace(" !", "!");
            text = text.Replace("! ", "!");
            text = text.Replace("!", "! ");
            text = text.Replace("( ", "(");
            text = text.Replace(" (", "(");
            text = text.Replace("(", " (");
            text = text.Replace(" )", ")");
            text = text.Replace(") ", ")");
            text = text.Replace(")", ") ");
            text = text.Replace("« ", "«");
            text = text.Replace(" «", "«");
            text = text.Replace("«", " «");
            text = text.Replace("» ", "»");
            text = text.Replace(" »", "»");
            text = text.Replace("»", "» ");
            text = text.Replace(" ؟", "؟");
            text = text.Replace("؟ ", "؟");
            text = text.Replace("؟", "؟ ");
            text = text.Replace(" “", "“");
            text = text.Replace("“ ", "“");
            text = text.Replace("“", " “");
            text = text.Replace(" ”", "”");
            text = text.Replace("” ", "”");
            text = text.Replace("”", "” ");
            text = text.Replace(" ترین", "‌ترین");
            text = text.Replace(" تر ", "‌تر ");
            text = text.Replace(" تری ", "‌تری ");
            text = text.Replace(" انداز", "‌انداز");
            text = text.Replace(" افزار", "‌افزار");
            text = text.Replace(" بندی ", "‌بندی ");
            text = text.Replace(" سازی ", "‌سازی ");
            text = text.Replace("آنها", "آن‌ها");
            text = text.Replace(" بی ", " بی‌");
            text = text.Replace(" نمی ", " نمی");
            text = text.Replace(" نمی", " نمی‌‌");
            text = text.Replace(" نمی‌‌", " نمی‌");
            textBox1.Text = text;
        }

        private void checkForUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://parskhan.aftab.cc/update/?v=1.0.0");
        }

        private void parsKhanWebsiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://parskhan.aftab.cc/");
        }

        private void aftabgardanWebsiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://aftab.cc/");
        }

        private void onlineHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://parskhan.aftab.cc/docs/");
        }

        private void virastyarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.virastyar.ir/live");
        }

        private void helpUsToImproveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://parskhan.aftab.cc/add/");
        }

        private void parsKhanForumsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://parskhan.aftab.cc/forums/");
        }

        private void contactUsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://aftab.cc/modules.php?name=Contact_Plus");
        }

        private void slangToFormalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://tools.aftab.cc/s2f");
        }

        private void alwaysOnTopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            alwaysOnTopToolStripMenuItem.Checked = true;
            if (this.TopMost == true)
                this.TopMost = false;
            else
                this.TopMost = true;
        }

    }







    /// <summary>
    /// کلاس مشخصات فایل صوتی
    /// </summary>
    public static class SoundInfo
    {

        [DllImport("winmm.dll")]
        private static extern uint mciSendString(
            string command,
            StringBuilder returnValue,
            int returnLength,
            IntPtr winHandle);

        public static int GetSoundLength(string fileName)
        {
            StringBuilder lengthBuf = new StringBuilder(32);

            mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);
            mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);
            mciSendString("close wave", null, 0, IntPtr.Zero);

            int length = 0;
            int.TryParse(lengthBuf.ToString(), out length);

            return length;
        }
    }
}