using SHDocVw;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class AddMarc : Form
    {
        Helper_DB db = new Helper_DB();
        String_Text st = new String_Text();
        Help008Tag tag008 = new Help008Tag();
        private string mOldMarc = string.Empty;
        Main m;
        public AddMarc(Main _m)
        {
            InitializeComponent();
            m = _m;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Alt || keyData == (Keys.Alt | Keys.Menu))
            {
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    
        private void AddMarc_Load(object sender, EventArgs e)
        {
            cb_SearchCol.SelectedIndex = 0;

            db.DBcon();
            TextReset();
        }

        private void tb_ISBN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
                return;

            TextReset();

            string SearchText = tb_Search.Text;
            string SearchCol = cb_SearchCol.SelectedItem.ToString();
            MarcCopySelect mcs = new MarcCopySelect(this);
            mcs.Init(SearchCol, SearchText);
            mcs.Show();
        }

        /// <summary>
        /// ISBN 검색후 특정 마크 선택시 현재폼에 적용시키는 폼
        /// </summary>
        /// <param name="Marc">뷰형태 마크데이터</param>
        /// <param name="ISBN">ISBN</param>
        /// <param name="GridData">
        /// 0:idx     <br></br>
        /// 1:compidx <br></br>
        /// 2:user    <br></br>
        /// 3:date    <br></br>
        /// 4:grade   <br></br>
        /// 5:tag008  <br></br>
        /// 6:LineMarc</param>
        public void SelectMarc_Sub(string Marc, string ISBN, string[] GridData)
        {
            richTextBox1.Text = Marc;
            lbl_ISBN.Text = ISBN;
            // [이름 혹은 회사명] [yyyy-MM-dd HH:mm:ss]
            lbl_SaveData.Text = string.Format("[{0}] [{1}]", GridData[2], GridData[3]);
            SetGrade(GridData[4]);
            //TODO: 이전데이터 저장할곳
            mOldMarc = GridData[6];
            lbl_Midx.Text = GridData[0];
        }

        private void SetGrade(string Grade)
        {
            cb_grade.SelectedIndex = cb_grade.Items.IndexOf(Grade);
        }

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

        private void btn_preview_Click(object sender, EventArgs e)
        {
            Marc_Preview mp = new Marc_Preview();
            mp.isbn = lbl_ISBN.Text;
            mp.richTextBox1.Text = richTextBox1.Text;
            mp.Show();
        }

        private void Btn_Memo_Click(object sender, EventArgs e)
        {
            Marc_memo memo = new Marc_memo(this);
            memo.StartPosition = FormStartPosition.Manual;
            memo.TopMost = true;
            memo.Location = new Point(1018, 8);
            memo.Show();
        }

        private void btn_Empty_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            TextReset();
        }

        /// <summary>
        /// 전체 초기화
        /// </summary>
        /// <param name="isDelete">탭 컨트롤에서 사용할 경우 false</param>
        public void TextReset(bool isDelete = true)
        {
            if (isDelete)
            {
                lbl_ISBN.Text = "[]";
                lbl_SaveData.Text = "[] []";
                lbl_Midx.Text = "";
                richTextBox1.Text = TextResetSub();
            }

            TextBox[] tb = {
                textDDC21, textDDC22, textDDC23, textKDC4, textKDC5, textKDC6,
                text041a, text041b, text041h, text041k,

                basicHeadBox,

                text245a, text245b, text245e, text245n, text245p, text245d, text245x,

                text250a,

                text260a, text260b, text260c, text260g,

                text300a, text300b, text300c1, text300c2, text300e,

                text500a, text504a, text505a, text507a, text507t,
                text520a, text521a, text525a, text536a, text546a,
                text586a, text650a, text653a, text700a, text710a,
                text900a, text910a, text940a
            };
            DataGridView[] dgv = {
                GridView020, GridView246, GridView440, GridView490, GridView505
            };

            foreach (TextBox box in tb)
            {
                box.Text = "";
            }
            foreach (DataGridView grid in dgv)
            {
                grid.Rows.Clear();

                grid.Rows.Add(50);

                if (grid.Name.IndexOf("505") > 0)
                    grid.Rows.Add(50);
            }
        }

        string TextResetSub()
        {
            // 입력일자 (00-05)
            // 발행년유형 (6)
            // 발행년1 (07-10)
            // 발행년2 (11-14)
            // 발행국 (15-17)

            // 삽화표시 (18-21)
            // 이용대상자수준 (22) v
            // 개별자료형태 (23) v
            // 내용형식1 (24) v
            // 내용형식2 (25) v

            // 한국대학부호 (26-27)
            // 수정레코드 (28)
            // 회의간행물 (29) c
            // 기념논문집 (30) c
            // 색인 (31)

            // 목록전거 (32)
            // 문학형식 (33) v
            // 전기 (34) v
            // 언어 (35-37) v
            // 한국정부기관부호 (38-39)
            string yyMMdd = DateTime.Now.ToString("yyMMdd");
            string yyyy = DateTime.Now.ToString("yyyy");
            string Empty_008 = yyMMdd + "s" + yyyy + "                  000   kor  ▲";
            text008.Text = Empty_008.Replace("▲", "");
            string Empty_text = string.Format(
                "020\t  \t▼a▼c▲\n" +
                "056\t  \t▼a▼2▲\n" +
                "100\t  \t▼a▲\n" +
                "245\t  \t▼a▼d▲\n" +
                "260\t  \t▼b▲\n" +
                "300\t  \t▼a▼c▲\n" +
                "653\t  \t▼a▲\n" +
                "700\t  \t▼a▲\n" +
                "950\t  \t▼b▲\n");
            etc1.Text = "";
            etc2.Text = "";
            return Empty_text;
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            int grade = cb_grade.SelectedIndex;
            int TagIndex = tabControl1.SelectedIndex;

            if (TagIndex == 1)
            {
                MessageBox.Show("[칸채우기]가 아닌 [마크 작성] 탭에서 저장해주세요!");
                return;
            }
            if (grade == 3 || grade == -1)
            {
                MessageBox.Show("등급을 설정해주세요. (C 이상)");
                return;
            }

            bool isUpdate;      // true일 경우 INSERT / false일 경우 UPDATE
            string Table = "Marc";
            string MarcText = richTextBox1.Text;

            if (!MarcText.EndsWith("\n"))
                MarcText += "\n";

            if (!isPass(MarcText))
            {
                MessageBox.Show("입력된 마크의 상태를 확인해주세요.", "isPass");
                return;
            }

            string tag056 = Tag056();
            string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string orimarc = st.made_Ori_marc(richTextBox1).Replace(@"\", "￦");
            
            if (!isMustTag(orimarc)) {
                richTextBox1.Text = MarcText;
                return;
            }

            string midx = lbl_Midx.Text;
            string[] BookData = GetBookData(MarcText);
            string[] SaveData = DateNameSplit();
            bool IsCoverDate = false;

            if (SaveData[1] != "")
            {
                // 마지막 수정일로부터 2일이 지났는지, 마지막 저장자가 사용자인지 확인
                TimeSpan sp = CheckDate(SaveData[1], date);
                IsCoverDate = IsCoverData(sp.Days, SaveData[0]);
                //if (IsCoverDate)
                //    etc2.Text = etc2.Text.Replace(SaveData[0], date);
            }
            //else
            //    etc2.Text += string.Format("{0}\t{1}\n", date, mUserName);

            if (lbl_Midx.Text != "")
                isUpdate = true;
            else
                isUpdate = false;

            if (isUpdate)
                UpdateMarc(Table, midx, orimarc, grade, tag056, date, IsCoverDate);
            else
                InsertMarc(Table, BookData, orimarc, grade, tag056, date);

            MessageBox.Show("저장되었습니다.", "저장");
        }

        #region SaveSub

        /// <summary>
        /// 마크DB에 UPDATE해주는 함수
        /// </summary>
        /// <param name="Table">테이블 이름</param>
        /// <param name="MarcIndex">마크 인덱스 번호</param>
        /// <param name="oriMarc">한줄짜리 마크</param>
        /// <param name="grade">마크 등급</param>
        /// <param name="tag056">분류기호</param>
        /// <param name="date">저장시각 yyyy-MM-dd HH:mm:ss</param>
        /// <param name="IsCovertDate">덮어씌울지 유무</param>
        void UpdateMarc(string Table, string MarcIndex, string oriMarc, int grade, string tag056, string date, bool IsCovertDate)
        {
            string[] EditTable =
            {
                "compidx", "marc", "marc_chk","marc1", "marc_chk1", "비고1",
                "비고2", "division", "008tag", "date", "user",
                "grade"
            };
            string[] EditColumn =
            {
                 PUB.user.CompanyIdx, oriMarc, "1",mOldMarc, "0", etc1.Text,
                etc2.Text, tag056, text008.Text, date, PUB.user.UserName,
                grade.ToString()
            };
            string[] SearchTable = { "idx","compidx" };
            string[] SearchColumn = { MarcIndex, PUB.user.CompanyIdx };

            //int marcChk = subMarcChk(Table, MarcIndex);
            //if (IsCovertDate)
            //    marcChk--;

            //switch (marcChk)
            //{
            //    case 0:
            //        EditTable[1] = "marc1";
            //        EditTable[2] = "marc_chk1";
            //        EditTable[3] = "marc_chk";
            //        break;
            //    case 1:
            //        EditTable[1] = "marc2";
            //        EditTable[2] = "marc_chk2";
            //        EditTable[3] = "marc_chk1";
            //        break;
            //    case 2:
            //        EditTable[1] = "marc";
            //        EditTable[2] = "marc_chk";
            //        EditTable[3] = "marc_chk2";
            //        break;
            //    default:
            //        EditTable[1] = "marc";
            //        EditTable[2] = "marc_chk";
            //        EditTable[3] = "marc_chk2";
            //        break;
            //}
            string UpCMD = db.More_Update(Table, EditTable, EditColumn, SearchTable, SearchColumn);
            PUB.log.Add("ADDMarcUPDATE", string.Format("{0}({1}) : {2}", PUB.user.UserName, PUB.user.CompanyIdx, UpCMD.Replace("\r", " ").Replace("\n", " ")));
            Helper_DB.ExcuteNonQuery(UpCMD);
        }
    

        /// <summary>
        /// 마크DB에 INSERT해주는 함수
        /// </summary>
        /// <param name="Table">테이블 이름</param>
        /// <param name="BookData">0:ISBN 1:서명 2:저자 3:출판사 4:정가</param>
        /// <param name="oriMarc">한줄짜리 마크</param>
        /// <param name="grade">마크 등급</param>
        /// <param name="tag056">분류기호</param>
        /// <param name="date">저장시각 yyyy-MM-dd HH:mm:ss</param>
        void InsertMarc(string Table, string[] BookData, string oriMarc, int grade, string tag056, string date)
        {
            string[] InsertTable =
            {
                "ISBN", "서명", "저자", "출판사", "가격",
                "marc", "비고1", "비고2", "grade", "marc_chk",
                "user", "division", "008tag", "date", "compidx"
            };
            string[] InsertColumn =
            {
                BookData[0], BookData[1], BookData[2], BookData[3], BookData[4],
                oriMarc, etc1.Text, etc2.Text, grade.ToString(), "1",
                PUB.user.UserName, tag056, text008.Text, date, PUB.user.CompanyIdx
            };

            string InCMD = db.DB_INSERT(Table, InsertTable, InsertColumn);
            PUB.log.Add("ADDMarcINSERT", string.Format("{0}({1}) : {2}", PUB.user.UserName, PUB.user.CompanyIdx, InCMD.Replace("\r", " ").Replace("\n", " ")));
            Helper_DB.ExcuteNonQuery(InCMD);
        }

        /// <summary>
        /// 마크 저장시 사용하며, 마지막 수정일과 수정자를 가져와 덮어씌울지 백업데이터를 만들지 구분
        /// </summary>
        /// <param name="TimeSpanDaysValue">저장할 마크의 마지막 수정일</param>
        /// <param name="user">저장할 마크의 마지막 수정자</param>
        /// <returns>마지막 수정일로부터 2일이 지나지 않고, 마지막 수정자와 해당 유저가 동일 할 경우 True 반환</returns>
        private bool IsCoverData(int TimeSpanDaysValue, string user)
        {
            if (TimeSpanDaysValue < -1)
                return false;
            if (user != PUB.user.UserName)
                return false;
            return true;
        }

        private TimeSpan CheckDate(string LastDate, string SaveDate)
        {
            DateTime Last = Convert.ToDateTime(LastDate);
            DateTime Save = Convert.ToDateTime(SaveDate);

            return Last - Save;
        }

        /// <summary>
        /// [이름 혹은 회사명] [yyyy-MM-dd HH:mm:ss] 분리
        /// </summary>
        /// <returns>0:이름혹은회사명 1:저장시각</returns>
        private string[] DateNameSplit()
        {
            string[] tmp = lbl_SaveData.Text.Split(']');
            string[] result = { "", "" };
            result[0] = tmp[0].Replace("[", "");
            result[1] = tmp[1].Replace("[", "").Trim();
            return result;
        }

        /// <summary>
        /// 필수태그 검사
        /// </summary>
        /// <param name="orimarc">한줄짜리 마크</param>
        /// <returns>필수태그 없을시 false 반환</returns>
        private bool isMustTag(string orimarc)
        {
            string[] SearchTag = { "056a", "0562", "245a", "245d", "260a", "260c", "300a", "300c", "653a" };
            string[] Tag = st.Take_Tag(orimarc, SearchTag);

            int count = 0;
            string msg = "";
            bool isTag = true;
            foreach (string tag in Tag)
            {
                if (tag == "")
                {
                    msg += SearchTag[count] + " ";
                    isTag = false;
                }
                count++;
            }
            if (!isTag)
            {
                MessageBox.Show(msg + "태그가 없습니다.");
                return false;
            }

            bool is1XX = false;
            string[] AuthorTag = { "100a", "110a", "111a" };
            Tag = st.Take_Tag(orimarc, AuthorTag);
            foreach (string author in Tag)
            {
                if (author != "")
                    is1XX = true;
            }
            if (!is1XX)
            {
                MessageBox.Show("기본표목이 존재하지않습니다.");
                return false;
            }

            bool is7XX = false;
            AuthorTag[0] = "700a";
            AuthorTag[1] = "710a";
            AuthorTag[2] = "711a";
            Tag = st.Take_Tag(orimarc, AuthorTag);

            foreach (string author in Tag)
            {
                if (author != "")
                    is7XX = true;
            }

            if (!is7XX)
            {
                MessageBox.Show("부출표목이 존재하지않습니다.");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 관련 도서 정보를 가져옴
        /// </summary>
        /// <param name="ViewMarc">뷰형태의 마크</param>
        /// <returns>0:ISBN 1:서명 2:저자 3:출판사 4:정가</returns>
        string[] GetBookData(string ViewMarc)
        {
            // ISBN, BookName, Author, BookComp, Price
            string[] result = { "", "", "", "", "" };
            bool IsISBN = false;
            string[] TargetArr = ViewMarc.Split('\n');
            foreach (string Target in TargetArr)
            {
                string[] tmp = Target.Replace("▲", "").Split('\t');
                // 0:ISBN 4:Price
                if (tmp[0] == "020" && !IsISBN) {
                    IsISBN = true;
                    result[0] = GetMiddelString(tmp[2], "▼a", "▼");
                    result[4] = GetMiddelString(tmp[2], "▼c", "▼");
                }

                // 2:Author
                if (tmp[0] == "100")
                    result[2] = GetMiddelString(tmp[2], "▼a", "▼");
                else if(tmp[0]=="110")
                    result[2] = GetMiddelString(tmp[2], "▼a", "▼");
                else if(tmp[0]=="111")
                    result[2] = GetMiddelString(tmp[2], "▼a", "▼");

                // 1:BookName
                if (tmp[0] == "245")
                    result[1] = GetMiddelString(tmp[2], "▼a", "▼");

                // 3:BookComp
                if (tmp[0] == "300")
                    result[3] = GetMiddelString(tmp[2], "▼b", "▼");
            }

            return result;
        }

        string Tag056()
        {
            string marc = richTextBox1.Text;
            string[] temp = marc.Split('\n');
            List<string> target = temp.ToList();
            btn_Reflesh008_Click(null, null);
            bool isEight = false;
            bool eight_chk = false;
            string tag056 = string.Empty;
            int count = 0;

            for (int a = 0; a < target.Count - 1; a++)
            {
                string[] tmp = target[a].Split('\t');
                string tag = tmp[0];
                if (tag == "") break;
                int eight = Convert.ToInt32(tag.Substring(0, 3));
                if (eight == 008)
                {
                    count = a;
                    eight_chk = true;
                    isEight = true;
                }
                else if (eight > 008 && !eight_chk)
                {
                    count = a;
                    eight_chk = true;
                }
                if (tag == "056")
                    tag056 = GetMiddelString(tmp[2], "▼a", "▼");
            }
            if(!isEight)
                target.Insert(count, string.Format("{0}\t{1}\t{2}▲", "008", "  ", text008.Text));

            richTextBox1.Text = string.Join("\n", target.ToArray());
            return tag056;
        }

        /// <summary>
        /// 마크 오류체크 (형식체크)
        /// </summary>
        /// <param name="BaseData">richTextBox에 들어가있는 텍스트</param>
        /// <returns>True / False</returns>
        private bool isPass(string BaseData)
        {
            string[] EnterSplit = BaseData.Split('\n');

            foreach (string Data in EnterSplit)
            {
                if (Data == "")
                    continue;

                string[] DataSplit = Data.Split('\t');
                if (DataSplit.Length == 3)
                {
                    if (DataSplit[1].Length == 2)
                    {
                        continue;
                    }
                    else
                    {
                        MessageBox.Show(string.Format("SplitError : {0}", string.Join("\t", DataSplit)));
                        return false;
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("DataError : {0}", Data));
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 문자와 문자사이의 값 가져오기
        /// </summary>
        /// <param name="str">대상 문자열</param>
        /// <param name="begin">시작 문자열</param>
        /// <param name="end">마지막 문자열</param>
        /// <param name="TagNum">불러올 태그 번호</param>
        /// <returns>문자 사이값</returns>
        public string GetMiddelString(string str, string begin, string end, string TagNum = "")
        {
            string result = "";

            if (string.IsNullOrEmpty(str) || str == "")
                return result;

            int count = 0;
            bool loop = false;

            for (int a = count; a < str.Length; a++)
            {
                count = str.IndexOf(begin);
                if (count > -1)
                {
                    str = str.Substring(count + begin.Length);
                    if (loop)
                        // 여러 태그들 구분을 지어줌.
                        result += "▽";

                    if (str.IndexOf(end) > -1)
                        result += str.Substring(0, str.IndexOf(end));
                    else
                        result += str;

                    result = TrimEndGubun(result, TagNum);
                }
                else
                    break;

                loop = true;
            }

            return result;
        }

        string TrimEndGubun(string str, string TagNum)
        {
            char[] gu = { '.', ',', ':', ';', '/', ' ' };
            if (TagNum == "300" || TagNum == "300a")
            {
                str = str.Trim();
                if (TagNum == "300a")
                {
                    gu = new char[] { '.', ',', '=', ':', ';', '/', '+', ' ' };
                    for (int i = 0; i < gu.Length; i++)
                    {
                        str = str.TrimEnd(gu[i]);
                    }
                }

                if (str.Contains("ill."))
                    return str;
                if (str.Contains("p."))
                    return str;
            }

            if (TagNum == "710" || TagNum == "910")
                return str;


            if (TagNum == "245") gu = new char[] { '.', ':', ';', '/', ' ' };
            if (TagNum == "245a") gu = new char[] { '.', ',', '=', ':', ';', '/', ' ' };
            for (int i = 0; i < gu.Length; i++)
            {
                str = str.TrimEnd(gu[i]);
            }
            //foreach (char gubun in gu)
            //{
            //    if (str.Length < 1) continue;
            //    if (str[str.Length - 1] == gubun)
            //    {
            //        str = str.Remove(str.Length - 1);
            //        str = str.Trim();
            //    }
            //}

            return str;
        }
        #endregion


        private void ComboBox008_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (text008.Text.Length < 3) return;

            string text = text008.Text;
            string comboName = ((ComboBox)sender).Name;
            int comboIdx = ((ComboBox)sender).SelectedIndex;

            text008.Text = tag008.Combo_Change(text, comboName, comboIdx);
        }

        private void btn_Reflesh008_Click(object sender, EventArgs e)
        {
            string data = text008.Text;
            string oriMarc = st.made_Ori_marc(richTextBox1).Replace("\\", "￦");

            #region 사전에 선언된 string배열에 맞는 데이터를 배정.

            // 참조할 태그 배열 선언
            string[] SearchTag = { "260c", "260a", "300a" };
            string[] ContentTag = st.Take_Tag(oriMarc, SearchTag);

            // 입력일자 (00 - 05)
            string day;
            if (input_date.Checked)
                day = string.Format("{0}{1}{2}",
                    DateTime.Now.ToString("yy"), DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"));
            else
                day = input_date.Value.ToString("yy") + input_date.Value.ToString("MM") + input_date.Value.ToString("dd");

            // 발행년 유형 (6), 발행년1 (07-10), 발행년2 (11-14)
            string DateSet = pubDateSet(ContentTag[0]);

            // 발행국 (15 - 17)
            string Country = pubCountry(ContentTag[1]);

            // 삽화표시 (18 - 21)
            string Picture = tag008.Picture_008(ContentTag[2]);

            string tmp = day + DateSet + Country + Picture;

            if (data == "")
            {
                text008.Text = tmp;
                return;
            }


            char[] textArray = data.ToCharArray();
            Array.Resize(ref textArray, 22);
            for (int a = 0; a < tmp.Length; a++)
            {
                textArray[a] = tmp[a];
            }
            string tTemp = tmp.ToString();
            tTemp = tTemp.PadRight(40, ' ');
            text008.Text = tTemp;
            text008.Text = tag008.Combo_Change(text008.Text, comboBox1.Name, comboBox1.SelectedIndex);// 이용대상자수준 (22) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox2.Name, comboBox2.SelectedIndex);// 개별자료형태 (23) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox3.Name, comboBox3.SelectedIndex);// 내용형식1 (24) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox7.Name, comboBox7.SelectedIndex);// 내용형식2 (25) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox4.Name, comboBox4.SelectedIndex);  // 문학형식 (33) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox5.Name, comboBox5.SelectedIndex); // 전기 (34) v
            text008.Text = tag008.Combo_Change(text008.Text, comboBox6.Name, comboBox6.SelectedIndex); // 언어 (35-37) v

            Publication(checkBox1.Checked, 29);// 회의간행물 (29) c
            Publication(checkBox2.Checked, 30);// 기념논문집 (30) c
            Publication(checkBox4.Checked, 31);// 색인 (31)

            textArray = text008.Text.ToCharArray();

            textArray[26] = col008res.Text[0]; //대학코드
            textArray[27] = col008res.Text[1];

            textArray[38] = gov008res.Text[0];// 정부코드
            textArray[39] = gov008res.Text[1];

            textArray[28] = ' ';// 수정레코드 (28)
            textArray[32] = ' ';// 목록전거 (32)
            text008.Text = new string(textArray);


            #endregion
        }

        #region 008태그 새로고침 버튼 서브함수

        /// <summary>
        /// 발행년유형 / 발행년1 / 발행년2 를 260c태그로 확인.
        /// </summary>
        /// <param name="ContentTag">260c의 태그내용</param>
        /// <returns></returns>
        private string pubDateSet(string ContentTag)
        {
            string Result = "";

            string pubDate = Regex.Replace(ContentTag, @"[^0-9]", "");

            if (pubDate.Length < 3)
            {
                MessageBox.Show("260c가 인식되지않습니다.");
                return "false";
            }
            else if (pubDate.Length < 5)
                Result = "s" + pubDate + "    ";
            else
                Result = "m" + pubDate;

            return Result;
        }

        /// <summary>
        /// 발행국명 을 260a태그로 확인.
        /// </summary>
        /// <param name="ContentTag">260a의 태그내용</param>
        /// <returns></returns>
        private string pubCountry(string ContentTag)
        {
            string Result = "";

            ContentTag = ContentTag.Replace("[", "").Replace("]", "").Trim();

            // string cmd = db.DB_Select_Search("`Code`", "Tag008_Country", "Area", ContentTag);
            string cmd = string.Format(
                "SELECT `Code` FROM `Tag008_Country` WHERE `Area` <= \"{0}\" ORDER BY `Area` DESC LIMIT 1;", ContentTag);
            string res = db.DB_Send_CMD_Search(cmd).Replace("|", "");

            if (res == "")
            {
                MessageBox.Show("260a가 인식되지않습니다.");
                return "false";
            }
            else if (res.Length < 3)
                Result = res + " ";
            else
                Result = res;

            return Result;
        }

        #endregion

        private void CheckBox008_CheckedChanged(object sender, EventArgs e)
        {
            string name = ((CheckBox)sender).Name;
            if (((CheckBox)sender).Checked == true)
            {
                switch (name)
                {
                    case "checkBox1":
                        ((CheckBox)sender).InvokeText("회의간행물o");
                        break;
                    case "checkBox2":
                        ((CheckBox)sender).InvokeText("기념논문집o");
                        break;
                    case "checkBox4":
                        ((CheckBox)sender).InvokeText("색인o");
                        break;
                }
            }
            else if (((CheckBox)sender).Checked == false)
            {
                switch (name)
                {
                    case "checkBox1":
                        ((CheckBox)sender).InvokeText("회의간행물x");
                        break;
                    case "checkBox2":
                        ((CheckBox)sender).InvokeText("기념논문집x");
                        break;
                    case "checkBox4":
                        ((CheckBox)sender).InvokeText("색인x");
                        break;
                }
            }
            switch (name)
            {
                case "checkBox1":
                    Publication(checkBox1.Checked, 29);
                    break;
                case "checkBox2":
                    Publication(checkBox2.Checked, 30);
                    break;
                case "checkBox4":
                    Publication(checkBox4.Checked, 31);
                    break;
            }
        }

        void Publication(bool check, int idx)
        {
            if (text008.Text == "") { return; }
            char[] ArrayChar = text008.Text.ToCharArray();
            if (check == false)     { ArrayChar[idx] = '0'; }
            else if (check == true) { ArrayChar[idx] = '1'; }
            text008.Text = new string(ArrayChar);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int TabIndex = tabControl1.SelectedIndex;

            // 종단기호 게저
            string Text = richTextBox1.Text.Replace("▲", "");

            string[] SplitLine = Text.Split('\n');

            switch (TabIndex)
            {
                case 0:     // 칸채우기 -> 메모장
                    InputMemo(SplitLine);
                    st.Color_change("▼", richTextBox1);
                    st.Color_change("▲", richTextBox1);
                    break;
                case 1:     // 메모장 -> 칸채우기
                    // 칸을 채우기 전에 텍스트박스와 그리드뷰를 비움.
                    TextReset(false);
                    foreach (string Line in SplitLine)
                    {
                        if (Line == "") break;

                        // [0]:태그번호, [1]:지시기호, [2]:마크내용
                        string[] SplitTag = Line.Split('\t');
                        InputTotal(SplitTag);
                    }
                    break;
            }
        }

        #region 칸채우기 SUB

        /// <summary>
        /// 칸채우기에 값을 집어넣는 함수
        /// </summary>
        /// <param name="SplitTag">[0]:태그번호, [1]:지시기호, [2]:마크내용</param>
        public void InputTotal(string[] SplitTag)
        {
            string TagNum = SplitTag[0];
            string Jisi = SplitTag[1];
            string Marc = SplitTag[2];

            if (TagNum == "020") Grid020(Marc);
            if (TagNum == "041") Text041(Marc);
            if (TagNum == "056") Text056(Marc);
            if (TagNum == "082") Text082(Marc);
            if (TagNum == "100" || TagNum == "110" || TagNum == "111") Text100(Marc, TagNum);
            if (TagNum == "245") Text245(Marc);
            if (TagNum == "246") Grid246(Jisi, Marc);
            if (TagNum == "250") InputOneTextBox(text250a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "260") Text260(Marc);
            if (TagNum == "300") Text300(Marc);
            if (TagNum == "440") Grid440(Marc);
            if (TagNum == "490") Grid490(Marc);
            if (TagNum == "500") InputOneTextBox(text500a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "504") InputOneTextBox(text504a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "505") InputOneTextBox(text505a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "505") Grid505(Marc);
            if (TagNum == "507") Text507(Marc);
            if (TagNum == "520") InputOneTextBox(text520a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "521") InputOneTextBox(text521a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "525") InputOneTextBox(text525a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "536") InputOneTextBox(text536a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "546") InputOneTextBox(text546a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "586") InputOneTextBox(text586a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "650") InputOneTextBox(text650a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "653") InputOneTextBox(text653a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "700") InputOneTextBox(text700a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "710") Text710And910(Marc, TagNum);
            if (TagNum == "900") InputOneTextBox(text900a, GetMiddelString(Marc, "▼a", "▼"));
            if (TagNum == "910") Text710And910(Marc, TagNum);
            if (TagNum == "940") InputOneTextBox(text940a, GetMiddelString(Marc, "▼a", "▼"));
        }

        #region Grid_Input

        /// <summary>
        /// 020Grid에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Grid020(string SplitTag)
        {
            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string g = GetMiddelString(SplitTag, "▼g", "▼");
            string c = GetMiddelString(SplitTag, "▼c", "▼");
            object[] Grid = { false, a, g, c };

            if (a.Contains("세트"))
                Grid[0] = true;

            for (int count = 0; count < GridView020.Rows.Count; count++)
            {
                if (GridView020.Rows[count].Cells["CheckSet"].Value == null &&
                    GridView020.Rows[count].Cells["Text020a"].Value == null &&
                    GridView020.Rows[count].Cells["Text020g"].Value == null &&
                    GridView020.Rows[count].Cells["Text020c"].Value == null)
                {

                    GridView020.Rows[count].Cells["CheckSet"].Value = Grid[0];
                    GridView020.Rows[count].Cells["Text020a"].Value = Grid[1];
                    GridView020.Rows[count].Cells["Text020g"].Value = Grid[2];
                    GridView020.Rows[count].Cells["Text020c"].Value = Grid[3];
                    break;
                }
            }

            //GridView020.Rows.Add(Grid);
        }

        /// <summary>
        /// 246Grid에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Grid246(string Jisi, string SplitTag)
        {
            string i = GetMiddelString(SplitTag, "▼i", "▼");
            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string b = GetMiddelString(SplitTag, "▼b", "▼");
            string n = GetMiddelString(SplitTag, "▼n", "▼");
            string p = GetMiddelString(SplitTag, "▼p", "▼");

            object[] Grid = { Jisi, i, a, b, n, p };
            for (int count = 0; count < GridView246.Rows.Count; count++)
            {
                if (GridView246.Rows[count].Cells["Text246Jisi"].Value == null &&
                    GridView246.Rows[count].Cells["Text246i"].Value == null &&
                    GridView246.Rows[count].Cells["Text246a"].Value == null &&
                    GridView246.Rows[count].Cells["Text246b"].Value == null &&
                    GridView246.Rows[count].Cells["Text246n"].Value == null &&
                    GridView246.Rows[count].Cells["Text246p"].Value == null)
                {

                    GridView246.Rows[count].Cells["Text246Jisi"].Value = Grid[0];
                    GridView246.Rows[count].Cells["Text246i"].Value = Grid[1];
                    GridView246.Rows[count].Cells["Text246a"].Value = Grid[2];
                    GridView246.Rows[count].Cells["Text246b"].Value = Grid[3];
                    GridView246.Rows[count].Cells["Text246n"].Value = Grid[4];
                    GridView246.Rows[count].Cells["Text246p"].Value = Grid[5];
                    break;
                }
            }

            //GridView246.Rows.Add(Grid);
        }

        /// <summary>
        /// 440Grid에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Grid440(string SplitTag)
        {
            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string n = GetMiddelString(SplitTag, "▼n", "▼");
            string p = GetMiddelString(SplitTag, "▼p", "▼");
            string v = GetMiddelString(SplitTag, "▼v", "▼");
            string x = GetMiddelString(SplitTag, "▼x", "▼");

            // string vNum = System.Text.RegularExpressions.Regex.Replace(v, @"[^0-9]", "");
            // string vTxt = System.Text.RegularExpressions.Regex.Replace(v, @"\d", "");

            object[] Grid = { a, n, p, v, "", x };
            for (int count = 0; count < GridView440.Rows.Count; count++)
            {
                if (GridView440.Rows[count].Cells["text440a"].Value == null &&
                    GridView440.Rows[count].Cells["text440n"].Value == null &&
                    GridView440.Rows[count].Cells["text440p"].Value == null &&
                    GridView440.Rows[count].Cells["text440vNum"].Value == null &&
                    GridView440.Rows[count].Cells["text440vTxt"].Value == null &&
                    GridView440.Rows[count].Cells["text440x"].Value == null)
                {

                    GridView440.Rows[count].Cells["text440a"].Value = Grid[0];
                    GridView440.Rows[count].Cells["text440n"].Value = Grid[1];
                    GridView440.Rows[count].Cells["text440p"].Value = Grid[2];
                    GridView440.Rows[count].Cells["text440vNum"].Value = Grid[3];
                    GridView440.Rows[count].Cells["text440vTxt"].Value = Grid[4];
                    GridView440.Rows[count].Cells["text440x"].Value = Grid[5];
                    break;
                }
            }

            //GridView440.Rows.Add(Grid);
        }

        /// <summary>
        /// 490Grid에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Grid490(string SplitTag)
        {
            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string v = GetMiddelString(SplitTag, "▼v", "▼");

            object[] Grid = { a, v };
            for (int count = 0; count < GridView490.Rows.Count; count++)
            {
                if (GridView490.Rows[count].Cells["text490a"].Value == null &&
                    GridView490.Rows[count].Cells["text490v"].Value == null)
                {
                    GridView490.Rows[count].Cells["text490a"].Value = Grid[0];
                    GridView490.Rows[count].Cells["text490v"].Value = Grid[1];
                    break;
                }
            }

            //GridView490.Rows.Add(Grid);
        }

        /// <summary>
        /// 505Grid에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Grid505(string SplitTag)
        {
            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string n = GetMiddelString(SplitTag, "▼n", "▼");
            string t = GetMiddelString(SplitTag, "▼t", "▼");
            string d = GetMiddelString(SplitTag, "▼d", "▼");
            string e = GetMiddelString(SplitTag, "▼e", "▼");

            // object[] Grid = { n, t, d, e };
            // for (int count = 0; count < GridView505.Rows.Count; count++)
            // {
            //     if (GridView505.Rows[count].Cells["text505n"].Value == null &&
            //         GridView505.Rows[count].Cells["text505t"].Value == null &&
            //         GridView505.Rows[count].Cells["text505d"].Value == null &&
            //         GridView505.Rows[count].Cells["text505e"].Value == null)
            //     {
            // 
            //         GridView505.Rows[count].Cells["text505n"].Value = Grid[0];
            //         GridView505.Rows[count].Cells["text505t"].Value = Grid[1];
            //         GridView505.Rows[count].Cells["text505d"].Value = Grid[2];
            //         GridView505.Rows[count].Cells["text505e"].Value = Grid[3];
            //         break;
            //     }
            // }

            InputGrid505(SplitTag);
            //GridView505.Rows.Add(Grid);
            text505a.Text = a;
        }


        private void InputGrid505(string Tag505)
        {
            string[] Split505 = Tag505.Split('▼');

            string[] grid = { "", "", "", "" };     // n t d e
            string[] clear = { "", "", "", "" };
            char[] Symbol = { 'n', 't', 'd', 'e' };
            int row = 0;
            int Before = -1;
            int After = -1;

            foreach (string Tag in Split505)
            {
                if (Tag == "") continue;
                Before = After;
                for (int a = 0; a < Symbol.Length; a++)
                {
                    if (Tag[0] == Symbol[a])
                    {
                        After = a;
                        break;
                    }
                }

                if (Before >= After)
                    row++;

                GridView505.Rows[row].Cells[After].Value = Tag.TrimStart(Symbol);
            }

        }
        #endregion

        #region Text_Input

        /// <summary>
        /// 041Text에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag">마크데이터</param>
        private void Text041(string SplitTag)
        {
            TextBox[] Text = {
                text041a, text041k, text041h, text041b
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string k = GetMiddelString(SplitTag, "▼k", "▼");
            string h = GetMiddelString(SplitTag, "▼h", "▼");
            string b = GetMiddelString(SplitTag, "▼b", "▼");

            string[] Marc = { a, k, h, b };

            InputMoreTextBox(Text, Marc);
        }

        /// <summary>
        /// 100Text에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag">마크데이터</param>
        private void Text100(string SplitTag, string TagNum)
        {
            TextBox Text = basicHeadBox;

            RadioButton[] rbtn = { rbtn_100, rbtn_110, rbtn_111 };

            if (TagNum == "100")
                rbtn[0].Checked = true;
            if (TagNum == "110")
                rbtn[1].Checked = true;
            if (TagNum == "111")
                rbtn[2].Checked = true;

            string a = GetMiddelString(SplitTag, "▼a", "▼");

            InputOneTextBox(Text, a);
        }

        /// <summary>
        /// 056Text에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Text056(string SplitTag)
        {
            TextBox[] Text = {
                textKDC4, textKDC5, textKDC6
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string num = GetMiddelString(SplitTag, "▼2", "▼");

            int TextCount;
            switch (num)
            {
                case "4":
                    TextCount = 0;
                    break;
                case "5":
                    TextCount = 1;
                    break;
                case "6":
                    TextCount = 2;
                    break;
                default:
                    TextCount = 1;
                    break;
            }

            Text[TextCount].Text = a;
        }

        /// <summary>
        /// 082Text에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Text082(string SplitTag)
        {
            TextBox[] Text = {
                textDDC21, textDDC22, textDDC23
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string num = GetMiddelString(SplitTag, "▼2", "▼");

            int TextCount;
            switch (num)
            {
                case "21":
                    TextCount = 0;
                    break;
                case "22":
                    TextCount = 1;
                    break;
                case "23":
                    TextCount = 2;
                    break;
                default:
                    TextCount = 1;
                    break;
            }

            Text[TextCount].Text = a;
        }

        /// <summary>
        /// 245Text에 적용하는 함수
        /// </summary>
        /// <param name="SplitTag"></param>
        private void Text245(string SplitTag)
        {
            TextBox[] Text = {
                text245a, text245b, text245x, text245n, text245p,
                text245d, text245e
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼", "245a");
            string b = GetMiddelString(SplitTag, "▼b", "▼");
            string x = GetMiddelString(SplitTag, "▼x", "▼");
            string n = GetMiddelString(SplitTag, "▼n", "▼");
            string p = GetMiddelString(SplitTag, "▼p", "▼");
            string d = GetMiddelString(SplitTag, "▼d", "▼", "245");
            string e = GetMiddelString(SplitTag, "▼e", "▼", "245");

            string[] Marc = {
                a, b, x, n, p,
                d, e
            };

            InputMoreTextBox(Text, Marc);
        }

        private void Text260(string SplitTag)
        {
            TextBox[] Text = {
                text260a, text260b, text260c, text260g
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string b = GetMiddelString(SplitTag, "▼b", "▼");
            string c = GetMiddelString(SplitTag, "▼c", "▼");
            string g = GetMiddelString(SplitTag, "▼g", "▼");

            string[] Marc = { a, b, c, g };

            InputMoreTextBox(Text, Marc);
        }

        private void Text300(string SplitTag)
        {
            TextBox[] Text = {
                text300a, text300b, text300c1, text300c2, text300e
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼", "300a");
            string b = GetMiddelString(SplitTag, "▼b", "▼", "300");
            string c = GetMiddelString(SplitTag, "▼c", "▼");
            string e = GetMiddelString(SplitTag, "▼e", "▼");

            string[] size = { "", "" };
            string[] size_tmp = c.ToUpper().Split('X');

            size[0] = Regex.Replace(size_tmp[0], @"[^0-9]", "");
            if (size_tmp.Length > 1)
                size[1] = Regex.Replace(size_tmp[1], @"[^0-9]", "");

            string[] Marc = { a, b, size[0], size[1], e };

            InputMoreTextBox(Text, Marc);
        }

        private void Text507(string SplitTag)
        {
            TextBox[] Text = {
                text507a, text507t
            };

            string a = GetMiddelString(SplitTag, "▼a", "▼");
            string t = GetMiddelString(SplitTag, "▼t", "▼");

            string[] Marc = { a, t };

            InputMoreTextBox(Text, Marc);
        }

        private void Text710And910(string SplitTag, string TagNum)
        {
            TextBox[] box = { text710a, text910a };

            string a = GetMiddelString(SplitTag, "▼a", "▲", TagNum);

            a = a.Replace(".▼", "▼");
            a = a.Replace("▼b", "@");

            // int count = a.IndexOf("▼");
            // if (count > -1)
            // {
            //     a = a.Remove(count, 2);
            //     if (a[count - 1] != '.')
            //         a = a.Insert(count, ".");
            // }

            if (TagNum == "710")
                InputOneTextBox(box[0], a);

            if (TagNum == "910")
                InputOneTextBox(box[1], a);
        }

        /// <summary>
        /// 여러 텍스트박스에 값을 입력.
        /// </summary>
        /// <param name="Box">텍스트박스 배열</param>
        /// <param name="Marc">텍스트박스에 들어갈 값 배열</param>
        private void InputMoreTextBox(TextBox[] box, string[] Marc)
        {
            int count = 0;

            foreach (string marc in Marc)
            {
                if (box[count].Text == "")
                    box[count].Text = marc;

                else
                    box[count].Text += "▽" + marc;

                count++;
            }
        }

        /// <summary>
        /// 단일 텍스트박스에 값을 입력
        /// </summary>
        /// <param name="box">입력할 텍스트박스</param>
        /// <param name="marc">텍스트박스에 들어갈 값</param>
        private void InputOneTextBox(TextBox box, string marc)
        {
            if (box.Text == "")
            {
                box.Text = marc;
            }
            else
            {
                box.Text += "▽" + marc;
            }
        }
        #endregion


        /// <summary>
        /// 문자와 문자사이의 값 가져오기
        /// </summary>
        /// <param name="str">대상 문자열</param>
        /// <param name="begin">시작 문자열</param>
        /// <param name="end">마지막 문자열</param>
        /// <param name="TagNum">불러올 태그 번호</param>
        /// <returns>문자 사이값</returns>
        // public string GetMiddelString(string str, string begin, string end, string TagNum = "")
        // {
        //     string result = "";
        // 
        //     if (string.IsNullOrEmpty(str) || str == "")
        //         return result;
        // 
        //     int count = 0;
        //     bool loop = false;
        // 
        //     for (int a = count; a < str.Length; a++)
        //     {
        //         count = str.IndexOf(begin);
        //         if (count > -1)
        //         {
        //             str = str.Substring(count + begin.Length);
        //             if (loop)
        //                 // 여러 태그들 구분을 지어줌.
        //                 result += "▽";
        // 
        //             if (str.IndexOf(end) > -1)
        //                 result += str.Substring(0, str.IndexOf(end));
        //             else
        //                 result += str;
        // 
        //             result = TrimEndGubun(result, TagNum);
        //         }
        //         else
        //             break;
        // 
        //         loop = true;
        //     }
        // 
        //     return result;
        // }
        // 
        // string TrimEndGubun(string str, string TagNum)
        // {
        // 
        //     if (TagNum == "300")
        //     {
        //         str = str.Trim();
        //         if (str.Contains("ill."))
        //             return str;
        //         if (str.Contains("p."))
        //             return str;
        //     }
        // 
        //     if (TagNum == "710" || TagNum == "910")
        //         return str;
        // 
        //     char[] gu = { '.', ',', ':', ';', '/' };
        // 
        //     foreach (char gubun in gu)
        //     {
        //         if (str.Length < 1) continue;
        //         if (str[str.Length - 1] == gubun)
        //         {
        //             str = str.Remove(str.Length - 1);
        //             str = str.Trim();
        //         }
        //     }
        // 
        //     return str;
        // }
        #endregion

        #region 메모장 채우기 SUB

        /// <summary>
        /// 메모장 채우기
        /// </summary>
        /// <param name="SplitTag">메모장에 있는 값<br>[0]:태그번호, [1]:지시기호, [2]:마크내용</br></param>
        private void InputMemo(string[] SplitTag)
        {
            string[] Tag =
            {
                "020", "041", "056", "082", "100",
                "110", "111", "245", "246", "250",
                "260", "300", "440", "490", "500",
                "504", "505", "507", "520", "521",
                "525", "536", "546", "586", "650",
                "653", "700", "710", "900", "910",
                "940"
            };

            List<string> RemainTag = new List<string>();    // 메모장으로 출력되는 최종 리스트

            List<string> BlankTag = MakeMarcLine();         // 칸채우기의 값들이 여기로 저장이 되어 들어옴
            List<string> TextTag = SplitTag.ToList();       // 칸채우기에 없는 값들이 여기로 저장되어있음.
            List<string> AllTag = new List<string>();       // 칸채우기와 나머지 값들을 짱뽕시킨 짬통 리스트
            AllTag.AddRange(BlankTag);
            AllTag.AddRange(TextTag);
            AllTag.Sort();
            AllTag.RemoveAll(x => x.Length < 3 || x == "");
            for (int i = 0; i < AllTag.Count; i++)
            {
                string tTagNum = AllTag[i].Substring(0, 3);
                bool isCopy = false;
                List<string> tTag = Tag.ToList();
                List<string> tFindTag = tTag.FindAll(x => x == tTagNum);
                if (tFindTag.Count > 0) isCopy = true;

                if (isCopy)
                {
                    string AddText = "";
                    BlankTag.RemoveAll(x => x.Length < 4 || x == "");
                    for (int j = 0; j < BlankTag.Count; j++)
                    {
                        string StrNum = BlankTag[j].Substring(0, 3);
                        int Num = Convert.ToInt32(StrNum);
                        int tagNumInt = Convert.ToInt32(tTagNum);

                        if (Num == tagNumInt)
                        {
                            AddText = BlankTag[j].Replace("\n", "");
                            AddText = AddText.Replace("▲", "▲\n");

                            break;
                        }
                    }
                    if (AddText == "")
                        continue;
                    if (AddText.Substring(AddText.Length - 1, 1) == "\n")
                        AddText = AddText.Substring(0, AddText.Length - 1);
                    RemainTag.Add(AddText);
                }
                else
                {
                    if (tTagNum == "950")
                    {
                        List<string> tFindTag020 = RemainTag.FindAll(x => x.Substring(0, 3) == "020").FindAll(x => x.Contains("▼c")).Distinct().ToList();
                        if (tFindTag020.Count == 0) continue;
                        int tStartIDX = tFindTag020[0].IndexOf("▼c") + 2;
                        int tEndIDX = tFindTag020[0].IndexOf("▼", tStartIDX + 1);
                        if (tEndIDX == -1) tEndIDX = tFindTag020[0].IndexOf("▲", tStartIDX - 1);
                        else continue;
                        string tTagText020 = tFindTag020[0].Substring(tStartIDX, tEndIDX - tStartIDX);

                        tStartIDX = AllTag[i].IndexOf("▼b") + 2;
                        tEndIDX = AllTag[i].IndexOf("▼", tStartIDX + 1);
                        if (tEndIDX == -1) tEndIDX = AllTag[i].IndexOf("▲", tStartIDX - 1);
                        if (tEndIDX == -1) tEndIDX = AllTag[i].Length;

                        AllTag[i] = AllTag[i].Remove(tStartIDX, tEndIDX - tStartIDX);
                        string tNewText = string.Format("{0}{1}", AllTag[i], tTagText020);
                        tNewText.TrimEnd('\n');
                        RemainTag.Add(tNewText + "▲");
                    }
                    else
                    {
                        AllTag[i].TrimEnd('\n');
                        RemainTag.Add(AllTag[i] + "▲");
                    }
                }
            }
            //AllTag.Sort();

            //foreach (string Content in AllTag)
            //{
            //    if (Content == "")
            //        continue;

            //    if (Content.Length < 3)
            //        continue;

            //    string tagNum = Content.Substring(0, 3);
            //    bool isCopy = false;

            //    foreach (string Num in Tag)
            //    {
            //        if (tagNum == Num)
            //        {
            //            isCopy = true;
            //            break;
            //        }
            //    }

            //    if (isCopy)
            //    {
            //        string AddText = "";

            //        foreach (string Blank in BlankTag)
            //        {
            //            if (Blank.Length < 4)
            //                continue;

            //            string StrNum = Blank.Substring(0, 3);
            //            int Num = Convert.ToInt32(StrNum);
            //            int tagNumInt = Convert.ToInt32(tagNum);

            //            if (Num == tagNumInt)
            //            {
            //                AddText = Blank.Replace("\n", "");
            //                AddText = AddText.Replace("▲", "▲\n");
            //                break;
            //            }
            //        }
            //        if (AddText == "")
            //            continue;

            //        if (AddText.Substring(AddText.Length - 1, 1) == "\n")
            //            AddText = AddText.Substring(0, AddText.Length - 1);

            //        RemainTag.Add(AddText);
            //    }
            //    else
            //    {
            //        Content.TrimEnd('\n');
            //        RemainTag.Add(Content + "▲");
            //    }
            //}

            RemainTag = RemainTag.Distinct().ToList();


            richTextBox1.Text = string.Join("\n", RemainTag) + "\n";
        }

        /// <summary>
        /// 칸채우기에 채워진 값들을 메모장 형식으로 변환하여 반환
        /// </summary>
        /// <returns></returns>
        private List<string> MakeMarcLine()
        {
            List<string> LineMarc = new List<string>();

            string[] Tag = {
                "020", "041", "056", "082", "100",
                "110", "111", "245", "246", "250",
                "260", "300", "440", "490", "500",
                "504", "505", "507", "520", "521",
                "525", "536", "546", "586", "650",
                "653", "700", "710", "900", "910",
                "940"
            };

            string[] GridTag = {
                "020", "246", "440", "490", "505"
            };

            string[] TextTag = {
                "041", "056", "082", "100", "110",
                "111", "245", "250", "260", "300",
                "500", "505", "504", "507", "520",
                "521", "525", "536", "546", "586",
                "650", "653", "700", "710", "900",
                "910", "940"
            };

            foreach (string TagNum in Tag)
            {
                bool isGrid = false;
                bool isText = false;

                foreach (string Grid in GridTag)
                {
                    if (TagNum == Grid)
                    {
                        isGrid = true;
                        break;
                    }
                }
                foreach (string Text in TextTag)
                {
                    if (TagNum == Text)
                    {
                        isText = true;
                        break;
                    }
                }

                if (isGrid)
                    LineMarc.Add(GridMarc(TagNum));

                if (isText)
                    LineMarc.Add(TextMarc(TagNum));
            }

            return LineMarc;
        }

        #region GridInsert부분
        private string GridMarc(string Tag)
        {
            DataGridView[] dgvNum = { GridView020, GridView246, GridView440, GridView490, GridView505 };
            string result = "";

            switch (Tag)
            {
                case "020": result = Grid020Insert(dgvNum[0]); break;
                case "246": result = Grid246Insert(dgvNum[1]); break;
                case "440": result = Grid440Insert(dgvNum[2]); break;
                case "490": result = Grid490Insert(dgvNum[3]); break;
                case "505": result = Grid505Insert(dgvNum[4]); break;
                default:
                    break;
            }

            return result;
        }

        private string Grid020Insert(DataGridView dgv)
        {
            string Insert020Sub(string Check)
            {
                string res = "  ";
                if (Check == "True")
                    res = "1 ";
                return res;
            }
            int count = dgv.Rows.Count - 1;
            string result = "";

            for (int a = 0; a < count; a++)
            {
                if (dgv.Rows[a].Cells["Text020a"].Value == null)
                    break;

                string CheckSet;
                if (dgv.Rows[a].Cells["CheckSet"].Value == null)
                    CheckSet = "";
                else
                    CheckSet = dgv.Rows[a].Cells["CheckSet"].Value.ToString();

                string a020;
                if (dgv.Rows[a].Cells["Text020a"].Value == null)
                    a020 = "";
                else
                    a020 = dgv.Rows[a].Cells["Text020a"].Value.ToString();

                string g020;
                if (dgv.Rows[a].Cells["Text020g"].Value == null)
                    g020 = "";
                else
                    g020 = dgv.Rows[a].Cells["Text020g"].Value.ToString();

                string c020;
                if (dgv.Rows[a].Cells["Text020c"].Value == null)
                    c020 = "";
                else
                    c020 = dgv.Rows[a].Cells["Text020c"].Value.ToString();

                result += string.Format("020\t{0}\t▼a{1}", Insert020Sub(CheckSet), a020);

                if (g020 != "")
                    result += "▼g" + g020;

                if (c020 != "")
                    result += "▼c" + c020;

                result += "▲\n";
            }

            return result;
        }

        private string Grid246Insert(DataGridView dgv)
        {
            int count = dgv.Rows.Count - 1;
            string result = "";

            for (int a = 0; a < count; a++)
            {
                if (dgv.Rows[a].Cells[0].Value == null)
                    break;

                string Jisi;
                if (dgv.Rows[a].Cells["Text246Jisi"].Value == null)
                    Jisi = "";
                else
                    Jisi = dgv.Rows[a].Cells["Text246Jisi"].Value.ToString();

                string a246;
                if (dgv.Rows[a].Cells["Text246a"].Value == null)
                    a246 = "";
                else
                    a246 = dgv.Rows[a].Cells["Text246a"].Value.ToString();

                string b246;
                if (dgv.Rows[a].Cells["Text246b"].Value == null)
                    b246 = "";
                else
                    b246 = dgv.Rows[a].Cells["Text246b"].Value.ToString();

                string i246;
                if (dgv.Rows[a].Cells["Text246i"].Value == null)
                    i246 = "";
                else
                    i246 = dgv.Rows[a].Cells["Text246i"].Value.ToString();

                string n246;
                if (dgv.Rows[a].Cells["Text246n"].Value == null)
                    n246 = "";
                else
                    n246 = dgv.Rows[a].Cells["Text246n"].Value.ToString();

                string p246;
                if (dgv.Rows[a].Cells["Text246p"].Value == null)
                    p246 = "";
                else
                    p246 = dgv.Rows[a].Cells["Text246p"].Value.ToString();


                result += string.Format("246\t{0}\t", Jisi);

                if (i246 != "") result += "▼i" + i246;
                if (a246 != "") result += "▼a" + a246;
                if (b246 != "") result += "▼b" + b246;
                if (n246 != "") result += "▼n" + n246;
                if (p246 != "") result += "▼p" + p246;

                result += "▲\n";
            }
            return result;
        }

        private string Grid440Insert(DataGridView dgv)
        {
            int count = dgv.Rows.Count - 1;
            string result = "";

            for (int a = 0; a < count; a++)
            {
                if (dgv.Rows[a].Cells[0].Value == null)
                    break;

                for (int b = 0; b < dgv.ColumnCount; b++)
                {
                    if (dgv.Rows[a].Cells[b].Value == null)
                        dgv.Rows[a].Cells[b].Value = "";
                }

                string a440;
                if (dgv.Rows[a].Cells["text440a"].Value == null)
                    a440 = "";
                else
                    a440 = dgv.Rows[a].Cells["text440a"].Value.ToString();

                string n440;
                if (dgv.Rows[a].Cells["text440n"].Value == null)
                    n440 = "";
                else
                    n440 = dgv.Rows[a].Cells["text440n"].Value.ToString();

                string p440;
                if (dgv.Rows[a].Cells["text440p"].Value == null)
                    p440 = "";
                else
                    p440 = dgv.Rows[a].Cells["text440p"].Value.ToString();

                string v440Num;
                if (dgv.Rows[a].Cells["text440vNum"].Value == null)
                    v440Num = "";
                else
                    v440Num = dgv.Rows[a].Cells["text440vNum"].Value.ToString();

                string v440Txt;
                if (dgv.Rows[a].Cells["text440vTxt"].Value == null)
                    v440Txt = "";
                else
                    v440Txt = dgv.Rows[a].Cells["text440vTxt"].Value.ToString();

                string x440;
                if (dgv.Rows[a].Cells["text440x"].Value == null)
                    x440 = "";
                else
                    x440 = dgv.Rows[a].Cells["text440x"].Value.ToString();


                result += string.Format("440\t  \t▼a{0}", a440);

                if (n440 != "") result += "▼n" + n440;
                if (p440 != "") result += "▼p" + p440;
                if (v440Num != "") result += "▼v" + v440Num + v440Txt;
                if (x440 != "") result += "▼x" + x440;

                result += "▲\n";
            }

            return result;
        }

        private string Grid490Insert(DataGridView dgv)
        {
            int count = dgv.Rows.Count - 1;
            string result = "";

            for (int a = 0; a < count; a++)
            {
                if (dgv.Rows[a].Cells[0].Value == null)
                    break;

                string a490;
                if (dgv.Rows[a].Cells["text490a"].Value == null)
                    a490 = "";
                else
                    a490 = dgv.Rows[a].Cells["text490a"].Value.ToString();

                string v490;
                if (dgv.Rows[a].Cells["text490v"].Value == null)
                    v490 = "";
                else
                    v490 = dgv.Rows[a].Cells["text490v"].Value.ToString();

                result += string.Format("490\t  \t▼a{0}", a490);

                if (v490 != "") result += "▼v" + v490;

                result += "▲\n";
            }

            return result;
        }

        private string Grid505Insert(DataGridView dgv)
        {
            int count = dgv.Rows.Count - 1;
            string result = "";

            for (int a = 0; a < count; a++)
            {
                if (dgv.Rows[a].Cells[1].Value == null)
                    break;

                string n505;
                if (dgv.Rows[a].Cells["text505n"].Value == null)
                    n505 = "";
                else
                    n505 = dgv.Rows[a].Cells["text505n"].Value.ToString();

                string t505;
                if (dgv.Rows[a].Cells["text505t"].Value == null)
                    t505 = "";
                else
                    t505 = dgv.Rows[a].Cells["text505t"].Value.ToString();

                string d505;
                if (dgv.Rows[a].Cells["text505d"].Value == null)
                    d505 = "";
                else
                    d505 = dgv.Rows[a].Cells["text505d"].Value.ToString();

                string e505;
                if (dgv.Rows[a].Cells["text505e"].Value == null)
                    e505 = "";
                else
                    e505 = dgv.Rows[a].Cells["text505e"].Value.ToString();

                if (n505 != "") result += "▼n" + n505;
                if (t505 != "") result += "▼t" + t505;
                if (d505 != "") result += "▼d" + d505;
                if (e505 != "") result += "▼e" + e505;

                if (a == count - 1)
                    result += "▲\n";
            }

            if (result != "")
                result = string.Format("505\t 0\t") + result;

            return result;
        }

        #endregion

        #region TextInsert부분

        private string TextMarc(string tag)
        {
            string result = "";
            //"▼" "▲";

            switch (tag)
            {
                case "041": result = Text041Insert(); break;
                case "056": result = Text056Insert(); break;
                case "082": result = Text082Insert(); break;
                case "100": result = Text100Insert(tag); break;
                case "110": result = Text100Insert(tag); break;
                case "111": result = Text100Insert(tag); break;
                case "245": result = Text245Insert(); break;
                case "250": result = Text250Insert(); break;
                case "260": result = Text260Insert(); break;
                case "300": result = Text300Insert(); break;
                case "500": result = Text500Insert(); break;
                case "504": result = Text504Insert(); break;
                case "505": result = Text505Insert(); break;
                case "507": result = Text507Insert(); break;
                case "520": result = Text520Insert(); break;
                case "521": result = Text521Insert(); break;
                case "525": result = Text525Insert(); break;
                case "536": result = Text536Insert(); break;
                case "546": result = Text546Insert(); break;
                case "586": result = Text586Insert(); break;
                case "650": result = Text650Insert(); break;
                case "653": result = Text653Insert(); break;
                case "700": result = Text700Insert(); break;
                case "710": result = Text710Insert(); break;
                case "900": result = Text900Insert(); break;
                case "910": result = Text910Insert(); break;
                case "940": result = Text940Insert(); break;
            }

            return result;
        }

        private string Text041Insert()
        {
            string[] boxText = { text041a.Text, text041b.Text, text041h.Text, text041k.Text };

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = "041\t  \t";

            if (boxText[0] != "") result += "▼a" + boxText[0].Replace("▽", "▼a");
            if (boxText[1] != "") result += "▼b" + boxText[1];
            if (boxText[2] != "") result += "▼h" + boxText[2].Replace("▽", "▼h");
            if (boxText[3] != "") result += "▼k" + boxText[3];

            result += "▲";

            return result;
        }

        private string Text056Insert()
        {
            string[] boxText = { textKDC4.Text, textKDC5.Text, textKDC6.Text };

            bool isText = isEmpty(boxText);
            string result = "";
            if (!isText)
                return "";

            if (boxText[0] != "")
                result += string.Format("056\t  \t▼a{0}▼2{1}▲", boxText[0], "4");
            if (boxText[1] != "")
                result += string.Format("056\t  \t▼a{0}▼2{1}▲", boxText[1], "5");
            if (boxText[2] != "")
                result += string.Format("056\t  \t▼a{0}▼2{1}▲", boxText[2], "6");

            return result;
        }

        private string Text082Insert()
        {
            string[] boxText = { textDDC21.Text, textDDC22.Text, textDDC23.Text };

            bool isText = isEmpty(boxText);
            string result = "";
            if (!isText)
                return "";

            if (boxText[0] != "")
                result += string.Format("082\t  \t▼a{0}▼2{1}▲", boxText[0], "21");
            if (boxText[1] != "")
                result += string.Format("082\t  \t▼a{0}▼2{1}▲", boxText[1], "22");
            if (boxText[2] != "")
                result += string.Format("082\t  \t▼a{0}▼2{1}▲", boxText[2], "23");

            return result;
        }

        private string Text100Insert(string TagNum)
        {
            string boxText = basicHeadBox.Text;

            bool isText;
            if (boxText == "")
                isText = false;
            else
                isText = true;

            if (!isText)
                return "";

            string result = "";

            string[] splitText = boxText.Split('▽');

            if (TagNum == "100" && rbtn_100.Checked)
                result = string.Format("{0}\t  \t▼a{1}", TagNum, splitText[0]);
            if (TagNum == "110" && rbtn_110.Checked)
                result = string.Format("{0}\t  \t▼a{1}", TagNum, splitText[0]);
            if (TagNum == "111" && rbtn_111.Checked)
                result = string.Format("{0}\t  \t▼a{1}", TagNum, splitText[0]);

            result += "▲";

            return result;
        }

        private string Text245Insert()
        {
            string[] boxText = {
                text245a.Text, text245n.Text, text245p.Text, text245b.Text, text245x.Text , text245d.Text, text245e.Text };

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = "245\t  \t";

            if (boxText[0] != "") result += "▼a" + boxText[0];
            if (boxText[1] != "") result += "▼n" + boxText[1];
            if (boxText[3] != "")
            {
                string[] splitText245b = boxText[3].Split('▽');
                foreach (string text in splitText245b)
                    result += "▼b" + text;

            }
            if (boxText[2] != "") result += "▼p" + boxText[2];
            if (boxText[4] != "") result += "▼x" + boxText[4];
            if (boxText[5] != "") result += "▼d" + boxText[5];
            if (boxText[6] != "") result += "▼e" + boxText[6].Replace("▽", "▼e");

            result += "▲";

            return result;
        }

        private string Text250Insert()
        {
            string boxText = text250a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("250\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text260Insert()
        {
            string[] boxText = {
                text260a.Text, text260b.Text, text260c.Text, text260g.Text };

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = "260\t  \t";

            if (boxText[0] != "") result += "▼a" + boxText[0];
            if (boxText[1] != "") result += "▼b" + boxText[1].Replace("▽", "▼b"); ;
            if (boxText[2] != "") result += "▼c" + boxText[2];
            if (boxText[3] != "") result += "▼g" + boxText[3];

            result += "▲";

            return result;
        }

        private string Text300Insert()
        {
            string[] boxText = {
                text300a.Text, text300b.Text, text300c1.Text, text300c2.Text, text300e.Text };

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = "300\t  \t";

            if (boxText[0] != "") result += "▼a" + Tag300a_Sub(boxText[0]);
            if (boxText[1] != "") result += "▼b" + boxText[1];
            if (boxText[2] != "")
            {
                result += "▼c" + boxText[2];
                if (boxText[3] == "") result += "cm";
            }
            if (boxText[3] != "") result += " x " + boxText[3] + "cm";
            if (boxText[4] != "") result += "▼e" + boxText[4];

            result += "▲";

            return result;
        }
        string Tag300a_Sub(string Text)
        {
            string result = Text;

            if (result.IndexOf(", ") > -1)
                return result + " p.";
            if (result.IndexOf("p.p.") > -1 || result.IndexOf("p. p.") > -1)
                return result.Replace("p.p.", "p.").Replace("p. p.", "p.");

            if (Regex.IsMatch(result, @"^[0-9]+$"))
                return result + " p.";

            if (!result.StartsWith("[") && !result.EndsWith("]"))
                return result;
            else if (Regex.IsMatch(GetMiddelString(result, "[", "]"), @"^[0-9]+$"))
            {
                string tTest = GetMiddelString(result, "[", "]");
                return result.Replace("p", "").Trim() + " p."; ;
            }


            return result;
        }
        private string Text500Insert()
        {
            string boxText = text500a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                result += string.Format("500\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text504Insert()
        {
            string boxText = text504a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("504\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text505Insert()
        {
            string boxText = text505a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("505\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text507Insert()
        {
            string[] boxText = {
                text507a.Text, text507t.Text };

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = "507\t  \t";

            if (boxText[0] != "") result += "▼a" + boxText[0];
            if (boxText[1] != "") result += "▼t" + boxText[1];

            result += "▲";

            return result;
        }

        private string Text520Insert()
        {
            string boxText = text520a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("520\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text521Insert()
        {
            string boxText = text521a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("521\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text525Insert()
        {
            string boxText = text525a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("525\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text536Insert()
        {
            string boxText = text536a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("536\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text546Insert()
        {
            string boxText = text546a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("546\t  \t▼a{0}", boxText);

            result += "▲";

            return result;
        }

        private string Text586Insert()
        {
            string boxText = text586a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                result += string.Format("586\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text650Insert()
        {
            string boxText = text650a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                result += string.Format("650\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text653Insert()
        {
            string boxText = text653a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("653\t  \t▼a{0}", boxText.Replace("▽", "▼a"));

            result += "▲";

            return result;
        }

        private string Text700Insert()
        {
            string boxText = text700a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                result += string.Format("700\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text710Insert()
        {
            string boxText = text710a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                if (text.IndexOf("@") > 0)
                    result += string.Format("710\t  \t▼a{0}▲\n", text.Replace("@", "▼b"));
                else
                    result += string.Format("710\t  \t▼a{0}▲\n", text);

            }

            return result;
        }

        private string Text900Insert()
        {
            string boxText = text900a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                result += string.Format("900\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text910Insert()
        {
            string boxText = text910a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string[] splitText = boxText.Split('▽');

            string result = "";

            foreach (string text in splitText)
            {
                if (text.IndexOf("@") > 0)
                    result += string.Format("910\t  \t▼a{0}▲\n", text.Replace("@", "▼b"));
                else
                    result += string.Format("910\t  \t▼a{0}▲\n", text);
            }

            return result;
        }

        private string Text940Insert()
        {
            string boxText = text940a.Text;

            bool isText = isEmpty(boxText);

            if (!isText)
                return "";

            string result = string.Format("940\t  \t▼a{0}\n", boxText);

            result += "▲";

            return result;
        }



        private bool isEmpty(string boxText)
        {
            if (boxText == "")
                return false;
            return true;
        }

        private bool isEmpty(string[] boxText)
        {
            bool[] isText = new bool[boxText.Length];
            int count = 0;
            int chkCount = 0;
            foreach (string Check in boxText)
            {
                if (Check == "")
                    isText[count] = false;
                else
                {
                    isText[count] = true;
                    chkCount++;
                }
                count++;
            }

            if (chkCount == 0)
                return false;

            return true;
        }
        #endregion

        #endregion

        private void Btn_interlock_Click(object sender, EventArgs e)
        {
            // 언어 36
            string[] combo6 = {
                "한국어", "영어", "일본어", "중국어", "독일어어",
                "프랑스어", "러시아어", "스페인어", "이탈리아어", "네덜란드어어",
                "핀란드어", "스웨덴어", "포르투갈어", "노르웨이어", "그리스어",
                "체코어", "폴란드어", "다국어", "말레이시아어", "몽골어",
                "버마어", "베트남어", "슬로베니아어", "아랍어", "아프리카어",
                "에스토니아어", "우즈베키스탄어", "우크라이나어", "티베르어", "타갈로그어",
                "헝가리어"
            };

            string[] combo6_res = {
                "kor", "eng", "jpn", "chi", "ger",
                "fre", "rus", "spa", "ita", "dut",
                "fin", "swe", "por", "nor", "grc",
                "cze", "pol", "mul", "may", "mon",
                "bur", "vie", "slv", "ara", "afr",
                "est", "uzb", "ukr", "mar", "cam",
                "tha", "tur", "tuk", "tlb", "tag",
                "hun"
            };

            string result = "";
            string a041 = text041a.Text;
            string k041 = text041k.Text;
            string h041 = text041h.Text;
            string b041 = text041b.Text;

            int count = 0;
            foreach (string Code in combo6_res)
            {
                a041 = a041.Replace(Code, combo6[count]);
                k041 = k041.Replace(Code, combo6[count]);
                h041 = h041.Replace(Code, combo6[count]);
                b041 = b041.Replace(Code, combo6[count]);
                count++;
            }

            a041 = a041.Replace("▽", ", ");

            // k로 번역된 h 원작을 a로 중역
            if (a041 != "" && k041 != "" && h041 != "")
                result = string.Format("{0}로 번역된 {1} 원작을 {2}로 중역", k041, h041, a041);

            // h 원작을 a로 번역
            else if (a041 != "" && k041 == "" && h041 != "")
                result = string.Format("{0} 원작을 {1}로 번역", h041, a041);

            // 본문은 a1, a2로 혼합수록됨.
            else if (a041.IndexOf(",") > 0)
                result = string.Format("본문은 {0} 혼합수록 됨.", a041);

            text546a.Text = result;
        }

        private void invertCheck_CheckedChanged(object sender, EventArgs e)
        {
            string tmpStr = text245d.Text;

            if (tmpStr[tmpStr.Length - 1] != ',') tmpStr = basic_Replace(tmpStr);
            else tmpStr = tmpStr.Remove(tmpStr.Length - 1);
            basicHeadBox.Text = tmpStr;

            string[] invert = basicHeadBox.Text.Split(' ');

            for (int a = 0; a < invert.Length; a++)
            {
                if (invert[a][invert[a].Length - 1] == ',')
                    invert[a] = invert[a].Substring(0, invert[a].Length - 1);
            }

            try
            {
                for (int a = 0; a < invert.Length; a++)
                {
                    int length = invert[a].Length - 1;
                    if (a == 0)
                    {
                        if (invert[a][length] != ',') invert[a] += ",";
                        basicHeadBox.Text = invert[a] + " ";
                        if (invert[a][length] == ',') invert[a] = invert[a].Substring(0, length);
                    }
                    else
                    {
                        if (invert[a][length] != ',') invert[a] += ",";
                        basicHeadBox.Text += invert[a] + " ";
                        if (invert[a][length] == ',') invert[a] = invert[a].Substring(0, length);
                    }
                }
                int basicLength = basicHeadBox.Text.Length - 1;
                if (basicHeadBox.Text[basicLength] == ' ')
                    basicHeadBox.Text = basicHeadBox.Text.Substring(0, basicLength);

                basicLength = basicHeadBox.Text.Length - 1;
                if (basicHeadBox.Text[basicLength] == ',')
                    basicHeadBox.Text = basicHeadBox.Text.Substring(0, basicLength);
            }
            catch(Exception ex)
            {
                MessageBox.Show("데이터가 올바르지않습니다.\n245d를 확인해주세요.\n" + ex.ToString());
            }
        }
        #region 기본표목 생성 서브 함수

        /// <summary>
        /// 245d에서 " 역할어,"를 잘라내는 함수
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        string basic_Replace(string strValue)
        {
            basicHeadBox.Text = "";
            string result = strValue + ",";
            string[] Role = {"글", "그림", "지음", "글·그림", "편", "엮음", "저", "씀" };
            string[] gl = { "글.그림", "글그림", "그림글", "그림.글" };

            foreach (string target in gl) result = result.Replace(target, "글.그림");
            foreach (string target in Role) result = result.Replace(" " + target + ",", "");

            return result;
        }
        #endregion

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                Skill_Search_Text sst = new Skill_Search_Text();
                switch (e.KeyValue)
                {
                    case 70:        // f
                        string value = "";
                        if (sst.InputBox("찾을 단어를 입력해주세요.", "찾기 (Ctrl+F)", ref value) == DialogResult.OK)
                            st.Color_change(value, richTextBox1);
                        break;
                    case 72:        // h
                        findNchange fnc = new findNchange(this);
                        fnc.Show();
                        break;
                    default:
                        break;
                }
            }

            if (e.KeyCode == Keys.F9) SaveGrade(Keys.F9);
            else if (e.KeyCode == Keys.F10) SaveGrade(Keys.F10);
            else if (e.KeyCode == Keys.F11) SaveGrade(Keys.F11);
            else if (e.KeyCode == Keys.F12) SaveGrade(Keys.F12);

            if (e.KeyCode == Keys.F3) richTextBox1.SelectedText = "▼";
            if (e.KeyCode == Keys.F4) richTextBox1.SelectedText = "▲";
        }

        #region KeyDown_Sub

        /// <summary>
        /// F9 ~ F12로 등급별 저장
        /// </summary>
        /// <param name="key"></param>
        void SaveGrade(Keys key)
        {
            switch (key)
            {
                case Keys.F9:
                    cb_grade.SelectedItem = "A (F9)";
                    btn_Save_Click(null, null);
                    break;
                case Keys.F10:
                    cb_grade.SelectedItem = "B (F10)";
                    btn_Save_Click(null, null);
                    break;
                case Keys.F11:
                    cb_grade.SelectedItem = "C (F11)";
                    btn_Save_Click(null, null);
                    break;
                case Keys.F12:
                    cb_grade.SelectedItem = "D (F12)";
                    btn_Save_Click(null, null);
                    break;
            }
        }
        #endregion

        private void FillTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;

            if (e.Alt && e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
            {
                var letter = e.KeyCode.ToString().ToLower();
                tb.InvokeInsertText("▽" + letter);
                e.SuppressKeyPress = true;
                return;
            }

            if (e.KeyCode == Keys.F3)
            {
                tb.InvokeInsertText("▽");
            }
            else if (e.KeyCode == Keys.F4)
            {
                tb.InvokeInsertText("△");
            }
        }
        private void etc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                ((RichTextBox)sender).Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            }
        }

        private void Btn_SearchKolis_Click(object sender, EventArgs e)
        {
            AddMarc_FillBlank af = new AddMarc_FillBlank(this);
            af.Show();
        }


    }
}
