﻿using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Timers;
using System.Media;
using System.Threading;
using System.Globalization;

// txt2com.exe
// ทำงานแบบ Windows Application 
namespace Original
{
    public class G
    {
        public static string cpFlag;
        public static string cpCom;
        public static string cpCompany;
        public static string cpFileText;
        public static string cFoldLink;
        public static string cHistory="0";
        public static string cpAct4group="0";
        public static string cpAct4single = "0";
        public static int nFileType=0;
        public static int nFileRun = 0;
        public static bool lInForm=false;  
		public static bool lFullremark = false; // แสดงไฟล์Textแบบเต็ม  
        // public static bool lDebug = false;
    }
   
    //    **** Start Window Form 
    public class WAmphan : Form
    {
        private static System.Timers.Timer runTimer;
        public Button bMinimize, bOpFle, bExit;
        public static Label  ctext1, ctext2, ctextF;
        public static Int32 nCount = 1;
        public static DateTime dStartDate = DateTime.Now;
        public WAmphan()
        {
            G.cpFlag = "1";
            this.Size = new System.Drawing.Size(500, 160);
            this.ControlBox = false;
            this.AutoScroll = false;
            this.Font = new Font("Tahoma", 12, FontStyle.Regular);
            this.Text = "ระบบเปิด|ปิดไฟ";
            Panel pnlTop = new Panel() { Height = 4, Dock = DockStyle.Top, BackColor = Color.Gold };
            this.Controls.Add(pnlTop);
            Panel pnlRight = new Panel() { Width = 4, Dock = DockStyle.Right, BackColor = Color.Gold };
            this.Controls.Add(pnlRight);
            Panel pnlBottom = new Panel() { Height = 4, Dock = DockStyle.Bottom, BackColor = Color.Gold };
            this.Controls.Add(pnlBottom);
            Panel pnlLeft = new Panel() { Width = 4, Dock = DockStyle.Left, BackColor = Color.Gold };
            this.Controls.Add(pnlLeft);
            ctext1 = new Label();
            ctext1.Location = new Point(5, 40);
            ctext1.AutoSize = true;
            this.Controls.Add(ctext1);
            ctext2 = new Label();
            ctext2.Location = new Point(5, 65);
            ctext2.AutoSize = true;
            this.Controls.Add(ctext2);
            ctextF = new Label();
            ctextF.Location = new Point(5, 90);
            ctextF.AutoSize = true;
            this.Controls.Add(ctextF);
            ctextF.Text = G.cpCom+","+G.cFoldLink;
            if (G.cHistory == "1" || G.cHistory == "2") { ctextF.Text = ctextF.Text + " ,เก็บประวัติ"; }
            else { ctextF.Text = ctextF.Text + ",ไม่เก็บประวัติ"; }

            ctextF.Text = ctextF.Text + " (ไฟล์ตั้งค่า txt2com.ini)";
            ctext1.Text = "โปรแกรมกำลังทำงาน"; ctext2.Text = "สามารถตรวจสอบได้จาก History\\txt2com.html";

            bMinimize = new Button();
            bMinimize.Size = new Size(100, 30);
            bMinimize.Location = new Point(0, 5);
            bMinimize.Enabled = true;
            bMinimize.Text = "MINIMIZE";
            bMinimize.Font = new Font("Tahoma", 12, FontStyle.Bold);
            bMinimize.ForeColor = Color.Blue;
            this.Controls.Add(bMinimize);
            bMinimize.Click += new EventHandler(bMinimize_Click);

            bOpFle = new Button();
            bOpFle.Size = new Size(100, 30);
            bOpFle.Location = new Point(101, 5);
            bOpFle.Enabled = true;
            bOpFle.Text = "OPEN";
            bOpFle.Font = new Font("Tahoma", 12, FontStyle.Bold);
            bOpFle.ForeColor = Color.Blue;
            // bOpFle.Visible = false;
            this.Controls.Add(bOpFle);
            bOpFle.Click += new EventHandler(bOpFle_Click);

            bExit = new Button();
            bExit.Size = new Size(100, 30);
            bExit.Location = new Point(201+180, 5+80); // new Point(101, 5)
            bExit.Enabled = true;
            bExit.Text = "EXIT";
            bExit.Font = new Font("Tahoma", 12, FontStyle.Bold);
            bExit.ForeColor = Color.Blue;
            this.Controls.Add(bExit);
            bExit.Click += new EventHandler(bExit_Click);

            G.lInForm = true;
            Settimer();
        }

        private static void Settimer()
        {
            runTimer = new System.Timers.Timer(2 * 1000); // 5 วินาที
            runTimer.Elapsed += OnTimedEvent;
            runTimer.AutoReset = true;
            runTimer.Enabled = true;
        }

        private void bMinimize_Click(object sender, EventArgs e)
        {
              this.WindowState = FormWindowState.Minimized;
        }

        private void bOpFle_Click(object sender, EventArgs e) 
        {
            // หยุดเวลา 
            runTimer.Stop();
            runTimer.Enabled = false;
            string cOpenFile    = Program.MyFolderApp + @"\History\txt2com.html"; 
            Util.Program.OpenWebSite(cOpenFile);
            this.bOpFle.Visible = false;
            runTimer.Enabled = true;
            runTimer.Start();
        }

        private void bExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        // หยุดคอยเวลา
        static void uYodTimeWait(int ms)  
        {
            ms = ms * 1000;
            DateTime start = DateTime.Now;
            while ((DateTime.Now - start).TotalMilliseconds < ms)
                Application.DoEvents();
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            // หยุดเวลา 
            runTimer.Stop();
            runTimer.Enabled = false;
            if (!File.Exists(Program.fBackupTxt)) { Program.crfBackupTxt(); } // Bug มีการลบไฟล์
            DirectoryInfo driMach = new DirectoryInfo(G.cFoldLink);
            FileInfo[] File_txtmach = driMach.GetFiles("*.txt");
            string cFle4Dele = ""; // ชื่อไฟล์ที่จะลบ เผื่อไฟล์เปลี่ยน กรณีมากกว่า 10 รายการ
            foreach (FileInfo cfile in File_txtmach)
            {
                G.cpFileText = G.cFoldLink+"\\"+cfile.Name;
                cFle4Dele = cfile.FullName;
                switch (G.cpCompany)
                {
                    case ("5"): Program.Halls("K",G.cpFileText); break;
                    case ("6"): Program.Halls("H", G.cpFileText);  break;
                    case ("9"): Program.OtherCOM(G.cpFileText); break; // สำหรับกรณีพิเศษ จากบริษัทอื่นๆ
                    default:
                        G.nFileType = 0;  // กรณีที่ส่งมาเป็นข้อความ
                        Program.ChangeAndCutFile();
						if (G.lFullremark) { Program.saveRemark("========="); } // 
						if (G.nFileRun > 0) // มีการแบ่งไฟล์ ทีละ 10 ห้อง  
                        {
                            string cTempCard;
                            for (int i = 1; i <= G.nFileRun; i++)
                            {
                                cTempCard = Program.cTempWork + "_" + i.ToString().PadLeft(2, '0') + ".txt";
                                if (G.cpFlag == "0") { Util.Program.Pok_Mess("AmPhan " + i.ToString().Trim() + " --> " + cTempCard); }
                                // ส่ง 2 ครั้ง ด้วย 2400 และ 9600  
                                switch (G.cpAct4group) // ตรวจสอบวิธีไหนดีที่สุด  
                                {
                                    case ("1"):
                                        Program.AMP(cTempCard, 2, 1); Program.TM(1); Program.AMP(cTempCard, 2, 0); Program.TM(1);
                                        break;
                                    case ("2"):
                                        Program.AMP(cTempCard, 9, 1); Program.TM(1); Program.AMP(cTempCard, 9, 0); Program.TM(1);
                                        break;
                                    case ("3"):
                                        Program.AMP(cTempCard, 2, 1); Program.TM(1); Program.AMP(cTempCard, 9, 0); Program.TM(1); Program.AMP(cTempCard, 2, 0); Program.TM(1);
                                        break;
                                    case ("4"):
                                        Program.AMP(cTempCard, 9, 1); Program.TM(1); Program.AMP(cTempCard, 2, 0); Program.TM(1); Program.AMP(cTempCard, 9, 0); Program.TM(1);
                                        break;
                                    case ("5"):
                                        Program.AMP(cTempCard, 2, 1); Program.TM(1);
                                        break;
                                    case ("6"):
                                        Program.AMP(cTempCard, 9, 1); Program.TM(1);
                                        break;
                                    default:
                                        Program.AMP(cTempCard, 2, 1); Program.TM(1);
                                        Program.AMP(cTempCard, 9, 0); Program.TM(1);
                                        break;
                                }
                                Program.TM(2);
                            }
                        }
                        else
                        {
                            if (G.cpFlag == "0") { Util.Program.Pok_Mess("AmPhan 0 --> " + G.cpFileText); }
                            // ส่ง 2 ครั้ง ด้วย 2400 และ 9600   
                            switch (G.cpAct4single) // ตรวจสอบวิธีไหนดีที่สุด สำหรับอันเดียวหรือกลุ่มเล็ก  
                            {
                                case ("1"):
                                    Program.AMP(G.cpFileText, 2, 1); Program.AMP(G.cpFileText, 2, 0);
                                    break;
                                case ("2"):
                                    Program.AMP(G.cpFileText, 9, 1); Program.AMP(G.cpFileText, 9, 0);
                                    break;
                                case ("3"):
                                    Program.AMP(G.cpFileText, 2, 1); Program.AMP(G.cpFileText, 9, 0); Program.AMP(G.cpFileText, 2, 0);
                                    break;
                                case ("4"):
                                    Program.AMP(G.cpFileText, 9, 1); Program.AMP(G.cpFileText, 2, 0); Program.AMP(G.cpFileText, 9, 0);
                                    break;
                                case ("5"):
                                    Program.AMP(G.cpFileText, 2, 1);
                                    break;
                                case ("6"):
                                    Program.AMP(G.cpFileText, 9, 1);
                                    break;
                                default:
                                    Program.AMP(G.cpFileText, 2, 1); Program.AMP(G.cpFileText, 9, 0);
                                    break;
                            }
                        }
                        break;
                }
                 if (File.Exists("C:\\Windows\\Media\\Speech On.wav"))
                {
                    SoundPlayer POKSound = new SoundPlayer("C:\\Windows\\Media\\Speech On.wav");
                    POKSound.Play();
                }
                // ctext1.Text = ctext1.Text + " รออ่านไฟล์ต่อไป ";
                Program.TM(2);
                File.Delete(cFle4Dele);
            }
            // ทำงานต่อ  
            nCount++;
            if (G.cHistory=="2") { Util.Program.ReverseTextFile(Program.fBackupTxt, Program.fBackupTxtR,30); } // กลับไฟล์จะท้าย
            runTimer.Enabled = true;
            runTimer.Start();
            TimeSpan ts = (DateTime.Now - dStartDate);
        }
    }
    // End Window Form 



    // เริ่มโปรแกรมย่อย
    static class Program  
    {
        private static string myProgramn = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        private static string MyApp = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
        private static string cTemp = ""; 
        public static string cTempWork = "tCard";
        public static string MyProg = "txt2com".ToLower();
        private static int nTemp = 0;
        public static int nForWork = 1;
        public static string cFleWorkAct = "";  // ไว้ในในอนาคต ต่อไป 
        public static bool App4Console = false; // true ทำงานแบบ Console Application ,fause ทำงานแบบ Windows Application 
        public static string MyFolderApp = System.IO.Directory.GetCurrentDirectory();  // โพลเดอร์ทำงาน
        public static bool insource = false;
        public static bool inharddisk = false;
        public static string FldBackupTxt = MyFolderApp+"\\" ; // โพลเดอร์สำหรับเก็บประวัติ เปิด/ปิดไฟ 
        public static string fBackupTxt = FldBackupTxt + "History\\Open.txt";  // ไฟล์เก็บประวัติ เปิด/ปิดไฟ
        public static string fBackupTxtR = FldBackupTxt + "History\\OpenR.txt"; // ไฟล์เก็บประวัติ เปิด/ปิดไฟ แบบย้อนหลัง
        private static bool lDebug = false; // สำหรับ Debug ขณะรันโปรแกรม

        /// <summary>
        [STAThread]

        static void Readme() 
        {
            if (!File.Exists("txt2combat.bat"))
            {
                TextWriter WriteTxt1 = new StreamWriter("txt2combat.bat");
                WriteTxt1.WriteLine("Cls");
                WriteTxt1.WriteLine("Rem Sample");
                WriteTxt1.WriteLine("Rem txt2com 0 com? 2 :M0101");
                WriteTxt1.WriteLine("Rem txt2com 0 com? 2 test.txt");
                WriteTxt1.WriteLine("Rem Type Exit For Exit");
                WriteTxt1.WriteLine("Cmd");
                WriteTxt1.Close();
            }
            string Fle4Readme = MyFolderApp + "\\Readme.txt";
            TextWriter Logtxt = new StreamWriter(Fle4Readme);
            // การใช้งาน
            Logtxt.WriteLine("*" + MyProg + ".exe  ,DT : " + File.GetLastWriteTime(MyApp).ToString("dd/MM/yy HH:mm"));
            Logtxt.WriteLine(MyApp);
            Logtxt.WriteLine("ชุดคำสั่ง ");
            Logtxt.WriteLine("txt2com 0 COM? n FT ---> แสดงค่าด้วยและส่งตรงๆ ");
            Logtxt.WriteLine("txt2com 1 COM? n FT ---> ส่งตรงๆ ");
            Logtxt.WriteLine("txt2com L COM? n 0 ---> ส่งแบบวนลูปรับค่าtext ");
            Logtxt.WriteLine("txt2com C ---> เช็คการ์ด ");
            Logtxt.WriteLine("txt2com D ---> ลบไฟล์ช่วยงาน");
            Logtxt.WriteLine("txt2com S ---> ตั้งค่าการทำงาน");
            Logtxt.WriteLine("n= 1-6 ");
            Logtxt.WriteLine("FT = ไฟล์หรือข้อความ");
            Logtxt.WriteLine("");
            Logtxt.WriteLine("เน้นพิเสษ");
            Logtxt.WriteLine("txt2com 1 com1 2 :M01011 สำหรับอำพัน");
            Logtxt.WriteLine("txt2com 1 com1 6 :M01011 สำหรับ Halls");
            Logtxt.WriteLine("txt2com L com? n 0-- > วนลูป รับค่าไฟล์ข้อความ");
            Logtxt.WriteLine("txt2com C -- Check Com Port");
            Logtxt.WriteLine("com1               เปลี่ยนCom ตามต้องการ");
            Logtxt.WriteLine("2                     2=อำพัน 6=Halls 9=อื่นๆ เทียบกับ room4code.txt");
            Logtxt.WriteLine("0                     0 - 6 ไว้ทดลองกรณีต่างๆ");
			Logtxt.WriteLine(""); Logtxt.WriteLine("");
            Logtxt.WriteLine(MyProg+".debug สำหรับ Debug โปรแกรม");
			Logtxt.WriteLine(MyProg+".textbug เน้นคำสำหรับการค้นหา");
			Logtxt.WriteLine(""); Logtxt.WriteLine("");

            string[] readText;   
            cTemp = "txt2com.ini";
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("txt2com.ini ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp+"  สำหรับตั้งค่าการทำงาน เน้นใช้กับ txt2com L");
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim());}}
                Logtxt.WriteLine("");
                Logtxt.WriteLine("***ใช้สำหรับทั่วไป");
                Logtxt.WriteLine("บรรทัดที่ 2 เปลี่ยนค่าเป็น 0-2 เพื่อเก็บประวัติ");
                Logtxt.WriteLine("บรรทัดที่ 6 เปลี่ยนค่าเป็น 0-6 เพื่อทดลองส่งไฟที่เหมาะสม ชุดใหญ่");
                Logtxt.WriteLine("บรรทัดที่ 7 เปลี่ยนค่าเป็น 0-6 เพื่อทดลองส่งไฟที่เหมาะสม ชุดเล็ก");
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }

            cTemp = fBackupTxt;
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine(fBackupTxt+" ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp);
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                
            } else {Logtxt.WriteLine(cTemp+"  สำหรับเก็บประวัติการทำงาน");}

            Logtxt.WriteLine(""); Logtxt.WriteLine("");
            Logtxt.WriteLine(fBackupTxtR+ "  สำหรับเก็บประวัติการทำงานจากท้าย****");
            Logtxt.WriteLine(""); Logtxt.WriteLine("");

            cTemp="txt2com.set";   
            if (File.Exists(cTemp))
            {
                Logtxt.WriteLine("txt2com.set ,DT:" + File.GetLastWriteTime(cTemp).ToString("dd/MM/yy HH:mm"));
                Logtxt.WriteLine(cTemp+"  หา Com อัตโนมัติ");
                readText = File.ReadAllLines(cTemp);
                foreach (string s in readText) { if (s != "") { Logtxt.WriteLine(s.Trim()); } }
                Logtxt.WriteLine(""); Logtxt.WriteLine("");
            }


            Logtxt.Close(); Logtxt.Dispose();
            if (Layout.Program.Password.Input_Password("Open Readme.txt",""))
            { 
				Util.Program.OpenWebSite(Fle4Readme);    // Pipop
				Fle4Readme = MyFolderApp + "\\History\\txt2com.html"; 
				if (File.Exists(Fle4Readme)) {Util.Program.OpenWebSite(Fle4Readme);} // Pipop
				Util.Program.OpenWebSite("uyod.net/pdf/txt2com.pdf"); 
			}
        }


        public static void AMP(string cTxtFile, int nRate,int nOption) // สำหรับระบบ อำพันได้ 
        {
            // nOption มีผลในการ SAVE
            string p = "AMP";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            try
            {
                if (lDebug) { Special.DEBUG.D(p, " - 02 -"+ G.cpCom); }
                SerialPort dPort = new SerialPort();  
                dPort.PortName = G.cpCom;
                switch (nRate)
                {
                    case (2): dPort.BaudRate = 2400; break;
                    default: dPort.BaudRate = 9600; break;  
                }
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้
                if (!inharddisk) {
                    if (lDebug) { Special.DEBUG.D(p, " - 03"); }
                    dPort.Open();
                    using (FileStream fileStream = new FileStream(cTxtFile, FileMode.Open, FileAccess.Read, FileShare.Read))  // Pipop-Am
                    {
                        BinaryReader binary = new BinaryReader(fileStream, Encoding.GetEncoding(28591));
                        dPort.Write(binary.ReadBytes((int)fileStream.Length), 0, (int)fileStream.Length);
                    }
                    dPort.Close(); dPort.Dispose();
                    if (lDebug) { Special.DEBUG.D(p, " - 04"); }
                } // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้
                if (G.cpFlag == "0")
                {
                    Util.Program.Pok_Mess("ส่ง " + cTxtFile + " แบบที่ " + G.cpCompany + " -ไปที่ " + G.cpCom + " สำเร็จ" + " ->" + dPort.BaudRate.ToString());
                }
                if (nOption==1 && (G.cHistory == "1" || G.cHistory == "2")) { SaveHistory(1, cTxtFile); }  
            }
            catch
            { ErrorInCOM(); }
            if (lDebug) { Special.DEBUG.D(p, " - 05-FINNISH"); }
        }


        private static bool HallsTran(string txt,ref int n1, ref int n2, ref int n3, ref int n4, ref int n5, ref int n6, ref int n7, ref int n8)
        {
            string p= "HallsTran";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            bool lFlag = true;
            switch (txt)
            {
                case ("01011"): n1 = 1; n2 = 6; n3 = 0; n4 = 1; n5 = 1; n6 = 0; n7 = 217; n8 = 154;  break;
                case ("01010"): n1 = 1; n2 = 6; n3 = 0; n4 = 1; n5 = 2; n6 = 0; n7 = 217; n8 = 106; break;
                case ("01021"): n1 = 1; n2 = 6; n3 = 0; n4 = 2; n5 = 1; n6 = 0; n7 = 41; n8 = 154; break;
                case ("01020"): n1 = 1; n2 = 6; n3 = 0; n4 = 2; n5 = 2; n6 = 0; n7 = 41; n8 = 106; break;
                case ("01031"): n1 = 1; n2 = 6; n3 = 0; n4 = 3; n5 = 1; n6 = 0; n7 = 120; n8 = 90; break;
                case ("01030"): n1 = 1; n2 = 6; n3 = 0; n4 = 3; n5 = 2; n6 = 0; n7 = 120; n8 = 170; break;
                case ("01041"): n1 = 1; n2 = 6; n3 = 0; n4 = 4; n5 = 1; n6 = 0; n7 = 201; n8 = 155; break;
                case ("01040"): n1 = 1; n2 = 6; n3 = 0; n4 = 4; n5 = 2; n6 = 0; n7 = 201; n8 = 107; break;
                case ("01051"): n1 = 1; n2 = 6; n3 = 0; n4 = 5; n5 = 1; n6 = 0; n7 = 152; n8 = 91; break;
                case ("01050"): n1 = 1; n2 = 6; n3 = 0; n4 = 5; n5 = 2; n6 = 0; n7 = 152; n8 = 171; break;
                case ("01061"): n1 = 1; n2 = 6; n3 = 0; n4 = 6; n5 = 1; n6 = 0; n7 = 104; n8 = 91; break;
                case ("01060"): n1 = 1; n2 = 6; n3 = 0; n4 = 6; n5 = 2; n6 = 0; n7 = 104; n8 = 171; break;
                case ("01071"): n1 = 1; n2 = 6; n3 = 0; n4 = 7; n5 = 1; n6 = 0; n7 = 57; n8 = 155; break;
                case ("01070"): n1 = 1; n2 = 6; n3 = 0; n4 = 7; n5 = 2; n6 = 0; n7 = 57; n8 = 107; break;
                case ("01081"): n1 = 1; n2 = 6; n3 = 0; n4 = 8; n5 = 1; n6 = 0; n7 = 9; n8 = 152; break;
                case ("01080"): n1 = 1; n2 = 6; n3 = 0; n4 = 8; n5 = 2; n6 = 0; n7 = 9; n8 = 104; break;

                case ("02011"): n1 = 2; n2 = 6; n3 = 0; n4 = 1; n5 = 1; n6 = 0; n7 = 217; n8 = 169; break;
                case ("02010"): n1 = 2; n2 = 6; n3 = 0; n4 = 1; n5 = 2; n6 = 0; n7 = 217; n8 = 89; break;
                case ("02021"): n1 = 2; n2 = 6; n3 = 0; n4 = 2; n5 = 1; n6 = 0; n7 = 41; n8 = 169; break;
                case ("02020"): n1 = 2; n2 = 6; n3 = 0; n4 = 2; n5 = 2; n6 = 0; n7 = 41; n8 = 89; break;
                case ("02031"): n1 = 2; n2 = 6; n3 = 0; n4 = 3; n5 = 1; n6 = 0; n7 = 120; n8 = 105; break;
                case ("02030"): n1 = 2; n2 = 6; n3 = 0; n4 = 3; n5 = 2; n6 = 0; n7 = 120; n8 = 153; break;
                case ("02041"): n1 = 2; n2 = 6; n3 = 0; n4 = 4; n5 = 1; n6 = 0; n7 = 201; n8 = 168; break;
                case ("02040"): n1 = 2; n2 = 6; n3 = 0; n4 = 4; n5 = 2; n6 = 0; n7 = 201; n8 = 88; break;
                case ("02051"): n1 = 2; n2 = 6; n3 = 0; n4 = 5; n5 = 1; n6 = 0; n7 = 152; n8 = 104; break;
                case ("02050"): n1 = 2; n2 = 6; n3 = 0; n4 = 5; n5 = 2; n6 = 0; n7 = 152; n8 = 152; break;
                case ("02061"): n1 = 2; n2 = 6; n3 = 0; n4 = 6; n5 = 1; n6 = 0; n7 = 104; n8 = 104; break;
                case ("02060"): n1 = 2; n2 = 6; n3 = 0; n4 = 6; n5 = 2; n6 = 0; n7 = 104; n8 = 152; break;
                case ("02071"): n1 = 2; n2 = 6; n3 = 0; n4 = 7; n5 = 1; n6 = 0; n7 = 57; n8 = 168; break;
                case ("02070"): n1 = 2; n2 = 6; n3 = 0; n4 = 7; n5 = 2; n6 = 0; n7 = 57; n8 = 88; break;
                case ("02081"): n1 = 2; n2 = 6; n3 = 0; n4 = 8; n5 = 1; n6 = 0; n7 = 9; n8 = 171; break;
                case ("02080"): n1 = 2; n2 = 6; n3 = 0; n4 = 8; n5 = 2; n6 = 0; n7 = 9; n8 = 91; break;
                default: lFlag = false; break;
            }
            if (lDebug) { Special.DEBUG.D(p, " - 02-FINNISH"); }
            return lFlag;
        }


        public static void Halls(string cWHO, string cTxtorFile)  // สำหรับกิ๊บและฮอล Halls
        {
            string p = "Halls";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            int oldFileType = G.nFileType;
            if (G.nFileType == 0) { HallsOpen(cWHO, cTxtorFile); }
            else 
            { // มาในรูปแบบ *.txt ให้ส่งทีละบรรทัด
                G.nFileType = 0; // สำหรับ ข้อความ
                string[] lines = File.ReadAllLines(cTxtorFile);
                foreach (string linein in lines) {HallsOpen(cWHO, linein.Trim()); }
            }
            if (lDebug) { Special.DEBUG.D(p, " - 02"); }
            if (G.cpFlag == "0")  
            { Util.Program.Pok_Mess("ส่ง " + cTxtorFile + " แบบที่ " + G.cpCompany + " -ไปที่ " + G.cpCom + " สำเร็จ"); }
            G.nFileType = oldFileType;
            if (G.cHistory == "1" || G.cHistory == "2") { SaveHistory(1, cTxtorFile); }
            if (lDebug) { Special.DEBUG.D(p, " - 03-FINNISH"); }
        }


        public static void HallsOpen(string cProg,string cTxtFile)  
        {
            string p = "HallsOpen";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            int nCol1, nCol2, nCol3, nCol4, nCol5, nCol6, nCol7, nCol8;
            if (lDebug) { Special.DEBUG.D(p, " - 02"); }
            if (cProg == "H") // สำหรับระบบของ Halls
            {
                if (G.nFileType != 0) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 5 หลักเท่านั้น"); return; }
                if (cTxtFile.Length == 0) { return; }
                if (cTxtFile.Length != 5) { Util.Program.Pok_Mess(cTxtFile+" รับได้เฉพาะตัวเลข 5 หลักเท่านั้น"); return; }
                nCol1 = 0; nCol2 = 0; nCol3 = 0; nCol4 = 0;
                nCol5 = 0; nCol6 = 0; nCol7 = 0; nCol8 = 0;
                if (!HallsTran(cTxtFile, ref nCol1, ref nCol2, ref nCol3, ref nCol4, ref nCol5, ref nCol6, ref nCol7, ref nCol8)) // แปลงเป็นชุดคำสั่ง
                { Util.Program.Pok_Mess(cTxtFile+" ตัวแปรไม่เข้าระบบ จะไม่ทำงาน"); return; }
                if (G.cpFlag == "0" && insource)
                {
                    Util.Program.Pok_Mess("cTxtFile = "+cTxtFile + System.Environment.NewLine + System.Environment.NewLine
                      + "nCol1 = " + nCol1.ToString() + System.Environment.NewLine
                      + "nCol2 = " + nCol2.ToString() + System.Environment.NewLine
                      + "nCol3 = " + nCol3.ToString() + System.Environment.NewLine
                      + "nCol4 = " + nCol4.ToString() + System.Environment.NewLine
                      + "nCol5 = " + nCol5.ToString() + System.Environment.NewLine
                      + "nCol6 = " + nCol6.ToString() + System.Environment.NewLine
                      + "nCol7 = " + nCol7.ToString() + System.Environment.NewLine  
                      + "nCol8 = " + nCol8.ToString() + System.Environment.NewLine);
                }
            }
            else // ระบบทั่วไปส่งมา 8 หลัก กิ๊บ
            {
                if (G.nFileType != 0) { Util.Program.Pok_Mess("รับได้เฉพาะตัวเลข 8 หลักเท่านั้น"); return; }
                if (cTxtFile.Length == 0) { return; }
                if (cTxtFile.Length != 8) { Util.Program.Pok_Mess(cTxtFile+" รับได้เฉพาะตัวเลข 8 หลักเท่านั้น"); return; }
                nCol1 = int.Parse(G.cpFileText.Substring(0, 1));
                nCol2 = int.Parse(G.cpFileText.Substring(1, 1));
                nCol3 = int.Parse(G.cpFileText.Substring(2, 1));
                nCol4 = int.Parse(G.cpFileText.Substring(3, 1));
                nCol5 = int.Parse(G.cpFileText.Substring(4, 1));
                nCol6 = int.Parse(G.cpFileText.Substring(5, 1));
                nCol7 = int.Parse(G.cpFileText.Substring(6, 1));
                nCol8 = int.Parse(G.cpFileText.Substring(7, 1));
            }
            if (lDebug) { Special.DEBUG.D(p, " - 03"); }
            try
            {   // เริ่มทำการส่งไป Com Port:
                SerialPort dPort = new SerialPort();
                dPort.PortName = G.cpCom;
                dPort.BaudRate = 9600;
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้   
                if (!inharddisk) {
                    dPort.Open();
                    byte[] WordText = new byte[8] {
                    (byte) nCol1,(byte) nCol2,(byte) nCol3,(byte) nCol4,
                    (byte) nCol5,(byte) nCol6,(byte) nCol7,(byte) nCol8};
                    dPort.Write(WordText, 0, WordText.Length);
                }
                // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้   
                dPort.Close(); dPort.Dispose(); 
            }
            catch { ErrorInCOM();  }
            if (lDebug) { Special.DEBUG.D(p, " - 04 -FINNISH"); }
        }

        // เปลี่ยนเลขห้องเป็นโค้ด 
        static string Tran4OtherCOM(string cCode1)  // OtherCOM-3
        {
            cCode1 =cCode1.Trim();
            string p = "Tran4OtherCOM";
            string cCode2="", linetext;
            if (lDebug) { Special.DEBUG.D(p, " - 00-"+cCode1);}
            if (!File.Exists("room4code.txt")) {
                if (lDebug) { Special.DEBUG.D(p, " - 01"); }
                TextWriter tRm4Code;
                tRm4Code = new StreamWriter("room4code.txt");
                tRm4Code.WriteLine("01010,:M01010");
                tRm4Code.WriteLine("01011,:M01011");
                tRm4Code.Close(); tRm4Code.Dispose();
                Util.Program.Pok_Mess("ข้อมูลและการ์ด" + Environment.NewLine + Environment.NewLine + "เพิ่มเติมที่ไฟล์  room4code.txt");
            }
            string[] Lines = File.ReadAllLines("room4code.txt");
            if (lDebug) { Special.DEBUG.D(p, " - 02 -room4code.txt"); }
            foreach (string line in Lines)
            { 
                linetext = line.Trim();
                nTemp = linetext.IndexOf(",");
                if (nTemp!=0)
                { if (linetext.Substring(0, nTemp)==cCode1)  { cCode2 = linetext.Substring(nTemp + 1); break;  }  }
            }
            if (cCode2=="") { Util.Program.Pok_Mess("ไม่พบข้อมูล "+cCode1+Environment.NewLine + Environment.NewLine + "เพิ่มเติมที่ไฟล์  room4code.txt"); }
            if (lDebug) { Special.DEBUG.D(p, " - 03-"+cCode2+" -FINNISH"); }
            return cCode2;
        }


        public static void OtherCOM(string cTxtorFile) // OtherCOM-2
        {
            string p = "OtherCOM";
            if (lDebug) { Special.DEBUG.D(p, " - 00"); }
            int oldFileType = G.nFileType;
            string ctxtOther; TextWriter tFleCard;
            if (G.nFileType == 0) { // ข้อมูลห้องเดียว นำใส่ Text File
                ctxtOther = cTempWork + ".txt";
                if (lDebug) { Special.DEBUG.D(p, " - 01"); }
                tFleCard = new StreamWriter(ctxtOther);
                tFleCard.WriteLine(Tran4OtherCOM(cTxtorFile));  // OtherCOM-31 นำค่ามาใส่ txt
                tFleCard.Close(); tFleCard.Dispose();
            } else { // ข้อมูลมาเป็นกลุ่ม
                ctxtOther = cTempWork + ".txt";
                if (lDebug) { Special.DEBUG.D(p, " - 02"); }
                tFleCard = new StreamWriter(ctxtOther);
                string[] txtLines = File.ReadAllLines(cTxtorFile);
                foreach (string txtLine in txtLines)
                {  cTemp = Tran4OtherCOM(txtLine);
                    if (cTemp != "") { tFleCard.WriteLine(cTemp); }
                }
                tFleCard.Close(); tFleCard.Dispose();
            }
            try
            {
                if (lDebug) { Special.DEBUG.D(p, " - 03"); }
                SerialPort dPort = new SerialPort();  // OtherCOM-4
                dPort.PortName = G.cpCom;
                dPort.BaudRate = 9600; 
                dPort.Parity = Parity.None;
                dPort.DataBits = 8;
                dPort.StopBits = StopBits.One;
                // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้
                if (!inharddisk)  
                {
                    if (lDebug) { Special.DEBUG.D(p, " - 040 - " + ctxtOther); }
                    dPort.Open(); // ส่งครั้งที่ 1 
                    using (FileStream fileStream = new FileStream(ctxtOther, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader binary = new BinaryReader(fileStream, Encoding.GetEncoding(28591)); // Pipop-Other
                        dPort.Write(binary.ReadBytes((int)fileStream.Length), 0, (int)fileStream.Length);
                    }
                    dPort.Close(); dPort.Dispose();
                    if (lDebug) { Special.DEBUG.D(p, " - 041 - "+ctxtOther); }
                    MyTime.Program.Pok_TimeWait(1, 1);  // OtherCOM-44

                    dPort.Open(); // ส่งครั้งที่ 2 
                    dPort.BaudRate = 2400;
                    using (FileStream fileStream = new FileStream(ctxtOther, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader binary = new BinaryReader(fileStream, Encoding.GetEncoding(28591));
                        dPort.Write(binary.ReadBytes((int)fileStream.Length), 0, (int)fileStream.Length);
                    }
                    dPort.Close(); dPort.Dispose();
                    if (lDebug) { Special.DEBUG.D(p, " - 051 - " + ctxtOther); }
                } // ไว้ทดสอบบนฮาร์ดดิสก์ตัวเอง  สามารถเอาออกได้
                if (G.cpFlag == "0")
                {
                    Util.Program.Pok_Mess("ส่ง " + cTxtorFile + " แบบที่ " + G.cpCompany + " -ไปที่ " + G.cpCom + " สำเร็จ" + " ->" + dPort.BaudRate.ToString());
                }
                if (G.cHistory == "1" || G.cHistory == "2") { SaveHistory(1,ctxtOther); }
            }
            catch { ErrorInCOM(); }
            if (lDebug) {Special.DEBUG.D(p, " - 06 -FINNISH"); }
        }


        static void ErrorInCOM()
        {   SaveHistory(-1, "ส่งแบบที่ " + G.cpCompany + " -ไม่พบ " + G.cpCom);
            if (G.lInForm)
            { MessageBox.Show("พบปัญหา "+G.cpCom, "",
              MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
              Application.Exit();  }
            else
            {  var nYesno = MessageBox.Show("ส่งแบบที่ " + G.cpCompany + " -ไม่พบ " + G.cpCom
                + System.Environment.NewLine + "กด Yes หา COM ใหม่ที่ใช้ได้", "",
                MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
                if (nYesno == DialogResult.Yes) { CheckComPort(); }
            }
        }

        static void Send_FileTxt()   
        {
            string p = "Send_FileTxt";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            switch (G.cpCompany) {
            case ("5"):
                    if (lDebug) { Special.DEBUG.D(p, " - 21 -"+ G.cpFileText); }
                    Halls("K",G.cpFileText);  // KIP
                    break;
            case ("6"):
                    if (lDebug) { Special.DEBUG.D(p, " - 22 -"+ G.cpFileText); }
                    Halls("H",G.cpFileText); // Halls
                    break;
            case ("9"): // สำหรับกรณีพิเศษ จากบริษัทอื่นๆ OtherCOM-1
                    if (lDebug) { Special.DEBUG.D(p, " - 23 -"+ G.cpFileText); }
                    OtherCOM(G.cpFileText);
                    break;
            default:
                    // Copy ให้เหมือน G.cpFlag == "L"
					if (G.lFullremark) { saveRemark("========="); }
                    if (lDebug) { Special.DEBUG.D(p, " - 31"); }
                    if (G.nFileRun>0) // มีการแบ่งไฟล์ ทีละ 10 ห้อง  
                    {
                        if (lDebug) { Special.DEBUG.D(p, " - 32"); }
                        if (G.cpFlag != "L") { Layout.Program.LayOut.BackGroud(6); }  
                        string cTempCard;
                        for (int i = 1; i <= G.nFileRun ; i++)
                        {
                            cTempCard = cTempWork +"_"+ i.ToString().PadLeft(2, '0') + ".txt";
                            if (G.cpFlag == "0") { Util.Program.Pok_Mess("AmPhan " + i.ToString().Trim() + " --> " + cTempCard); }
                            // ส่ง 2 ครั้ง ด้วย 2400 และ 9600  
                            if (lDebug) { Special.DEBUG.D(p, " - 33 -"+ cTempCard); }
                            switch (G.cpAct4group) // ตรวจสอบวิธีไหนดีที่สุด สำหรับกลุ่ม  
                            {
                                case ("1"):
                                    AMP(cTempCard, 2,1); TM(1); AMP(cTempCard, 2, 0); TM(1);
                                    break;
                                case ("2"):
                                    AMP(cTempCard, 9, 1); TM(1); AMP(cTempCard, 9, 0); TM(1);
                                    break;
                                case ("3"):
                                    AMP(cTempCard, 2, 1); TM(1); AMP(cTempCard, 9, 0); TM(1); AMP(cTempCard, 2, 0); TM(1);
                                    break;
                                case ("4"):
                                    AMP(cTempCard, 9, 1); TM(1); AMP(cTempCard, 2, 0); TM(1); AMP(cTempCard, 9, 0); TM(1);
                                    break;
                                case ("5"):
                                    AMP(cTempCard, 2, 1); TM(1);
                                    break;
                                case ("6"):
                                    AMP(cTempCard, 9, 1); TM(1);
                                    break;
                                default:
                                    AMP(cTempCard, 2,1); TM(1);
                                    AMP(cTempCard, 9,0); TM(1);
                                    break;
                            }
                            if (lDebug) { Special.DEBUG.D(p, " - 34"); }
                            TM(2);
                        }
                    }
                    else
                    {
                        if (lDebug) { Special.DEBUG.D(p, " - 35"); }
                        if (G.cpFlag == "0") { Util.Program.Pok_Mess("AmPhan 0 --> " + G.cpFileText); }
                        if (lDebug) { Special.DEBUG.D(p, " - 36 -"+ G.cpFileText); }
                        // ส่ง 2 ครั้ง ด้วย 2400 และ 9600  
                        switch (G.cpAct4single) // ตรวจสอบวิธีไหนดีที่สุด สำหรับอันเดียวหรือกลุ่มเล็ก  
                        {
                            case ("1"):
                                AMP(G.cpFileText, 2, 1); AMP(G.cpFileText, 2, 0); 
                                break;
                            case ("2"):
                                AMP(G.cpFileText, 9, 1); AMP(G.cpFileText, 9, 0); 
                                break;
                            case ("3"):
                                AMP(G.cpFileText, 2, 1);  AMP(G.cpFileText, 9, 0);  AMP(G.cpFileText, 2, 0); 
                                break;
                            case ("4"):
                                AMP(G.cpFileText, 9, 1); AMP(G.cpFileText, 2, 0); AMP(G.cpFileText, 9, 0); 
                                break;
                            case ("5"):
                                AMP(G.cpFileText, 2, 1); 
                                break;
                            case ("6"):
                                AMP(G.cpFileText, 9, 1); 
                                break;
                            default:
                                AMP(G.cpFileText, 2, 1); AMP(G.cpFileText, 9, 0);
                                break;
                        }
                        if (lDebug) { Special.DEBUG.D(p, " - 37"); }
                    }
                    break;
            }
            if (lDebug) { Special.DEBUG.D(p, " - 4 -FINNISH"); }
        }

        public static void TM(int ms) // ms=60 คือ 1 นาที
        {  Thread.Sleep(ms * 1000);   }

        public static void saveRemark(string txtremark)  
        {
            string p = "saveRemark";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            if (G.cHistory=="0") { return; }
            if (lDebug) { Special.DEBUG.D(p, " - 02 -"+ fBackupTxt); }
            using (StreamWriter Write2Txt2 = File.AppendText(fBackupTxt))
            { Write2Txt2.WriteLine(txtremark); Write2Txt2.Close(); }
            if (lDebug) { Special.DEBUG.D(p, " - 01 -FINNISH"); }
        }

     
        static void SaveHistory(int nHistory,string txtBackup)   
        {
            string p = "SaveHistory";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            if (nHistory == -1) { txtBackup = "*Error "+txtBackup;  } // มี Error เกิดขึ้น  
            using (StreamWriter Write2Txt2 = File.AppendText(fBackupTxt))
            {
                if (G.lFullremark) {
                    cTemp = Environment.NewLine + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                    if (G.nFileType == 0) { cTemp = cTemp + " ==> Code:" + txtBackup; }
                    else { cTemp = cTemp + " ==> File:" + txtBackup; }

                    cTemp = cTemp + " ,Flag:" + G.cpFlag;
                    cTemp = cTemp + " ,Com:" + G.cpCom;
                    cTemp = cTemp + " ,Company:" + G.cpCompany;
                    cTemp = cTemp + " ,G.nFileRun:" + G.nFileRun;
                    if (G.nFileRun > 0) // มีการแบ่งไฟล์ ทีละ 10 ห้อง  
                    { cTemp = cTemp + " ,G.cpAct4group:" + G.cpAct4group; }
                    else { cTemp = cTemp + " ,G.cpAct4single:" + G.cpAct4single; }
                    Write2Txt2.WriteLine(cTemp);
                }
                else {cTemp= DateTime.Now.ToString("HH:mm:ss")+" -> "; Write2Txt2.Write(cTemp); }  // เขียนเวลาก่อน
                if (lDebug) { Special.DEBUG.D(p, " - 02 -"+ txtBackup); }
                if (File.Exists(txtBackup)) 
                {
                    string[] roomText = File.ReadAllLines(@"History/card.TXT");
                    string[] readText = File.ReadAllLines(txtBackup); 
                    cTemp = ""; nTemp = 0;
                    foreach (string s in readText) { 
                        if (s != "")
                        {
                            switch (s.Substring(0,2))
                            {
                                case (":M"): cTemp = cTemp + "," + s.Substring(2, 4) + "@" + s.Substring(6) +SearchRoom(roomText, s.Substring(2, 4)) +  "  "; break;  
                                default: cTemp = cTemp + "," + s.Substring(0, 4) + "@" + s.Substring(4) + SearchRoom(roomText, s.Substring(0, 4)) + "  "; break; 
                            }
                            nTemp++;
                            if (nTemp>=10) { if (G.lFullremark) { Write2Txt2.WriteLine(cTemp.Substring(1)); } else { Write2Txt2.Write(cTemp.Substring(1)+" "); } nTemp = 0; cTemp = ""; }
                         }
                       }
                    if (nTemp>0 && nTemp<10) { if (G.lFullremark) { Write2Txt2.WriteLine(cTemp.Substring(1)); } else { Write2Txt2.Write(cTemp.Substring(1)+" "); }      }
                    nTemp = 0; cTemp = ""; 
                }
                nTemp = 0; cTemp = "";
                if (!G.lFullremark) { Write2Txt2.WriteLine(""); }
                Write2Txt2.Close(); }
            if (lDebug) { Special.DEBUG.D(p, " - 03 -FINNISH"); }
        }

        // หาห้องคู่กับ Relay  
        static String SearchRoom(Array arrayroom ,string cRelay)
        {
            string myRoom = "";
            foreach (string s in arrayroom)
            { if (s != "") { if (s.Substring(0, 4) == cRelay) { myRoom = " [" + s.Substring(10).Trim() + "]"; break; } } }
            return myRoom;
        }


        static void Cr_TextFile(string card_num)
        {
            card_num = card_num.Trim().ToLower(); 
            if (File.Exists("card" + card_num + "_0.txt")) { return; }
            TextWriter tFleCard_0 = new StreamWriter("card" + card_num + "_0.txt");
            TextWriter tFleCard_1 = new StreamWriter("card" + card_num + "_1.txt");
            string cTxt;
            for (int j = 1; j >= 0; j--)
            {
                for (int i = 1; i <= 16; i++)
                {
                    cTxt = ":M" + card_num + i.ToString().Trim().PadLeft(2, '0') + j.ToString().Trim();
                    if (j == 0) { tFleCard_0.WriteLine(cTxt); }
                    else { tFleCard_1.WriteLine(cTxt); }
                }
            }
            tFleCard_0.Close();
            tFleCard_1.Close();
        }

        static void Cr_AllTextFile() // สร้างไฟล์ card??.txt
        {
            // สร้างทีละ การ์ด   
            Cr_TextFile("01"); Cr_TextFile("02"); Cr_TextFile("03"); Cr_TextFile("04"); Cr_TextFile("05");
            Cr_TextFile("06"); Cr_TextFile("07"); Cr_TextFile("08"); Cr_TextFile("09"); Cr_TextFile("10");

            // สร้างรวม 3 การ์ด 
            if (!File.Exists("cardALL_1.txt"))
            {
                string card_num = "ALL";
                TextWriter tFleCard_0 = new StreamWriter("card" + card_num + "_0.txt");
                TextWriter tFleCard_1 = new StreamWriter("card" + card_num + "_1.txt");
                string cTxt = "";
                for (int j = 1; j <= 3; j++)
                {
                    for (int i = 1; i <= 16; i++)
                    {
                        for (int k = 0; k <= 1; k++)
                        {
                            cTxt = ":M" + j.ToString().Trim().PadLeft(2, '0') + i.ToString().Trim().PadLeft(2, '0') + k.ToString().Trim();
                            if (k == 0) { tFleCard_0.WriteLine(cTxt); }
                            else { tFleCard_1.WriteLine(cTxt); }
                        }
                    }
                }
                tFleCard_0.Close();
                tFleCard_1.Close();
            }
        }


        static void ConvertText2File() // แปลง Text เป็น ไฟล์ 
        {
            // กรณีส่งมาเป็น ข้อความ จะสร้างไฟล์มารับ
            // กรณีมาเป็นไฟล์ จะCopy ทั้งไฟล์ไป
            if (ThisIsText(G.cpFileText)==1) { return; }
            string cCard = cTempWork +"00.txt"; 
            if (File.Exists(cCard)) { File.Delete(cCard); }
            TextWriter tFleCard = new StreamWriter(cCard);
            if (G.cpFileText.Contains(",")) 
            {
                string[] cutword = G.cpFileText.Split(',');  // ตัดข้อความ
                for (int i=0; i<cutword.Length; i++)
                { tFleCard.WriteLine(cutword[i]); }
            }
            else { tFleCard.WriteLine(G.cpFileText); }  
            tFleCard.Close();
            G.cpFileText=cCard;  // เปลี่ยนเป็นไฟล์Run
            G.nFileType = 1; // เปลี่ยนค่าเป็นไฟล์ 
        }

        static int ThisIsText(string cFile) // ตรวจสอบไฟล์ Text
        {
            int isText =0;  // .txt
            string chkFile = cFile.ToLower().Trim();
            if (chkFile.Substring(chkFile.Length - 4) == ".txt")
            { if (File.Exists(chkFile)) { isText = 1; } else { isText = 2; } }
            return isText;
        }


        static void CheckComPort()
        {
            string p = "CheckComPort";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            TextWriter WriteTxt1 = new StreamWriter("txt2com.set");  
            string cComport;
            if (lDebug) { Special.DEBUG.D(p, " - 02"); }
            for (int i = 1; i <= 16; i++)
            {
                cComport = "COM" + i.ToString().Trim();
                try
                {
                    SerialPort cTestPort = new SerialPort();
                    cTestPort.PortName = cComport;
                    cTestPort.Open();
                    cTestPort.WriteLine(":M01011");
                    WriteTxt1.WriteLine(cComport);
                    cTestPort.Close(); cTestPort.Dispose();
                    G.cpCom = cComport;
                    Util.Program.Pok_Mess(cComport + " ใช้งานตามปรกติ");
                }
                catch
                {     }
            }
            WriteTxt1.Close();
            if (lDebug) { Special.DEBUG.D(p, " - 03 -FINNISH"); }
        }


        // สำหรับอ่าน คอมพอร์ต เป็น Textfile 
        static void ReadComPort2Text() {Util.Program.Pok_Mess("ยังไม่พัฒนา");    }

        
        static void Init()
        {
            string p = "Init";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            if (File.Exists("txt2com4remark.hav")) {G.lFullremark = true; } // แสดงแบบเต็ม  
            if (!Directory.Exists("\\Temp")) { Directory.CreateDirectory("\\Temp"); } 
            if (!Directory.Exists("History")) { Directory.CreateDirectory("History"); } 
            if (!File.Exists("txt2com.ini"))
            {
                if (lDebug) { Special.DEBUG.D(p, " - 02"); }
                TextWriter WriteTxt1 = new StreamWriter("txt2com.ini");
                WriteTxt1.WriteLine("Ho2Mach        โพลเดอร์ที่เก็บเท็กซ์ไฟล์ จากโปรแกรมโรงแรม");
                WriteTxt1.WriteLine("0                     เก็บประวัติข้อมูลเปิดปิดไฟ 0=ไม่เก็บ 1=เก็บ 2=เก็บประวัติแบบล่าสุดด้วย");
                WriteTxt1.WriteLine("");
                WriteTxt1.WriteLine("สำหรับรัน ไฟล์ตรงๆ txt2com");
                WriteTxt1.WriteLine("com1               เปลี่ยนCom ตามต้องการ");
                WriteTxt1.WriteLine("2                     2=อำพัน 6=Halls 9=อื่นๆ room4code.txt ");
                WriteTxt1.WriteLine("4                     0-6 ไว้ทดลองกรณีต่างๆ ในชุดใหญ่");
                WriteTxt1.WriteLine("0                     0-6 ไว้ทดลองกรณีต่างๆ ในชุดเล็ก");
                WriteTxt1.Close();
                Util.Program.Pok_Mess("สร้างไฟล์ txt2com.ini");
                if (lDebug) { Special.DEBUG.D(p, " - 03"); }
            }
            if (File.Exists("repopok.txt"))  // ตรวจสอบถ้ามี คลาวด์ ให้เปลี่ยนตัวเก็บประวัติ 
            {
                string[] Line4pok = File.ReadAllLines("repopok.txt");
                cTemp = Line4pok[0].Trim();
                if (cTemp != "" && Directory.Exists(cTemp)) 
                {
                    if (cTemp.Substring(cTemp.Length -1, 1) != @"\") { cTemp = cTemp + @"\"; }
                    FldBackupTxt = cTemp;
                    if (!Directory.Exists(FldBackupTxt + "History")) { Directory.CreateDirectory(FldBackupTxt + "History"); }
                    fBackupTxt = FldBackupTxt + "History\\Open.txt";
                    fBackupTxtR = FldBackupTxt + "History\\OpenR.txt";
                    if (lDebug) { Special.DEBUG.D(p, " - 04 -"+ fBackupTxt); }
                }
                 cTemp = "";
            }
            bool lNewBackFle = true;
            if (!File.Exists(fBackupTxt)) { lNewBackFle = false; } else 
            {
                if (lDebug) { Special.DEBUG.D(p, " - 05 -"+ fBackupTxt); }
                TimeSpan ts = (DateTime.Now - File.GetCreationTime(fBackupTxt));
                int nDay = ts.Days;
                if (nDay!=0)  { // เลยมา 1 วันให้ลบ
                    lNewBackFle = false;
                    cTemp = FldBackupTxt + "History\\Open" + File.GetCreationTime(fBackupTxt).ToString("ddMMyyyy_HHmmss")+".txt";
                    File.Copy(fBackupTxt, cTemp, true);
                    File.Delete(fBackupTxt); 
                    cTemp = "";
                    if (lDebug) { Special.DEBUG.D(p, " - 06 -"+ fBackupTxt); }
                } 
            }
            if (!File.Exists(@"History/card.TXT"))  
            {
                TextWriter WriteTxt1 = new StreamWriter(@"History/card.TXT");
                WriteTxt1.WriteLine("Not Found");
                WriteTxt1.Close();  
            }
            if (lNewBackFle==false) { crfBackupTxt(); } // สร้างใหม่ ทุกๆ 1 วัน    
        }


        public static void crfBackupTxt() // สร้างไฟล์ fBackupTxt
        {
            string p = "crfBackupTxt";
            if (lDebug) { Special.DEBUG.D(p, " - 01 -" + fBackupTxt); }
            TextWriter WriteTxt1;
            WriteTxt1 = new StreamWriter(fBackupTxt);
            WriteTxt1.WriteLine("Start : " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
            WriteTxt1.Close();
            if (lDebug) { Special.DEBUG.D(p, " - 02 -FINNISH"); }
        }


        static void Set2txt2comini()
        {
            if (!File.Exists("txt2com.ini")) { return; }
            File.Copy("txt2com.ini", "txt2com.bak", true);
            string[] ReadTxt = File.ReadAllLines("txt2com.bak");
            string cHistory = ReadTxt[1].Substring(0, 1).Trim();  // 1 = เก็บประวัติ   
            string cHistoryold= cHistory;
            bool lYesno = Layout.Program.myYesno.Form_Yesno("เก็บประวัติ ***อาจทำให้โปรแกรมช้า", "0=ยกเลิก,1=ตกลง,2=เรียงจากท้าย", ref cHistory);
            cHistory = cHistory.Trim();
            switch (cHistory)
            {
                case (""): case ("1"): case ("2"): break;
                default: cHistory = "0";break;
            }
            if (lYesno && cHistoryold != cHistory) // ตกลงเปลี่ยนค่า
            {
                TextWriter WriteTxt1 = new StreamWriter("txt2com.ini");
                nTemp = 0;
                foreach (string s in ReadTxt)
                {
                    if (nTemp==1) { WriteTxt1.WriteLine(cHistory + s.Trim().Substring(1)); } else { WriteTxt1.WriteLine(s.Trim()); }
                    nTemp++;
                }
                WriteTxt1.Close(); WriteTxt1.Dispose();
            }
        }


        public static void ChangeAndCutFile() // ตรวจสอบคำสั่งและจำนวนบรรทัด ให้ได้ ทีละ 10 บรรทัด  
        {
            if (!File.Exists(G.cpFileText)) { return; }
            string cTempCard = cTempWork + ".txt";
            TextWriter Cardtxt = new StreamWriter(cTempCard);
            string[] Lines = File.ReadAllLines(G.cpFileText);
            int nLine1 = Lines.Length;
            int nLine2 = 0;
            G.nFileRun = 0;
            string linetext;
            foreach (string line in Lines)
            {  linetext = line.Trim();
                if (linetext.Length==7 && linetext.Substring(0,2)==":M")  { Cardtxt.WriteLine(linetext); nLine2++; }
            }
            Cardtxt.Close(); Cardtxt.Dispose();     
            if (nLine1!=nLine2 || nLine2>3) { // เกิน 10 รายการให้ตัดไฟล์ 
                G.cpFileText = cTempCard;
                Lines = File.ReadAllLines(G.cpFileText);
                if (Lines.Length>10) 
                {
                    nTemp = -1;
                    foreach (string line in Lines)
                    {
                        if (nTemp==-1) {
                            G.nFileRun++;
                            nTemp = 0;
                            cTempCard = cTempWork+"_"+G.nFileRun.ToString().PadLeft(2, '0') + ".txt";
                            Cardtxt = new StreamWriter(cTempCard);
                        }
                        linetext = line.Trim();
                        Cardtxt.WriteLine(linetext);
                        nTemp++;
                        if (nTemp>=10)  {  nTemp = -1; Cardtxt.Close();Cardtxt.Dispose(); }
                    }
                    if (nTemp!=-1) { Cardtxt.Close(); Cardtxt.Dispose();  }
               }
            }
        }

        // ลบ Temp File ช่วยงาน 
        static void DelTempFile()
        {
            DirectoryInfo dFolderList = new DirectoryInfo("\\Temp");
            FileInfo[]  FileList = dFolderList.GetFiles("tCard*.txt", SearchOption.TopDirectoryOnly);
            foreach (FileInfo cFileList in FileList) { try { File.Delete(cFileList.FullName); } catch { break; }}

            dFolderList = new DirectoryInfo(FldBackupTxt + "\\History");
            FileList = dFolderList.GetFiles("Open*.txt", SearchOption.TopDirectoryOnly);
            foreach (FileInfo cFileList in FileList) {try { File.Delete(cFileList.FullName); } catch { break; } }
        }



        static void Test_Prog() 
        {
            string p = "Test_Prog";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            // แสดงว่าเป็นการทดสอบ 
            // CheckComPort();
            // txt2com 1 com1 2 :M01011 สำหรับอำพัน
            // txt2com 1 com1 6 :M01011 สำหรับ Halls
            // Readme();
            G.cpFlag = "1";  // 0=แสดงหน้าจอ 1=ไม่แสดงหน้าจอ 
            G.cpCom = "com1:";  // ComPort 
            G.cpCompany = "2"; // เน้น 2 อำพัน 6 Halls  9=อื่นๆ room4code.txt
            G.cpFileText = ":M01011,:M01021,:M01031";
            /*
            ข้อความหรือไฟล์ 
            SaveHistory(1, @"R:\Temp\test.txt");
            G.cpFileText = @"R:\Temp\test.txt";
            ChangeAndCutFile(); 
            Send_FileTxt();
            DelTempFile();            
            Set2txt2comini(); 
            Cr_AllTextFile(); 
            */
            // Util.Program.ReverseTextFile(fBackupTxt, fBackupTxtR, 10);
            if (lDebug) { Special.DEBUG.D(p, " - 02 -FINNISH"); }
        }


        static void Main(string[] args)  
        {
            if (MyApp.Substring(0, 2) == "V:") { insource = true; } // Run กับ Source
            if (Directory.Exists("R:\\Temp")) { inharddisk = true; }  // Run กับ Harddisk   
            lDebug = Special.DEBUG.Cr_Debug(MyProg);
            string p = "Main";
            if (lDebug) { Special.DEBUG.D(p, " - 01"); }
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); // เปลี่ยนรูปแบบวันที่ เป็น GB
            cTempWork = MyApp.Substring(0, 2) + "\\Temp\\tCard" + DateTime.Now.ToString("dddHHmmss").ToUpper();
            nForWork = 1;  //    ปรกติ  1 nForWork=0 ไม่ทำอะไรเลย ,1 ทำงานตามปรกติ 2 ไม่Runโปรแกรมและมีเตือน  
            if (lDebug) { Special.DEBUG.D(p, " - 02"); }
            if (lDebug) { Special.DEBUG.D(p, " - 03"); }
            Init(); // เริ่มเข้าโปรแกรม 
            // สร้างไฟล์ card??.txt ไว้ทดสอบการ์ดของอำพัน
            if (!insource && !File.Exists("cardALL_1.txt")) { Util.Program.Pok_Mess("สร้างไฟล์ txt ช่วยงาน"); Cr_AllTextFile(); }
            G.cpFlag = ""; G.cpCom = ""; G.cpCompany = ""; G.cpFileText = "";
            string[] ReadTxt = File.ReadAllLines("txt2com.ini");  // สำหรับใช้ใน Flag L  
            if (lDebug) { Special.DEBUG.D(p, " - 04 -txt2com.ini"); }
            if (ReadTxt.Length<8)
            {
                cTemp = "txt2com" + DateTime.Now.ToString("ddMM") + ".ini";
                Util.Program.Pok_Mess("ไฟล์ txt2com.ini  ไม่สมบูรณ์ให้ลบและสร้างใหม่"+Environment.NewLine+"สำรองไว้ที่ "+cTemp);
                File.Copy("txt2com.ini",cTemp , true);
                File.Delete("txt2com.ini");
                if (lDebug) { Special.DEBUG.D(p, " - 04 -txt2com.ini -Error"); }
                return;
            }
            if (lDebug) { Special.DEBUG.D(p, " - 05"); }
            G.cFoldLink = ReadTxt[0].Substring(0, 8).Trim(); // 8 ตำแหน่งแรก เป็นที่รับ ไฟล์ Text
            G.cHistory = ReadTxt[1].Substring(0, 1).Trim();  // 1 = เก็บประวัติ  
            G.cpAct4group= ReadTxt[6].Substring(0, 1).Trim(); // ตัวแปรสำหรับทดสอบ ในชุดใหญ่
            G.cpAct4single = ReadTxt[7].Substring(0, 1).Trim(); // ตัวแปรสำหรับทดสอบ ในชุดเล็ก
            if (lDebug) { Special.DEBUG.D(p, " - 06"); }
            if (args.Length == 0)  {  // กรณีเรียกไฟล์ ตรงๆ
                if (insource) { G.cpFlag = "T";  } else {
                    G.cpFlag = "L"; // กรณีเรียกไฟล์ เพื่อรัน อัตโนมัติ
                    G.cpCom = ReadTxt[4].Substring(0, 4).Trim();  // ComPort 
                    G.cpCompany = ReadTxt[5].Substring(0, 1).Trim(); ; // เน้น 2 อำพัน 6 Halls
                    G.cpFileText = "";
                    if (lDebug) { Special.DEBUG.D(p, " - 07 -"+ G.cpCom); }
                }
            }  else { // กรณีเรียกแบบมี parameter 
                if (lDebug) { Special.DEBUG.D(p, " - 08"); }
                G.cpFlag = args[0].Trim().ToUpper();  // 0=แสดงหน้าจอ 1=ไม่แสดงหน้าจอ 
                switch (G.cpFlag)
                {
                    case ("0"): case ("?"):
                        G.cpCom = "COM0"; // ComPort 
                        G.cpCompany = "2"; // เน้น 2 อำพัน 6 Halls
                        G.cpFileText = ":M01011"; // ข้อความหรือไฟล์ 
                        break;
                    case ("D"): case ("R"): case ("S"):  // Option เฉพาะข้ามไป
                        break;
                    case ("AMPHAN"): case ("AMP"): // พิเศษ กรณีอำพันให้ตามด้วย ชื่อไฟล์หรือข้อความเลย txt2com AMP ??? แทน txt2com 1 com1 2 ??? 
                        G.cpFlag = "1"; G.cpCom = ReadTxt[4].Substring(0, 4).Trim();
                        G.cpCompany = "2"; G.cpFileText = args[1].Trim(); 
                        break;
                    case ("HALLS"):  case ("HALL"): // พิเศษ กรณีอำพันให้ตามด้วย ชื่อไฟล์หรือข้อความเลย txt2com AMP ??? แทน txt2com 1 com1 2 ???
                        G.cpFlag = "1"; G.cpCom = ReadTxt[4].Substring(0, 4).Trim();
                        G.cpCompany = "6"; G.cpFileText = args[1].Trim(); 
                        break;
                    default:
                        // เป็นกรณีใช้เป็นปรกติ 
                        G.cpCom = args[1].Trim().ToUpper(); // ComPort 
                        G.cpCompany = args[2].Trim(); // เน้น 2 อำพัน 6 Halls
                        G.cpFileText = args[3].Trim(); // ข้อความหรือไฟล์ 
                        break;
                }
            }
            if (lDebug) { Special.DEBUG.D(p, " - 09"); }
            /*  สำหรับทดสอบระบบ  Pipop 0
            G.cpFlag = "1";  // 0=แสดงหน้าจอ 1=ไม่แสดงหน้าจอ L=แบบรับค่า 
            G.cpCom = "com1:";  // ComPort 
            G.cpCompany = "9" ; // เน้น 2=อำพัน 6= Halls 9=อื่นๆ 
            G.cpFileText = "test.txt"; // ข้อความหรือไฟล์  ":M01011"  ,  test.txt , 01011
            */
            if (G.cpFlag == "C") { CheckComPort(); if (lDebug) { Special.DEBUG.D(p, " - 09 -CheckComPort -FINNISH");} return; }
            if (G.cpFlag == "D") { DelTempFile(); if (lDebug) { Special.DEBUG.D(p, " - 09 -DelTempFile -FINNISH"); } return; }
            if (G.cpFlag == "R") { ReadComPort2Text(); if (lDebug) { Special.DEBUG.D(p, " - 09 -ReadComPort2Text -FINNISH"); } return; }
            if (G.cpFlag == "S") { Set2txt2comini(); if (lDebug) { Special.DEBUG.D(p, " - 09 -Set2txt2comini -FINNISH"); } return; }
            if (G.cpFlag == "T") { Test_Prog(); if (lDebug) { Special.DEBUG.D(p, " - 09 -Test_Prog -FINNISH"); } return; }
            if (lDebug) {Special.DEBUG.D(p, " -10");}
            if (G.cpCom.Substring(3, 1) == "?")  // เช็ค COM0 เพื่อหา COM? อัตโนมัติ 
            {
                if (!File.Exists("txt2com.set")) { ErrorInCOM(); }
                string[] lines = File.ReadAllLines("txt2com.set");  
                G.cpCom = lines[0].Trim().ToUpper();
            }
            if (lDebug) { Special.DEBUG.D(p, " -11"); }
            if (G.cpFlag=="L") { G.nFileType = 1; }
            else
            {   G.nFileType = 0;  // กรณีที่ส่งมาเป็นข้อความ
                if (ThisIsText(G.cpFileText)==1) { G.nFileType = 1; }
                else { if (ThisIsText(G.cpFileText) == 2) { Util.Program.Pok_Mess("ไม่พบไฟล์ " + G.cpFileText); return; } }
            }
            if (lDebug) { Special.DEBUG.D(p, " -12"); }
            if (G.cpCompany == "2")
            { if (G.nFileType == 0) { ConvertText2File(); }    // อำพัน ให้แปลงเป็นไฟล์เพื่อส่งเข้ากล่องไฟ
              if (G.nFileType == 1) { ChangeAndCutFile(); }    // ตรวจสอบไฟล์ขนาดใหญ่ ให้ตัดทีละ 10 Relay
            }
            /*                   
            Util.Program.Pok_InHarddisk("cpFlag=" + G.cpFlag
                + System.Environment.NewLine + System.Environment.NewLine
                + ",cpCom  =  " + G.cpCom + System.Environment.NewLine
                + ",cpCompany  =  " + G.cpCompany + System.Environment.NewLine
                + ",cpFileText  =  " + G.cpFileText + System.Environment.NewLine
                + ",cpAct4group  =  " + G.cpAct4group + System.Environment.NewLine
                + ",cpAct4single  =  " + G.cpAct4single  );
            */
            switch (G.cpFlag) 
            {
                case ("?"): Readme() ; break;
                case ("0"): Send_FileTxt(); if (lDebug) { Special.DEBUG.D(p, " -13 -Send_FileTxt(0)"); } break;
                case ("1"): Send_FileTxt(); if (lDebug) { Special.DEBUG.D(p, " -14 -Send_FileTxt(1)"); } break;
                case ("L"):
                    // ตรวจสอบเปิดซ้ำ 
                    if (lDebug) { Special.DEBUG.D(p, " - 15 -WAmphan"); }
                    Process mobj_pro = Process.GetCurrentProcess();
                    Process[] mobj_proList = Process.GetProcessesByName(mobj_pro.ProcessName);
                    if (mobj_proList.Length>1) { Util.Program.Pok_InHarddisk("เปิดโปรแกรมซ้ำ"); return;          }
                    if (!Directory.Exists(G.cFoldLink)) { Directory.CreateDirectory(G.cFoldLink); }
                    Application.EnableVisualStyles();
                    Application.Run(new WAmphan());
                    break;
            }
            if (lDebug) { Special.DEBUG.D(p, " -16"); }
            if (G.cHistory == "2" && G.cpFlag!="L")
            {
                if (G.lFullremark) { nTemp = 30; } else { nTemp = 50; }
                Util.Program.ReverseTextFile(fBackupTxt, fBackupTxtR,nTemp);
            } // กลับไฟล์จะท้าย
            if (lDebug) { Special.DEBUG.D(p, " -17 -FINNISH"); }
        }
    }
}
