//---------------------------------------------------------------------------

#include <vcl.h>
#include <IniFiles.hpp>
#include "ITSDbF.h"
#pragma hdrstop

#include "FrmUtilMainF.h"
#include <stdio.h>
#include <locale.h>

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCheckBox"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxProgressBar"
#pragma link "cxTextEdit"
#pragma link "dxSkinsCore"
#pragma link "dxSkinBlack"
#pragma link "dxSkinMcSkin"
#pragma link "dxmdaset"
#pragma resource "*.dfm"
TFrmUtilMain *FrmUtilMain;
//---------------------------------------------------------------------------

#define     XML_DIR     "\\MAPDATA\\layers\\"

APP_CONFIG       g_AppCfg;

//Provider=tbprov.Tbprov.5;Cache Authentication=False;Encrypt Password=False;Integrated Security="";Mask Password=False;Persist Encrypted=False;Persist Security Info=False;User ID="";Bind Flags=0;Initial Catalog="";Data Source=GMUTIS;Impersonation Level=Anonymous;Location="";Lock Owner="";Mode=ReadWrite;Protection Level=None;Extended Properties="";Updatable Cursor=False;Enlist=None
//Provider=tbprov.Tbprov.5;Cache Authentication=False;Encrypt Password=False;Integrated Security="";Mask Password=False;Persist Encrypted=False;Persist Security Info=False;User ID=itsdev;Bind Flags=0;Initial Catalog="";Data Source=GMUTIS;Impersonation Level=Anonymous;Location="";Lock Owner="";Mode=ReadWrite;Protection Level=None;Updatable Cursor=False;Enlist=None;

bool LoadDefaultConfigInfo(String ACfgFile/*=""*/)
{
    String   sCfgFile;
    TIniFile *pIniFile = NULL;

    g_AppCfg.bAppClose    = false;

    String sAppDir  = ExtractFilePath(Application->ExeName);
    String sCfgDir  = sAppDir + "Cfg\\";
    String sIniFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".ini");
    if (!ACfgFile.IsEmpty())
        sIniFile = ACfgFile + ".ini";

    sCfgFile = sCfgDir + sIniFile;
    String sMapDir = sAppDir + XML_DIR;
    ForceDirectories(sMapDir.c_str());

    try
    {
        String sTmp;

        pIniFile = new TIniFile(sCfgFile);

        String sSqlLog;
        g_AppCfg.itsdb.bSqlLog     = false;
        g_AppCfg.itsdb.sProvider   = pIniFile->ReadString("ITSDB", "PROVIDER",   "OraOLEDB.Oracle.1");
        g_AppCfg.itsdb.sServerName = pIniFile->ReadString("ITSDB", "SERVERNAME", "HANTE");
        g_AppCfg.itsdb.sUserName   = pIniFile->ReadString("ITSDB", "USERNAME",   "hnits");
        g_AppCfg.itsdb.sPassword   = pIniFile->ReadString("ITSDB", "PASSWORD",   "hnits");

        g_AppCfg.link.bSqlLog     = false;
        g_AppCfg.link.sProvider   = pIniFile->ReadString("ITSDB_LINK", "PROVIDER",   "OraOLEDB.Oracle.1");
        g_AppCfg.link.sServerName = pIniFile->ReadString("ITSDB_LINK", "SERVERNAME", "HANTE");
        g_AppCfg.link.sUserName   = pIniFile->ReadString("ITSDB_LINK", "USERNAME",   "hnits");
        g_AppCfg.link.sPassword   = pIniFile->ReadString("ITSDB_LINK", "PASSWORD",   "hnits");

        g_AppCfg.ifsc.bSqlLog     = false;
        g_AppCfg.ifsc.sProvider   = pIniFile->ReadString("ITSDB_IFSC", "PROVIDER",   "OraOLEDB.Oracle.1");
        g_AppCfg.ifsc.sServerName = pIniFile->ReadString("ITSDB_IFSC", "SERVERNAME", "HANTE");
        g_AppCfg.ifsc.sUserName   = pIniFile->ReadString("ITSDB_IFSC", "USERNAME",   "hnits");
        g_AppCfg.ifsc.sPassword   = pIniFile->ReadString("ITSDB_IFSC", "PASSWORD",   "hnits");

        g_AppCfg.road.bSqlLog     = false;
        g_AppCfg.road.sProvider   = pIniFile->ReadString("ITSDB_ROAD", "PROVIDER",   "OraOLEDB.Oracle.1");
        g_AppCfg.road.sServerName = pIniFile->ReadString("ITSDB_ROAD", "SERVERNAME", "HANTE");
        g_AppCfg.road.sUserName   = pIniFile->ReadString("ITSDB_ROAD", "USERNAME",   "hnits");
        g_AppCfg.road.sPassword   = pIniFile->ReadString("ITSDB_ROAD", "PASSWORD",   "hnits");


        String sTemp = g_AppCfg.itsdb.sProvider.UpperCase();
        if (sTemp.Pos("TIBERO"))
        {
            //g_AppCfg.itsdb.sProvider = "bprov.MSDTB.5";
        }

        g_AppCfg.flashmap.sMainMap = pIniFile->ReadString("FLASHMAP", "MAINMAP", "");
        g_AppCfg.flashmap.sLinkMap = pIniFile->ReadString("FLASHMAP", "LINKMAP",  "");

#if 0
        if (g_AppCfg.flashmap.sMainMap == "" ||
            g_AppCfg.flashmap.sLinkMap == "")
        {
            Application->MessageBox(L"지도 설정 정보를 읽어오는데 실패하였습니다.!!!!!!!!!!",
                                    L"환경설정 정보 로딩 오류!!!",
                                    MB_OK|MB_ICONERROR);
        }
#endif
        g_AppCfg.flashmap.sMainMap = sAppDir + g_AppCfg.flashmap.sMainMap;
        g_AppCfg.flashmap.sLinkMap = sAppDir + g_AppCfg.flashmap.sLinkMap;
    }
    __finally
    {
        if (pIniFile) delete pIniFile;
        pIniFile = NULL;
    }

    return true;
}
//---------------------------------------------------------------------------

void DB_CLOSE()
{
    ITSDb_Close();
}
//---------------------------------------------------------------------------
bool DB_OPEN(DB_INFO *ADbInfo)
{
    DB_CLOSE();
    ITSDb_SetInfo(ADbInfo->sProvider, ADbInfo->sServerName, ADbInfo->sUserName, ADbInfo->sPassword);
    if (!ITSDb_Open())
    {
        Application->MessageBox(L"데이터베이스 연결에 실패하였습니다.\r\n환경파일에서 데이터베이스 연결 정보를 확인하세요.",
                                L"데이터베이스 접속 오류!!!",
                                MB_OK|MB_ICONERROR);
        return false;
    }
    return true;
}

__fastcall TFrmUtilMain::TFrmUtilMain(TComponent* Owner)
    : TForm(Owner)
{
    Application->OnException = OnAppException;
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::OnAppException(TObject *Sender, Exception *exception)
{
    String sClassName = (NULL != Sender)        ? Sender->ClassName() : String("Unknown_Class");
    String sErrMsg    = (NULL != exception)     ? exception->Message  : String("Unknown_Error");
    String sError     = sClassName + " : " + sErrMsg;

    //Application->ShowException(&exception);
    //WriteLog(logError, "OnAppException: [%s]", AnsiString(sError).c_str());
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::CommClose()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    //Action = caFree;
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::FormCreate(TObject *Sender)
{
    FOnMessage = Application->OnMessage;
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::FormDestroy(TObject *Sender)
{
    try
    {
        //::OleUninitialize();
        //::CoUninitialize();
    }
    catch(Exception &exception)
    {
        //WriteLog(logError, "FormDestroy: [%s]", AnsiString(exception.ClassName()+exception.Message).c_str());
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::FormShow(TObject *Sender)
{
    Application->ProcessMessages();

    edPath->Text = ExtractFilePath(Application->ExeName) + XML_DIR;
    Refresh();
    Application->ProcessMessages();

    TmrOnShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    // 폼이 닫히기 전에 수행해야 할 모뮬 기술
    // 프로그램 종료를 사용자가 확인할 수 있도록...
	if (!g_AppCfg.bAppClose)
    {
        String strMsg;
        strMsg = "";
        strMsg = "[ " + Caption + " ]\r\n\n";
        strMsg+= "프로그램을 종료 하시겠습니까?";

		//if(Application->MessageBox(strMsg.c_str(), String("프로그램 종료 확인").c_str(), MB_YESNO|MB_ICONQUESTION) == IDYES)
        {
            /*
            *  화면관련 작업을 못하도록 여기에 코드를 적자...
            */
            ITSDb_ApplicationTerm();
			g_AppCfg.bAppClose = true;
        }
        CanClose = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::BtnCloseClick(TObject *Sender)
{
    g_AppCfg.bAppClose = true;
    Close();
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::TmrOnShowTimer(TObject *Sender)
{
    TmrOnShow->Enabled = false;

#if 0
    if (!ITSDb_Open())
    {
        Application->MessageBox(L"데이터베이스 연결에 실패하였습니다.\r\n환경파일에서 데이터베이스 연결 정보를 확인하세요.\r\n\r\n프로그램을 종료합니다.",
                                L"데이터베이스 접속 오류!!!",
                                MB_OK|MB_ICONERROR);
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }
#endif
    TmrAppState->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::TmrAppStateTimer(TObject *Sender)
{
    TmrAppState->Enabled = false;

	if (g_AppCfg.bAppClose)
    {
        ITSDb_Close();
        Close();
        try {
            Application->Terminate();
        } catch(Exception &exception) {}
    }
    else
    {
        TmrAppState->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::UpdateProgress(int AProg, String AMsg/*=""*/)
{
    try {
        cxProgressBar1->Position = AProg;
        if (AMsg != "") LblStatus->Caption = AMsg;
        Application->ProcessMessages();
    } catch(Exception &exception) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::cxButton1Click(TObject *Sender)
{
#if 0
    // 데이터베이스 버텍스 정보 설정
    int        nStep;
    String     sQry;
    TADOQuery *pADO = NULL;

    if (Application->MessageBox(L"데이터베이스 Vertex 정보를 생성하시겠습니까?\r\n기존의 정보가 삭제되고 새로운 정보가 입력됩니다.",
                                L"데이터베이스 Vertex 정보생성", MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES)
    {
        return;
    }
    cxProgressBar1->Properties->Max = 9;
    PnlProg->Left = 16;
    PnlProg->Top  = 304;
    PnlProg->Visible = true;
    cxButton1->Enabled = false;
    cxButton2->Enabled = false;
    try
    {
        pADO = new TADOQuery(NULL);
        ITSDb_GetConnection()->BeginTrans();
        pADO->Connection = ITSDb_GetConnection();

        try {
            nStep = 1;
            UpdateProgress(nStep, cxLabel3->Caption);
            sQry = "DELETE TB_ROAD_VRTX_ARR";
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->ExecSQL();
            LblDb01->Caption = "성공";

sQry = "INSERT INTO TB_ROAD_VRTX_ARR                                                       \r\n"
       "SELECT X.ROAD_ID, X.LEVL, Y.CRDN_CNT, X.X_CRDN_ARR, X.Y_CRDN_ARR,                  \r\n"
       "       Y.X_CRDN_MIN, Y.X_CRDN_MAX, Y.Y_CRDN_MIN, Y.Y_CRDN_MAX                      \r\n"
       "  FROM (SELECT ROAD_ID, :p01 AS LEVL,                                              \r\n"
       "               SUBSTR(MAX(SYS_CONNECT_BY_PATH (X_CRDN, ',')), 2) X_CRDN_ARR,       \r\n"
       "               SUBSTR(MAX(SYS_CONNECT_BY_PATH (Y_CRDN, ',')), 2) Y_CRDN_ARR        \r\n"
       "          FROM (SELECT ROAD_ID, X_CRDN, Y_CRDN,                                    \r\n"
       "                       ROW_NUMBER () OVER (PARTITION BY ROAD_ID ORDER BY ORD) RNUM \r\n"
       "                  FROM (SELECT ROAD_ID, ORD, X_CRDN, Y_CRDN                        \r\n"
       "                          FROM TB_ROAD_VRTX                                        \r\n"
       "                         WHERE LEVL = :p02                                         \r\n"
       "                        )                                                          \r\n"
       "               )                                                                   \r\n"
       "               START WITH RNUM = 1                                                 \r\n"
       "               CONNECT BY PRIOR RNUM = RNUM - 1 AND PRIOR ROAD_ID = ROAD_ID        \r\n"
       "         GROUP BY ROAD_ID) X,                                                      \r\n"
       "      (SELECT ROAD_ID, LEVL, COUNT(1) AS CRDN_CNT,                                 \r\n"
       "              MIN(X_CRDN) AS X_CRDN_MIN, MAX(X_CRDN) AS X_CRDN_MAX,                \r\n"
       "              MIN(Y_CRDN) AS Y_CRDN_MIN, MAX(Y_CRDN) AS Y_CRDN_MAX                 \r\n"
       "         FROM TB_ROAD_VRTX                                                         \r\n"
       "        GROUP BY ROAD_ID, LEVL) Y                                                  \r\n"
       " WHERE X.ROAD_ID = Y.ROAD_ID                                                       \r\n"
       "   AND X.LEVL    = Y.LEVL                                                          \r\n"
       "   AND X.ROAD_ID IN (SELECT ROAD_ID FROM TB_ROAD WHERE DEL_YN = 'N')               \r\n";


            nStep = 2;
            UpdateProgress(nStep, cxLabel4->Caption);
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "1000";
            pADO->Parameters->ParamByName("p02")->Value = "1000";
            pADO->ExecSQL();
            LblDb02->Caption = "성공";

            nStep = 3;
            UpdateProgress(nStep, cxLabel5->Caption);
            //pADO->Close();
            //pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "2000";
            pADO->Parameters->ParamByName("p02")->Value = "2000";
            pADO->ExecSQL();
            LblDb03->Caption = "성공";

            nStep = 4;
            UpdateProgress(nStep, cxLabel6->Caption);
            //pADO->Close();
            //pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "4000";
            pADO->Parameters->ParamByName("p02")->Value = "4000";
            pADO->ExecSQL();
            LblDb04->Caption = "성공";

            nStep = 5;
            UpdateProgress(nStep, cxLabel7->Caption);
            sQry = "DELETE TB_IFSC_VRTX_ARR";
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->ExecSQL();
            LblDb05->Caption = "성공";

sQry = "INSERT INTO TB_IFSC_VRTX_ARR                                                       \r\n"
       "SELECT X.IFSC_ID, X.LEVL, Y.CRDN_CNT, X.X_CRDN_ARR, X.Y_CRDN_ARR,                  \r\n"
       "	   Y.X_CRDN_MIN, Y.X_CRDN_MAX, Y.Y_CRDN_MIN, Y.Y_CRDN_MAX                      \r\n"
       "  FROM (SELECT IFSC_ID, :p01 AS LEVL,                                              \r\n"
       "		       SUBSTR(MAX(SYS_CONNECT_BY_PATH (X_CRDN, ',')), 2) X_CRDN_ARR,       \r\n"
       "		       SUBSTR(MAX(SYS_CONNECT_BY_PATH (Y_CRDN, ',')), 2) Y_CRDN_ARR        \r\n"
       "		  FROM (SELECT IFSC_ID, X_CRDN, Y_CRDN,                                    \r\n"
       "		               ROW_NUMBER () OVER (PARTITION BY IFSC_ID ORDER BY ORD) RNUM \r\n"
       "		          FROM (SELECT IFSC_ID, ORD, X_CRDN, Y_CRDN                        \r\n"
       "		                  FROM TB_IFSC_VRTX                                        \r\n"
       "		                 WHERE LEVL = :p02                                         \r\n"
       "		                )                                                          \r\n"
       " 		       )                                                                   \r\n"
       "		       START WITH RNUM = 1                                                 \r\n"
       "		       CONNECT BY PRIOR RNUM = RNUM - 1 AND PRIOR IFSC_ID = IFSC_ID        \r\n"
       "		 GROUP BY IFSC_ID) X,                                                      \r\n"
       "	  (SELECT IFSC_ID, LEVL, COUNT(1) AS CRDN_CNT,                                 \r\n"
       "              MIN(X_CRDN) AS X_CRDN_MIN, MAX(X_CRDN) AS X_CRDN_MAX,                \r\n"
       "              MIN(Y_CRDN) AS Y_CRDN_MIN, MAX(Y_CRDN) AS Y_CRDN_MAX                 \r\n"
       "         FROM TB_IFSC_VRTX                                                         \r\n"
       "        GROUP BY IFSC_ID, LEVL) Y                                                  \r\n"
       " WHERE X.IFSC_ID = Y.IFSC_ID                                                       \r\n"
       "   AND X.LEVL    = Y.LEVL                                                          \r\n"
       "   AND X.IFSC_ID IN (SELECT IFSC_ID FROM TB_IFSC WHERE DEL_YN = 'N')               \r\n";


            nStep = 6;
            UpdateProgress(nStep, cxLabel8->Caption);
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "50";
            pADO->Parameters->ParamByName("p02")->Value = "50";
            pADO->ExecSQL();
            LblDb06->Caption = "성공";

            nStep = 7;
            UpdateProgress(nStep, cxLabel9->Caption);
            //pADO->Close();
            //pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "100";
            pADO->Parameters->ParamByName("p02")->Value = "100";
            pADO->ExecSQL();
            LblDb07->Caption = "성공";

            nStep = 8;
            UpdateProgress(nStep, cxLabel10->Caption);
            //pADO->Close();
            //pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "250";
            pADO->Parameters->ParamByName("p02")->Value = "250";
            pADO->ExecSQL();
            LblDb08->Caption = "성공";

            nStep = 9;
            UpdateProgress(nStep, cxLabel11->Caption);
            //pADO->Close();
            //pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = "500";
            pADO->Parameters->ParamByName("p02")->Value = "500";
            pADO->ExecSQL();
            LblDb09->Caption = "성공";

            ITSDb_GetConnection()->CommitTrans();

            Application->MessageBox(L"데이터베이스 Vertex 정보를 생성하였습니다.", L"데이터베이스 Vertex 정보생성", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        } catch(Exception &exception) {
            ITSDb_GetConnection()->RollbackTrans();
            switch(nStep)
            {
            case 1: LblDb01->Caption = "실패"; break;
            case 2: LblDb02->Caption = "실패"; break;
            case 3: LblDb03->Caption = "실패"; break;
            case 4: LblDb04->Caption = "실패"; break;
            case 5: LblDb05->Caption = "실패"; break;
            case 6: LblDb06->Caption = "실패"; break;
            case 7: LblDb07->Caption = "실패"; break;
            case 8: LblDb08->Caption = "실패"; break;
            case 9: LblDb09->Caption = "실패"; break;
            }
            String sErrMsg;
            sErrMsg = "데이터베이스 작업중에 오류가 발생 하였습니다.\r\n";
            sErrMsg+= String(exception.ClassName()) + exception.Message;
            Application->MessageBox(sErrMsg.c_str(), L"데이터베이스 Vertex 정보 생성 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }
    }
    __finally
    {
        PnlProg->Visible = false;
        cxButton1->Enabled = true;
        cxButton2->Enabled = true;
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmUtilMain::cxButton2Click(TObject *Sender)
{
    int        nStep;
    String     sQry;
    TADOQuery *pADO = NULL;

    if ((!ChkLinkVertex->Checked) &&
        (!ChkIfscVertex->Checked) &&
        (!ChkRoadVertex->Checked)
        )
    {
        Application->MessageBox(L"작업 대상 정보를 선택하십시요.", L"XML 파일 생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    if (Application->MessageBox(L"선택한 정보의 좌표파일을 신규로 생성하시겠습니까?\r\n기존의 파일은 삭제되고 새로운 파일이 생성됩니다.",
                                L"지도 좌표 파일 생성", MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES)
    {
        return;
    }

    try
    {
        //_wsetlocale(LC_ALL, L"kor");

        cxProgressBar1->Properties->Max = 2;
        PnlProg->Left = 16;
        PnlProg->Top  = 124;
        PnlProg->Visible = true;

        pADO = new TADOQuery(NULL);
        pADO->Connection = ITSDb_GetConnection();

        pADO->CursorLocation = clUseClient;
        pADO->CursorType = ctStatic;//ctOpenForwardOnly;
        pADO->LockType = ltReadOnly;//ltBatchOptimistic;

        pADO->DisableControls();

        if (ChkLinkVertex->Checked) MakeLinkVertexXml(pADO);
        if (ChkIfscVertex->Checked) MakeIfscVertexXml(pADO);
        if (ChkRoadVertex->Checked) MakeRoadVertexXml(pADO);

        Application->MessageBox(L"선택한 정보의 좌표파일 생성을 완료하였습니다.", L"지도 좌표 파일 생성", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
    }
    __finally
    {
        PnlProg->Visible = false;
        cxButton2->Enabled = true;
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeLinkVertexXml(TADOQuery *pADO)
{
    if (DB_OPEN(&g_AppCfg.link) == false)
    {
        return false;
    }
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "LINK.dat";
    AnsiString sFileBackup = ExtractFilePath(Application->ExeName) + XML_DIR+ "LINK_"+Now().FormatString("yyyymmddhhnnss")+".dat";

    try
    {
        CopyFile(String(sFile).c_str(), String(sFileBackup).c_str(), true);   //존재하면 업어쓴다
    }
    catch(Exception &e)
    {
    }

	FILE      *fd    = NULL;

    UpdateProgress(1, "링크 구간좌표 정보 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"링크 구간좌표 정보 파일 파일을 생성하지 못하였습니다.",
                                L"링크 구간좌표 정보 파일 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    int colSize = 4000;
    int divSize = 200;
    int colCount = 0;

    String xCrdnArr = "";
    String yCrdnArr = "";

    String temp;
    int fromIdx = 1;
    for (int ii = 1; ; ii++)
    {
        if (fromIdx > colSize) break;

        temp.printf(L"SUBSTR(A.X_CRDN_ARR, %d, %d) AS XMSG%02d,   \r\n", fromIdx, divSize, ii);
        xCrdnArr += temp;

        temp.printf(L"SUBSTR(A.Y_CRDN_ARR, %d, %d) AS YMSG%02d,   \r\n", fromIdx, divSize, ii);
        yCrdnArr += temp;
        fromIdx = (ii * divSize) + 1;
        colCount = ii;
    }

    try
    {
        try
        {
            //sQry = "SELECT A.LINK_ID AS ID, A.X_CRDN_ARR, A.Y_CRDN_ARR  \r\n"
            sQry = "SELECT A.LINK_ID AS ID,       \r\n" +
                   xCrdnArr + yCrdnArr +
                   "       LEVL                   \r\n"
                   "  FROM TB_LINK_VRTX_ARR A,    \r\n"
                   "       TB_LINK          B     \r\n"
                   " WHERE B.DEL_YN  = 'N'        \r\n"
                   "   AND B.LINK_ID = A.LINK_ID  \r\n"
                   "   AND A.LEVL    = 2          \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;

            String ID;
            String XAddr;
            String YAddr;

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                ID    = pADO->FieldByName("ID")->AsString;
                //XAddr = pADO->FieldByName("X_CRDN_ARR")->AsWideString;
                //YAddr = pADO->FieldByName("Y_CRDN_ARR")->AsWideString;
                XAddr = "";
                YAddr = "";
                String sColNm;
                for (int ii = 1; ii <= colCount; ii++)
                {
                    sColNm.printf(L"XMSG%02d", ii);
                    XAddr += pADO->FieldByName(sColNm)->AsWideString;
                    sColNm.printf(L"YMSG%02d", ii);
                    YAddr += pADO->FieldByName(sColNm)->AsWideString;
                }

                fwprintf(fd, L"%s;%s;%s\n", ID.c_str(), XAddr.c_str(), YAddr.c_str());
                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            fclose(fd);
        }
        pADO->Close();
        DB_CLOSE();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeIfscVertexXml2(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "IFSC.dat";
    AnsiString sFileBackup = ExtractFilePath(Application->ExeName) + XML_DIR+ "IFSC_"+Now().FormatString("yyyymmddhhnnss")+".dat";

    try
    {
        CopyFile(String(sFile).c_str(), String(sFileBackup).c_str(), true);   //존재하면 업어쓴다
    }
    catch(Exception &e)
    {
    }

	FILE      *fd    = NULL;

    UpdateProgress(1, "정보제공구간 구간좌표 정보 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"정보제공구간 구간좌표 정보 파일을 생성하지 못하였습니다.",
                                L"정보제공구간 구간좌표 정보 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    int nTotal = 0;
#if 0
            sQry = "SELECT A.IFSC_ID AS ID,                            \r\n"
                   "       SUBSTR(A.X_CRDN_ARR,    1, 400) AS XMSG01,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR,  401, 400) AS XMSG02,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR,  801, 400) AS XMSG03,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 1201, 400) AS XMSG04,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 1601, 400) AS XMSG05,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 2001, 400) AS XMSG06,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 2401, 400) AS XMSG07,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 2801, 400) AS XMSG08,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 3201, 400) AS XMSG09,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 3601, 400) AS XMSG10,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 4001, 400) AS XMSG11,   \r\n"
                   "       SUBSTR(A.X_CRDN_ARR, 4401, 400) AS XMSG12,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR,    1, 400) AS YMSG01,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR,  401, 400) AS YMSG02,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR,  801, 400) AS YMSG03,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 1201, 400) AS YMSG04,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 1601, 400) AS YMSG05,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 2001, 400) AS YMSG06,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 2401, 400) AS YMSG07,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 2801, 400) AS YMSG08,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 3201, 400) AS YMSG09,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 3601, 400) AS YMSG10,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 4001, 400) AS YMSG11,   \r\n"
                   "       SUBSTR(A.Y_CRDN_ARR, 4401, 400) AS YMSG12    \r\n"
                   "  FROM TB_IFSC_VRTX_ARR A,                         \r\n"
                   "       TB_IFSC          B                          \r\n"
                   " WHERE B.DEL_YN  = 'N'                             \r\n"
                   "   AND B.IFSC_ID = A.IFSC_ID                       \r\n"
                   "   AND A.LEVL    = 5                               \r\n";

#if 1
            sQry = "SELECT A.IFSC_ID AS ID, A.X_CRDN_ARR, A.Y_CRDN_ARR  \r\n"
                   "  FROM TB_IFSC_VRTX_ARR A,                          \r\n"
                   "       TB_IFSC          B                           \r\n"
                   " WHERE B.DEL_YN  = 'N'                              \r\n"
                   "   AND B.IFSC_ID = A.IFSC_ID                        \r\n"
                   "   AND A.LEVL    = 5                                \r\n";
#endif
#endif

    try
    {
        try
        {
            sQry = "SELECT COUNT(1) AS TOTAL_CNT    \r\n"
                   "  FROM TB_IFSC_VRTX_ARR A,      \r\n"
                   "       TB_IFSC          B       \r\n"
                   " WHERE B.DEL_YN  = 'N'          \r\n"
                   "   AND B.IFSC_ID = A.IFSC_ID    \r\n"
                   "   AND A.LEVL    = 5            \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                nTotal = pADO->FieldByName("TOTAL_CNT")->AsInteger;
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        pADO->Close();
    }

    int nFetchRows = 500;
    int nFetchCnts = nTotal / nFetchRows;
    nFetchCnts = nFetchCnts + ((nTotal % nFetchRows) ? 1 : 0);

    for (int seq = 0; seq < nFetchCnts; seq++)
    {
        try
        {
            try
            {
                sQry = "SELECT ID, X_CRDN_ARR, Y_CRDN_ARR                                           \r\n"
                       "  FROM (                                                                    \r\n"
                       "SELECT A.IFSC_ID AS ID, A.X_CRDN_ARR, A.Y_CRDN_ARR, ROWNUM AS DATA_SEQ      \r\n"
                       "  FROM TB_IFSC_VRTX_ARR A,                                                  \r\n"
                       "       TB_IFSC          B                                                   \r\n"
                       " WHERE B.DEL_YN  = 'N'                                                      \r\n"
                       "   AND B.IFSC_ID = A.IFSC_ID                                                \r\n"
                       "   AND A.LEVL    = 5                                                        \r\n"
                       " ORDER BY A.IFSC_ID                                                         \r\n"
                       "   )                                                                        \r\n"
                       " WHERE DATA_SEQ >= :p01 AND DATA_SEQ < :p02                                 \r\n";

                pADO->Close();
                pADO->SQL->Text = sQry;
    			pADO->Parameters->ParamByName("p01")->Value = seq*nFetchRows;
    			pADO->Parameters->ParamByName("p02")->Value = (seq+1)*nFetchRows;
                pADO->Open();

                //nRows = pADO->RecordCount;
                //cxProgressBar1->Properties->Max = nRows;

                String ID;
                String XAddr;
                String YAddr;

                nCnt = 0;
                for( ; !pADO->Eof; pADO->Next(), nCnt++)
                {
                    ID    = pADO->FieldByName("ID")->AsString;
                    XAddr = pADO->FieldByName("X_CRDN_ARR")->AsString;
                    YAddr = pADO->FieldByName("Y_CRDN_ARR")->AsString;
                    fwprintf(fd, L"%s;%s;%s\n", ID.c_str(), XAddr.c_str(), YAddr.c_str());
                    //if ((nCnt % 50) == 0) UpdateProgress(nCnt);
                    Application->ProcessMessages();
                }
            }
            catch(Exception &exception)
            {
                throw Exception(String(exception.ClassName()) + exception.Message);
                return false;
            }
        }
        __finally
        {
            //UpdateProgress(nRows);
            if (fd)
            {
                fclose(fd);
            }
            pADO->Close();
        }
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeIfscVertexXml(TADOQuery *pADO)
{
    if (DB_OPEN(&g_AppCfg.ifsc) == false)
    {
        return false;
    }
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "IFSC.dat";
    AnsiString sFileBackup = ExtractFilePath(Application->ExeName) + XML_DIR+ "IFSC_"+Now().FormatString("yyyymmddhhnnss")+".dat";

    try
    {
        CopyFile(String(sFile).c_str(), String(sFileBackup).c_str(), true);   //존재하면 업어쓴다
    }
    catch(Exception &e)
    {
    }

	FILE      *fd    = NULL;

    UpdateProgress(1, "정보제공구간 구간좌표 정보 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"정보제공구간 구간좌표 정보 파일을 생성하지 못하였습니다.",
                                L"정보제공구간 구간좌표 정보 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    int colSize = 4000;
    int divSize = 200;
    int colCount = 0;

    String xCrdnArr = "";
    String yCrdnArr = "";

    String temp;
    int fromIdx = 1;
    for (int ii = 1; ; ii++)
    {
        if (fromIdx > colSize) break;

        temp.printf(L"SUBSTR(A.X_CRDN_ARR, %d, %d) AS XMSG%02d,   \r\n", fromIdx, divSize, ii);
        xCrdnArr += temp;

        temp.printf(L"SUBSTR(A.Y_CRDN_ARR, %d, %d) AS YMSG%02d,   \r\n", fromIdx, divSize, ii);
        yCrdnArr += temp;
        fromIdx = (ii * divSize) + 1;
        colCount = ii;
    }

    try
    {
        try
        {
            //sQry = "SELECT A.IFSC_ID AS ID, A.X_CRDN_ARR, A.Y_CRDN_ARR  \r\n"
            sQry = "SELECT A.IFSC_ID AS ID,       \r\n" +
                   xCrdnArr + yCrdnArr +
                   "       LEVL                   \r\n"
                   "  FROM TB_IFSC_VRTX_ARR A,    \r\n"
                   "       TB_IFSC          B     \r\n"
                   " WHERE B.DEL_YN  = 'N'        \r\n"
                   "   AND B.IFSC_ID = A.IFSC_ID  \r\n"
                   "   AND A.LEVL    = 5          \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;

            String ID;
            String XAddr;
            String YAddr;

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                ID    = pADO->FieldByName("ID")->AsString;
                //XAddr = pADO->FieldByName("X_CRDN_ARR")->AsWideString;
                //YAddr = pADO->FieldByName("Y_CRDN_ARR")->AsWideString;
                XAddr = "";
                YAddr = "";
                String sColNm;
                for (int ii = 1; ii <= colCount; ii++)
                {
                    sColNm.printf(L"XMSG%02d", ii);
                    XAddr += pADO->FieldByName(sColNm)->AsWideString;
                    sColNm.printf(L"YMSG%02d", ii);
                    YAddr += pADO->FieldByName(sColNm)->AsWideString;
                }

                fwprintf(fd, L"%s;%s;%s\n", ID.c_str(), XAddr.c_str(), YAddr.c_str());
                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            fclose(fd);
        }
        pADO->Close();
        DB_CLOSE();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeRoadVertexXml(TADOQuery *pADO)
{
    if (DB_OPEN(&g_AppCfg.road) == false)
    {
        return false;
    }
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "ROAD.dat";
    AnsiString sFileBackup = ExtractFilePath(Application->ExeName) + XML_DIR+ "ROAD_"+Now().FormatString("yyyymmddhhnnss")+".dat";

    try
    {
        CopyFile(String(sFile).c_str(), String(sFileBackup).c_str(), true);   //존재하면 업어쓴다
    }
    catch(Exception &e)
    {
    }

	FILE      *fd    = NULL;

    UpdateProgress(1, "도로 구간좌표 정보 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"도로 구간좌표 정보 파일을 생성하지 못하였습니다.",
                                L"도로 구간좌표 정보 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    int colSize = 4000;
    int divSize = 200;
    int colCount = 0;

    String xCrdnArr = "";
    String yCrdnArr = "";

    String temp;
    int fromIdx = 1;
    for (int ii = 1; ; ii++)
    {
        if (fromIdx > colSize) break;

        temp.printf(L"SUBSTR(A.X_CRDN_ARR, %d, %d) AS XMSG%02d,   \r\n", fromIdx, divSize, ii);
        xCrdnArr += temp;

        temp.printf(L"SUBSTR(A.Y_CRDN_ARR, %d, %d) AS YMSG%02d,   \r\n", fromIdx, divSize, ii);
        yCrdnArr += temp;
        fromIdx = (ii * divSize) + 1;
        colCount = ii;
    }

    try
    {
        try
        {
            //sQry = "SELECT A.ROAD_ID AS ID, A.X_CRDN_ARR, A.Y_CRDN_ARR  \r\n"
            sQry = "SELECT A.ROAD_ID AS ID,       \r\n" +
                   xCrdnArr + yCrdnArr +
                   "       LEVL                   \r\n"
                   "  FROM TB_ROAD_VRTX_ARR A,    \r\n"
                   "       TB_ROAD          B     \r\n"
                   " WHERE B.DEL_YN  = 'N'        \r\n"
                   "   AND B.ROAD_ID = A.ROAD_ID  \r\n"
                   "   AND A.LEVL    = 7          \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;

            String ID;
            String XAddr;
            String YAddr;

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                ID    = pADO->FieldByName("ID")->AsString;
                //XAddr = pADO->FieldByName("X_CRDN_ARR")->AsWideString;
                //YAddr = pADO->FieldByName("Y_CRDN_ARR")->AsWideString;
                XAddr = "";
                YAddr = "";
                String sColNm;
                for (int ii = 1; ii <= colCount; ii++)
                {
                    sColNm.printf(L"XMSG%02d", ii);
                    XAddr += pADO->FieldByName(sColNm)->AsWideString;
                    sColNm.printf(L"YMSG%02d", ii);
                    YAddr += pADO->FieldByName(sColNm)->AsWideString;
                }

                fwprintf(fd, L"%s;%s;%s\n", ID.c_str(), XAddr.c_str(), YAddr.c_str());
                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            fclose(fd);
        }
        pADO->Close();
        DB_CLOSE();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::WriteXmlHead(FILE *AFd, bool AHead/*=true*/)
{
    try
    {
        if (AFd == NULL) return false;

        if (AHead)
        {
            fprintf(AFd, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            fprintf(AFd, "<DataList>\n");
        }
        else
        {
            fprintf(AFd, "</DataList>\n");
        }
    }
    catch(Exception &exception)
    {
        throw Exception(String(exception.ClassName()) + exception.Message);
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::WriteXmlObject(FILE *AFd, String AObject)
{
    try
    {
        if (AFd == NULL) return false;

        fwprintf(AFd, L"<object>%s</object>\n", AObject.c_str());
    }
    catch(Exception &exception)
    {
        throw Exception(String(exception.ClassName()) + exception.Message);
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::WriteXmlRecordCount(FILE *AFd, int ARows)
{
    try
    {
        if (AFd == NULL) return false;

        fprintf(AFd, "<count>%d</count>\n", ARows);
    }
    catch(Exception &exception)
    {
        throw Exception(String(exception.ClassName()) + exception.Message);
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeNodeXml(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "Node.xml";
	FILE      *fd    = NULL;

    UpdateProgress(1, "노드정보 XML 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"노드정보 XML 파일을 생성하지 못하였습니다.",
                                L"노드정보 XML 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    WriteXmlHead(fd, true);
    WriteXmlObject(fd, "node");

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    try
    {
        try
        {
            sQry = "SELECT A.NODE_ID, A.NODE_TYPE, A.NODE_NAME, \r\n"
                   "       A.TURN_P, A.RMRK, A.X_CRDN, A.Y_CRDN \r\n"
                   "  FROM TB_NODE A                            \r\n"
                   " ORDER BY A.NODE_ID                         \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;
            WriteXmlRecordCount(fd, nRows);

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                String NODE_ID   = pADO->FieldByName("NODE_ID")->AsString;             //노드ID
                //String NODE_TYPE = pADO->FieldByName("NODE_TYPE")->AsString;           //노드유형
                String NODE_NAME = pADO->FieldByName("NODE_NAME")->AsString.Trim();    //교차로명칭
                //String TURN_P    = pADO->FieldByName("TURN_P")->AsString;              //회전제한유무
                //String RMRK      = pADO->FieldByName("RMRK")->AsString.Trim();         //비고
                String X_CRDN    = pADO->FieldByName("X_CRDN")->AsString;              //X 좌표
                String Y_CRDN    = pADO->FieldByName("Y_CRDN")->AsString;              //Y 좌표

                fwprintf(fd, L"    <node>");
                fwprintf(fd, L"<id>%s</id><x>%s</x><y>%s</y>", NODE_ID.c_str(), X_CRDN.c_str(), Y_CRDN.c_str());
                fprintf(fd,   "<name>%s</name>", UTF8Encode(NODE_NAME).c_str());
                fwprintf(fd, L"</node>\n");

                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            WriteXmlHead(fd, false);
            fclose(fd);
        }
        pADO->Close();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeLinkXml(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "Link.xml";
	FILE      *fd    = NULL;

    UpdateProgress(1, "링크정보 XML 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"링크정보 XML 파일을 생성하지 못하였습니다.",
                                L"링크정보 XML 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    WriteXmlHead(fd);
    WriteXmlObject(fd, "link");

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    try
    {
        try
        {
            sQry = "SELECT A.LINK_ID, A.F_NODE, A.T_NODE, TRIM(A.ROAD_NAME) ROAD_NAME,                     \r\n"
                   "       NVL(B.NODE_NAME, '') F_NAME, NVL(C.NODE_NAME, '') T_NAME,                       \r\n"
                   "       A.ROAD_USE, A.LANES,  A.ROAD_RANK, TRIM(A.ROAD_TYPE) AS ROAD_TYPE, A.ROAD_NO,   \r\n"
                   "       A.MAX_SPD, A.LINK_LENG, A.DEL_YN, DECODE(A.AREA_CD, 'LAT001', 'Y', 'N') REGN_YN \r\n"
                   "  FROM TB_LINK A, TB_NODE B, TB_NODE C                                                 \r\n"
                   " WHERE A.F_NODE = B.NODE_ID(+)                                                         \r\n"
                   "   AND A.T_NODE = C.NODE_ID(+)                                                         \r\n"
                   " ORDER BY LINK_ID                                                                      \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;
            WriteXmlRecordCount(fd, nRows);

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                String LINK_ID          = pADO->FieldByName("LINK_ID")->AsString;          //'링크ID';;
                String F_NODEID         = pADO->FieldByName("F_NODE")->AsString;           //'시작노드ID';;
                String T_NODEID         = pADO->FieldByName("T_NODE")->AsString;           //'종료노드ID';;
                String ROAD_NAME        = pADO->FieldByName("ROAD_NAME")->AsString.Trim();        //'도로명';;
                String F_NAME           = pADO->FieldByName("F_NAME")->AsString;           //'시작노드';;
                String T_NAME           = pADO->FieldByName("T_NAME")->AsString;           //'종료노드';;
                String ROAD_USE         = pADO->FieldByName("ROAD_USE")->AsString;         //'도로사용여부';;
                String LANES            = pADO->FieldByName("LANES")->AsString;            //'차로수';;
                String ROAD_RANK        = pADO->FieldByName("ROAD_RANK")->AsString;        //'도로등급';;
                String ROAD_TYPE        = pADO->FieldByName("ROAD_TYPE")->AsString;        //'도로유형';;
                String ROAD_NO          = pADO->FieldByName("ROAD_NO")->AsString;          //'도로번호';;
                String MAX_SPD          = pADO->FieldByName("MAX_SPD")->AsString;          //'최고제한속도';;
                String LINK_LENG        = pADO->FieldByName("LINK_LENG")->AsString;        //'연장';;
                String DEL_YN           = pADO->FieldByName("DEL_YN")->AsString;           //'삭제 여부';;
                String REGN_YN          = pADO->FieldByName("REGN_YN")->AsString;          //'로컬지역여부';

                fwprintf(fd, L"    <link>");
                fwprintf(fd, L"<id>%s</id><f_node>%s</f_node><t_node>%s</t_node><info>%s</info><dist>%s</dist>\n",
                             LINK_ID.c_str(), F_NODEID.c_str(), T_NODEID.c_str(), ROAD_RANK.c_str(), LINK_LENG.c_str());
                fprintf(fd,   "        <name>%s</name><f_name>%s</f_name><t_name>%s</t_name>",
                             UTF8Encode(ROAD_NAME).c_str(), UTF8Encode(F_NAME).c_str(), UTF8Encode(T_NAME).c_str());
                fwprintf(fd, L"</link>\n");

                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            WriteXmlHead(fd, false);
            fclose(fd);
        }
        pADO->Close();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeIfscXml(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "Ifsc.xml";
	FILE      *fd    = NULL;

    UpdateProgress(1, "정보제공구간 XML 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"정보제공구간 XML 파일을 생성하지 못하였습니다.",
                                L"정보제공구간 XML 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    WriteXmlHead(fd);
    WriteXmlObject(fd, "ifsc");

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    try
    {
        try
        {
            sQry = "SELECT IFSC_ID, IFSC_NM, DRCT_CD, STRT_NM, END_NM, SECT_LNGT,             \r\n"
                   "       EXTR_CNCT_SECT_YN, DEL_YN, RMRK, F_NODE_ID, T_NODE_ID,             \r\n"
                   "       SECT_GRAD_CD, AREA_CD, DECODE(AREA_CD, 'LAT001', 'Y', 'N') REGN_YN \r\n"
                   "  FROM TB_IFSC                                                            \r\n"
                   " ORDER BY IFSC_ID                                                         \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;
            WriteXmlRecordCount(fd, nRows);

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                String IFSC_ID           = pADO->FieldByName("IFSC_ID")->AsString;
                String IFSC_NM           = pADO->FieldByName("IFSC_NM")->AsString.Trim();
                String DRCT_CD           = pADO->FieldByName("DRCT_CD")->AsString;
                //String RMRK              = pADO->FieldByName("RMRK")->AsString.Trim();
                //String EXTR_CNCT_SECT_YN = pADO->FieldByName("EXTR_CNCT_SECT_YN")->AsString;
                //String DEL_YN            = pADO->FieldByName("DEL_YN")->AsString;
                String SECT_LNGT         = pADO->FieldByName("SECT_LNGT")->AsString;
                //String SECT_GRAD_CD      = pADO->FieldByName("SECT_GRAD_CD")->AsString;
                String F_NODE_ID         = pADO->FieldByName("F_NODE_ID")->AsString;
                String T_NODE_ID         = pADO->FieldByName("T_NODE_ID")->AsString;
                String STRT_NM           = pADO->FieldByName("STRT_NM")->AsString.Trim();
                String END_NM            = pADO->FieldByName("END_NM")->AsString.Trim();
                //String REGN_YN           = pADO->FieldByName("REGN_YN")->AsString;
                //String AREA_CD           = pADO->FieldByName("AREA_CD")->AsString;

                fwprintf(fd, L"    <link>");
                fwprintf(fd, L"<id>%s</id><f_node>%s</f_node><t_node>%s</t_node><info>%s</info><dist>%s</dist>\n",
                             IFSC_ID.c_str(), F_NODE_ID.c_str(), T_NODE_ID.c_str(), DRCT_CD.c_str(), SECT_LNGT.c_str());
                fprintf(fd,   "        <name>%s</name><f_name>%s</f_name><t_name>%s</t_name>",
                             UTF8Encode(IFSC_NM).c_str(), UTF8Encode(STRT_NM).c_str(), UTF8Encode(END_NM).c_str());
                fwprintf(fd, L"</link>\n");

                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            WriteXmlHead(fd, false);
            fclose(fd);
        }
        pADO->Close();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeRoadXml(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "Road.xml";
	FILE      *fd    = NULL;

    UpdateProgress(1, "도로정보 XML 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"도로정보 XML 파일을 생성하지 못하였습니다.",
                                L"도로정보 XML 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    WriteXmlHead(fd);
    WriteXmlObject(fd, "road");

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    try
    {
        try
        {
            sQry = "SELECT ROAD_ID, ROAD_NAME, DRCT_CD, STRT_NM, END_NM, \r\n"
                   "       DEL_YN, SECT_LNGT, F_NODE_ID, T_NODE_ID,      \r\n"
                   "       SECT_GRAD_CD, AREA_CD,                        \r\n"
                   "       DECODE(AREA_CD, 'LAT001', 'Y', 'N') REGN_YN   \r\n"
                   "  FROM TB_ROAD                                       \r\n"
                   " ORDER BY ROAD_ID                                    \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;
            WriteXmlRecordCount(fd, nRows);

            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                String ROAD_ID      = pADO->FieldByName("ROAD_ID")->AsString;
                String ROAD_NAME    = pADO->FieldByName("ROAD_NAME")->AsString.Trim();
                String DRCT_CD      = pADO->FieldByName("DRCT_CD")->AsString;
                String STRT_NM      = pADO->FieldByName("STRT_NM")->AsString.Trim();
                String END_NM       = pADO->FieldByName("END_NM")->AsString.Trim();
                //String DEL_YN       = pADO->FieldByName("DEL_YN")->AsString;
                String SECT_LNGT    = pADO->FieldByName("SECT_LNGT")->AsString;
                String F_NODE_ID    = pADO->FieldByName("F_NODE_ID")->AsString;
                String T_NODE_ID    = pADO->FieldByName("T_NODE_ID")->AsString;
                //String SECT_GRAD_CD = pADO->FieldByName("SECT_GRAD_CD")->AsString;
                //String AREA_CD      = pADO->FieldByName("AREA_CD")->AsString;
                //String REGN_YN      = pADO->FieldByName("REGN_YN")->AsString;

                fwprintf(fd, L"    <link>");
                fwprintf(fd, L"<id>%s</id><f_node>%s</f_node><t_node>%s</t_node><info>%s</info><dist>%s</dist>\n",
                             ROAD_ID.c_str(), F_NODE_ID.c_str(), T_NODE_ID.c_str(), DRCT_CD.c_str(), SECT_LNGT.c_str());
                fprintf(fd,   "        <name>%s</name><f_name>%s</f_name><t_name>%s</t_name>",
                             UTF8Encode(ROAD_NAME).c_str(), UTF8Encode(STRT_NM).c_str(), UTF8Encode(END_NM).c_str());
                fwprintf(fd, L"</link>\n");

                if ((nCnt % 50) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            WriteXmlHead(fd, false);
            fclose(fd);
        }
        pADO->Close();
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmUtilMain::MakeRegionVertexXml(TADOQuery *pADO)
{
    AnsiString sFile = ExtractFilePath(Application->ExeName) + XML_DIR+ "RegionVertex.xml";
	FILE      *fd    = NULL;

    UpdateProgress(1, "행정구역 Vertex XML 파일생성");

	if ((fd = fopen(sFile.c_str(), "w")) == NULL)
    {
        Application->MessageBox(L"행정구역 Vertex 정보 파일을 생성하지 못하였습니다.",
                                L"행정구역 Vertex 정보 XML 파일생성", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    WriteXmlHead(fd);
    WriteXmlObject(fd, "region_vertex");

    int    nRows= 0;
    int    nCnt = 0;
    String sQry;

    try
    {
        try
        {
            sQry = "SELECT CONFIGSEQ AS ORD, COORDX AS X_CRDN, COORDY AS Y_CRDN  \r\n"
                   "  FROM LINK_SUBSECTION                                       \r\n"
                   " WHERE SUBSECTIONKIND = 'B'                                  \r\n"
                   "   AND DISPLAYLEVEL   = 1                                    \r\n"
                   " ORDER BY CONFIGSEQ                                          \r\n";

            pADO->Close();
			pADO->SQL->Text = sQry;
            pADO->Open();

            nRows = pADO->RecordCount;
            cxProgressBar1->Properties->Max = nRows;
            WriteXmlRecordCount(fd, nRows);

            String sPosX = "";
            String sPosY = "";
            String sMinXY = "";
            String sMaxXY = "";
            int    nOrd, nOrdCnt;

            nOrd = 1;
            for( ; !pADO->Eof; pADO->Next(), nCnt++)
            {
                sPosX += pADO->FieldByName("X_CRDN")->AsString;
                sPosY += pADO->FieldByName("Y_CRDN")->AsString;

                sPosX = sPosX.SubString(1, sPosX.Length()-1);
                sPosY = sPosY.SubString(1, sPosY.Length()-1);

                fwprintf(fd, L"    <pos><order>%d</order><x>%s</x><y>%s</y></pos>\n", nOrd++, sPosX.c_str(), sPosY.c_str());

                sPosX = "";
                sPosY = "";

                if ((nCnt % 20) == 0) UpdateProgress(nCnt);
            }
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
            return false;
        }
    }
    __finally
    {
        UpdateProgress(nRows);
        if (fd)
        {
            WriteXmlHead(fd, false);
            fclose(fd);
        }
        pADO->Close();
    }
    return true;
}
//---------------------------------------------------------------------------

