#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <stdlib.h>

#include <dirent.h>
#include <time.h>
#include <math.h>
#include "libpq-fe.h"


int AnalysisDat(char *Dat ,int kouji_id);
int RetCharIndex(char *Word_);
void RetCode(int Index_, char *Code_);
int StrRep(char *Buff_, char *OldWord_, char *NewWord_);
int RetMessageType(char *Dat_, int *Length_);
void AnaMesseTypeClassA(char *BitCode_,int kouji_id);
void AnaMesseTypeClassBase(char *BitCode_);
void AnaMesseTypeShipInfo(char *BitCode_,int kouji_id);
void AnaMesseTypeClassB(char *BitCode_,int kouji_id);
void AnaMesseTypeClassBCS(char *BitCode_,int kouji_id);
int RetCodeIndex(char *Code_);
void RetASCIIChar(int Index_, char *Word_);

//20110421 Kikuchi
int MeasureInfo_Regist(FILE *fp, PGconn *conn , int kouji_id, int PosiAc, int Mmsi,int NaviSt ,double Rot, double Sog, double Lat, double Lon, double Cog, double THead, char *TsTable ,int UpFlag ,int TypeFlag);
int ShipInfo_Regist(FILE *fp, PGconn *conn , int kouji_id, int Mmsi ,char *ShipName ,int ShipType, int ShipLength, int ShipWidth, char *Dest, char *TsTable, int UpFlag, int TypeFlag);
int XML_output(FILE *fp, FILE *fpx, PGconn *conn , int kouji_id, char *TsTable);


//新規に追加
char conn_info[256];		//DB接続設定
PGconn *conn;				//DB接続Object
FILE *fp;					//Log_Fileのポインタ
FILE *fpx;					//XML_Fileのポインタ

//int kouji_id = 54;
char TsTable[128];
char HisTable[128];
char SqlSelect[1024];
char SqlTerm[1024];
char SqlHis[1024];
char TermID[1024];
char Longi[1024];
char Lati[1024];
int UpFlag;
int TypeFlag;
int ii;

char ToFolder[512];

char WordArray[64][2] =
{
	"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
	"L", "M", "N", "O",	"P", "Q", "R", "S", "T", "U", "V", "W", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
	"p", "q", "r", "s", "t", "u", "v", "w"
};

char CodeArray[64][10] =
{
	"000000", "000001", "000010", "000011", "000100", "000101", "000110", "000111", "001000", "001001", "001010", "001011", "001100", "001101",
	"001110", "001111", "010000", "010001", "010010", "010011", "010100", "010101", "010110", "010111", "011000", "011001", "011010", "011011",
	"011100", "011101", "011110", "011111", "100000", "100001", "100010", "100011", "100100", "100101", "100110", "100111", "101000", "101001",
	"101010", "101011", "101100", "101101", "101110", "101111", "110000", "110001", "110010", "110011", "110100", "110101", "110110", "110111",
	"111000", "111001", "111010", "111011", "111100", "111101", "111110", "111111"
};

char SixBitASCIIArray[64][2] =
{
	"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[",
	"", "]", "^", "_", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7",
	"8", "9", ":", ";", "<", "=", ">", "?"
};

//===========================
// Main()
//===========================
int main(int argc, char *argv[])
{
	char AnaDat[256];
	char AisDat[256];
	char *Token;
	char *SepWord = ",";
	int Count = 0;
	int kouji_id = atoi(argv[2]);			//工事ID
	
	memset(&AisDat, 0x00, sizeof(AisDat));
	
	// テストデータ
	// ClassA
	//sprintf(AisDat, "!AIVDM,1,1,,B,15BcRH0001aweBpD@E9rQK:d0@<w,0*2F");
	//sprintf(AisDat, "!AIVDM,1,1,,A,37cWDF5001b0hGbDJJe9LijR2000,0*08");
	// BasePoint
	//sprintf(AisDat, "!AIVDM,1,1,,B,404757iue27ci9wLcrDAl>700L4O,0*12");
	// ShipInfo
	//sprintf(AisDat, "!AIVDM,2,1,8,B,57b>t6029rUaQD=c<01<PDpN1PT4pL00000000168@F;352a0;jhEhDhBj@0,0*25");
	// ClassB
	// ClassB [CS]
	
//	printf("%s\n", argv[1]);
	sprintf(AisDat, argv[1]);
	
	// 配信先フォルダの取得
	sprintf(ToFolder, "%s", argv[3]);
	
	// ",,"->", ," [正確に切り出しを行う為]
	StrRep(AisDat, ",,", ", ,");
	//printf("aisdata => %s\n", AisDat);
	if (strcmp(AisDat, "") != 0)
	{
		AnalysisDat(AisDat,kouji_id);
	}
	return 0;
}

//===========================
// データを解析
//===========================
int AnalysisDat(char *AisDat_,int kouji_id)
{
	int Ret;
	int iCount;
	int Length;
	char BitCode[1024];
	char Word[32];
	// メッセージタイプを取得
	int MesseType = RetMessageType(AisDat_, &Length);
	
	if (MesseType != 5)
		return;
	memset(&BitCode, 0x00, sizeof(BitCode));
	for(iCount = 0; iCount < (int)strlen(AisDat_); iCount++)
	{
		char SixBitCode[7];
		memset(&SixBitCode, 0x00, sizeof(SixBitCode));
		memset(&Word, 0x00, sizeof(Word));
		
		strncpy(Word, AisDat_ + iCount, 1);
		if ((Ret = RetCharIndex(Word)) != -1)
		{
			RetCode(Ret, SixBitCode);
		}
		strcat(BitCode, SixBitCode);
	}
	// それぞれのフォーマットで解析
	if (1 <= MesseType && 3 >= MesseType)
	{
		//AnaMesseTypeClassA(BitCode,kouji_id);
	}
	else if (MesseType == 4)
	{
		//AnaMesseTypeClassBase(BitCode);
	}
	else if (MesseType == 5)
	{
		AnaMesseTypeShipInfo(BitCode,kouji_id);
	}
	else if (MesseType == 18)
	{
		//AnaMesseTypeClassB(BitCode,kouji_id);
	}
	else if (MesseType == 24)
	{
		//AnaMesseTypeClassBCS(BitCode,kouji_id);
	}
	return 0;
}

//===========================
// 文字番号を返す
//===========================
int RetCharIndex(char *Word_)
{
	
	int iCount = 0;
	for(iCount = 0; iCount < sizeof(WordArray) / sizeof(WordArray[0]); iCount++)
	{
		if (strcmp(WordArray[iCount], Word_) == 0)
		{
			return iCount;
		}
	}
	return -1;
}

//===========================
// 対応コードを返す
//===========================
void RetCode(int Index_, char *Code_)
{
	sprintf(Code_, "%s", CodeArray[Index_]);
}

//===========================
// 文字列を置換する
//===========================
int StrRep(char *Buff_, char *OldWord_, char *NewWord_)
{
	char *Poi;
	size_t OldLen;
	size_t NewLen;
	
	OldLen = strlen(OldWord_);
	NewLen = strlen(NewWord_);
	
	if (OldLen == 0 || (Poi = strstr(Buff_, OldWord_)) == NULL)
	{
		return -1;
	}
	memmove(Poi + NewLen, Poi + OldLen, strlen(Buff_) - (Poi + OldLen - Buff_) + 1);
	memcpy(Poi, NewWord_, NewLen);
	return 0;
}

//===========================
// 規定値, メッセージタイプを返す
//===========================
int RetMessageType(char *Dat_, int *Length_)
{
	char MessageWord[32] = "";
	strncpy(MessageWord, Dat_, 1);
	int Type = RetCharIndex(MessageWord);
	switch(Type)
	{
		case 1:
			*Length_ = 28;
			break;
		case 2:
			*Length_ = 28;
			break;
		case 3:
			*Length_ = 28;
			break;
		case 4:
			*Length_ = 28;
			break;
		case 5:
			*Length_ = 60;
			break;
		case 18:
			*Length_ = 28;
			break;
		case 24:
			*Length_ = 28;
			break;
		default:
			*Length_ = -1;
			break;
	}
	return Type;
}

//===========================
// 6BitCodeを元に文字列を形成
//===========================
void SixBit2Char(char *BitCode_, char *AnaChar_)
{
	int iCount;
	int CodeLen = (strlen(BitCode_) / 6);
	// 6Bitに切り出し
	char SepCode[32];
	char GetWord[32];
	char ConnChar[512];
	
	memset(&ConnChar, 0x00, sizeof(ConnChar));
	for(iCount = 0; iCount < CodeLen; iCount++)
	{
		memset(&SepCode, 0x00, sizeof(SepCode));
		strncpy(SepCode, BitCode_ + (6 * iCount), 6);
		
		int CharIndex = RetCodeIndex(SepCode);
		memset(&GetWord, 0x00, sizeof(GetWord));
		RetASCIIChar(CharIndex, GetWord);
		strcat(ConnChar, GetWord);
	}
	sprintf(AnaChar_, "%s", ConnChar);
}

//===========================
// 6BitCodeからIndex番号を返す
//===========================
int RetCodeIndex(char *Code_)
{
	int iCount = 0;
	for(iCount = 0; iCount < sizeof(CodeArray) / sizeof(CodeArray[0]); iCount++)
	{
		if (strcmp(CodeArray[iCount], Code_) == 0)
		{
			return iCount;
		}
	}
	return -1;
}

//===========================
// 対応文字を返す
//===========================
void RetASCIIChar(int Index_, char *Word_)
{
	sprintf(Word_, "%s", SixBitASCIIArray[Index_]);
}

//===========================
// クラスA
//===========================
void AnaMesseTypeClassA(char *BitCode_ ,int kouji_id)
{
	char MesseIDCode[64] = "";
	char RepIndCode[64] = "";
	char MmsiCode[64] = "";
	char NaviStCode[64] = "";
	char RotCode[64] = "";
	char SogCode[64] = "";
	char PosiAcCode[64] = "";
	char LonCode[64] = "";
	char LatCode[64] = "";
	char CogCode[64] = "";
	char THeadCode[64] = "";
	char UtcTimeCode[64] = "";
	char ManIndCode[64] = "";
	char SpareCode[64] = "";
	char RaimCode[64] = "";
	char RadioStCode[64] = "";
	
	// コードを切り出し
	strncpy(MesseIDCode, BitCode_ + 0, 6);
	strncpy(RepIndCode, BitCode_ + 6, 2);
	strncpy(MmsiCode, BitCode_ + 8, 30);
	strncpy(NaviStCode, BitCode_ + 38, 4);
	strncpy(RotCode, BitCode_ + 42, 8);
	strncpy(SogCode, BitCode_ + 50, 10);
	strncpy(PosiAcCode, BitCode_ + 60, 1);
	strncpy(LonCode, BitCode_ + 61, 28);
	strncpy(LatCode, BitCode_ + 89, 27);
	strncpy(CogCode, BitCode_ + 116, 12);
	strncpy(THeadCode, BitCode_ + 128, 9);
	strncpy(UtcTimeCode, BitCode_ + 137, 6);
	strncpy(ManIndCode, BitCode_ + 143, 2);
	strncpy(SpareCode, BitCode_ + 145, 3);
	strncpy(RaimCode, BitCode_ + 148, 1);
	strncpy(RadioStCode, BitCode_ + 149, 19);
	
	// 各規約に従い変換
	int MesseID = strtol(MesseIDCode, NULL, 2);
	int RepInd = strtol(RepIndCode, NULL, 2);
	int Mmsi = strtol(MmsiCode, NULL, 2);
	int NaviSt = strtol(NaviStCode, NULL, 2);
	double Rot = strtol(RotCode, NULL, 2);
	double Sog = strtol(SogCode, NULL, 2) / 10.0;
	int PosiAc = strtol(PosiAcCode, NULL, 2);
	double Lon = strtol(LonCode, NULL, 2) / 10000.0 / 60.0;
	double Lat = strtol(LatCode, NULL, 2) / 10000.0 / 60.0;
	double Cog = strtol(CogCode, NULL, 2) / 10.0;
	double THead = strtol(THeadCode, NULL, 2);
	int UtcTime = strtol(UtcTimeCode, NULL, 2);
	int ManInd = strtol(ManIndCode, NULL, 2);
	int Spare = strtol(SpareCode, NULL, 2);
	int Raim = strtol(RaimCode, NULL, 2);
	int RadioSt = strtol(RadioStCode, NULL, 2);

//***********************************************************************//
	// Debug 表示
	/*
	printf("MessageID => %d\n", MesseID);
	printf("RepInd => %d\n", RepInd);
	printf("MMSI => %d\n", Mmsi);			//ターミナルID(MMSI_ID)
	printf("NaviSt => %d\n", NaviSt);		//ナビゲーションステータス
	printf("Rot => %f\n", Rot);				//ROT
	printf("Sog => %f\n", Sog);				//SOG
	printf("PosiAc => %d\n", PosiAc);		//位置の精度
	printf("Lon => %f\n", Lon);				//経度
	printf("Lat => %f\n", Lat);				//緯度
	printf("Cog => %f\n", Cog);				//COG
	printf("THead => %f\n", THead);			//TrueHeading
	printf("UtcTime => %d\n", UtcTime);		//UTC時間
	printf("ManInd => %d\n", ManInd);
	printf("Spare => %d\n", Spare);
	printf("Raim => %d\n", Raim);
	printf("RadioSt => %d\n", RadioSt);
	*/

//***********************************************************************//
	//SQLに登録用の変数の定義(不足分)
	char measure_info[128];		//現在の座標


	//printf("kouji_id=%d\n",kouji_id);
	//時間関係定義
  	//time_t timer;
   	//struct tm *t_st;
	//char db_time[256];
	int rows;
	int TypeFlag = 1;
	fp = fopen("./log.txt", "a");
	PGresult *res;				//SQLを実行した戻り値

	memset(&TsTable, 0x00, sizeof(TsTable));
	memset(&HisTable, 0x00, sizeof(HisTable));
	sprintf(TsTable,"qgis.ais_terminal");
	sprintf(HisTable,"qgis.ais_his_measure");
	
	//●データーベースへ接続
	memset(&conn_info, 0x00, sizeof(conn_info));
	sprintf(conn_info,"host=localhost dbname=qgis user=posgre password=posgre");
	conn = PQconnectdb(conn_info);
	
	//●データベース接続確認処理(成功/失敗)
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		//--err出力
		fprintf(fp, "%s\r\n", PQerrorMessage(conn));
		fprintf(fp, "DB接続にerrがありました\r\n");
		fprintf(fp, "接続を解除して終了します\r\n");
		
		//--データーベースとの接続の解除
		PQfinish(conn);
		fclose(fp);
		exit(-1);
	}
	else
	{
		// 現在時刻の取得
		//time(&timer);
		// 現在時刻を構造体に変換
		//t_st = localtime(&timer);

		// 時刻代入
		//memset(&db_time, 0x00, sizeof(db_time));
		//memset(&db_time2, 0x00, sizeof(db_time2));
		//sprintf(db_time,"%d-%d-%d %d:%d:%d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
		
		//■新規データか確認
		//SELECT
		memset(&SqlSelect, 0x00, sizeof(SqlSelect));
		sprintf(SqlSelect, "SELECT terminal_id,measure_info[0],measure_info[1] FROM %s WHERE kouji_id = %d AND terminal_id = %d;", TsTable, kouji_id ,Mmsi);
		res = PQexec(conn, SqlSelect);

		if (PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(fp, "SELECTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", SqlSelect);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
		else
		{
			//printf("SQL実行OK\n");					//デバック用
			rows = PQntuples(res);

			if (rows != 0)
			{
				//printf("データ登録済です\n");			//デバック用
				UpFlag = 1;
				
				MeasureInfo_Regist(fp,conn,kouji_id,PosiAc,Mmsi,NaviSt,Rot,Sog,Lat,Lon,Cog,THead,TsTable,UpFlag,TypeFlag);
			}
			else
			{
				//printf("データが未登録です\n");		//デバック用
				UpFlag = 0;
				MeasureInfo_Regist(fp,conn,kouji_id,PosiAc,Mmsi,NaviSt,Rot,Sog,Lat,Lon,Cog,THead,TsTable,UpFlag,TypeFlag);
			}
		}
		UpFlag = 0;
		MeasureInfo_Regist(fp,conn,kouji_id,PosiAc,Mmsi,NaviSt,Rot,Sog,Lat,Lon,Cog,THead,HisTable,UpFlag,TypeFlag);

		//■ais_terminalをXML出力
		XML_output(fp,fpx,conn,kouji_id,TsTable);
		fclose(fp);
		//PQclear(res);
		PQfinish(conn);
	}
//***********************************************************************//
}

//===========================
// 基地局情報
//===========================
void AnaMesseTypeClassBase(char *BitCode_)
{
	char MesseIDCode[64] = "";
	char RepIndCode[64] = "";
	char MmsiCode[64] = "";
	char YearCode[64] = "";
	char MonthCode[64] = "";
	char DayCode[64] = "";
	char HourCode[64] = "";
	char MinCode[64] = "";
	char SecCode[64] = "";
	char FixQuaCode[64] = "";
	char LonCode[64] = "";
	char LatCode[64] = "";
	char EpfdCode[64] = "";
	char SpareCode[64] = "";
	char RaimCode[64] = "";
	char SotdmaCode[64] = "";
	
	// コードを切り出し
	strncpy(MesseIDCode, BitCode_ + 0, 6);
	strncpy(RepIndCode, BitCode_ + 6, 2);
	strncpy(MmsiCode, BitCode_ + 8, 30);
	strncpy(YearCode, BitCode_ + 38, 14);
	strncpy(MonthCode, BitCode_ + 52, 4);
	strncpy(DayCode, BitCode_ + 56, 5);
	strncpy(HourCode, BitCode_ + 61, 5);
	strncpy(MinCode, BitCode_ + 66, 6);
	strncpy(SecCode, BitCode_ + 72, 6);
	strncpy(FixQuaCode, BitCode_ + 78, 1);
	strncpy(LonCode, BitCode_ + 79, 28);
	strncpy(LatCode, BitCode_ + 107, 27);
	strncpy(EpfdCode, BitCode_ + 134, 4);
	strncpy(SpareCode, BitCode_ + 138, 10);
	strncpy(RaimCode, BitCode_ + 148, 1);
	strncpy(SotdmaCode, BitCode_ + 149, 19);
	
	// 各規約に従・ﾄ変換
	int MesseID = strtol(MesseIDCode, NULL, 2);
	int RepInd = strtol(RepIndCode, NULL, 2);
	int Mmsi = strtol(MmsiCode, NULL, 2);
	int Year = strtol(YearCode, NULL, 2);
	int Month = strtol(MonthCode, NULL, 2);
	int Day = strtol(DayCode, NULL, 2);
	int Hour = strtol(HourCode, NULL, 2);
	int Min = strtol(MinCode, NULL, 2);
	int Sec = strtol(SecCode, NULL, 2);
	int FixQua = strtol(FixQuaCode, NULL, 2);
	double Lon = strtol(LonCode, NULL, 2) / 10000.0 / 60.0;
	double Lat = strtol(LatCode, NULL, 2) / 10000.0 / 60.0;
	int Epfd = strtol(EpfdCode, NULL, 2);
	int Spare = strtol(SpareCode, NULL, 2);
	int Raim = strtol(RaimCode, NULL, 2);
	int Sotdma = strtol(SotdmaCode, NULL, 2);
	
	// Debug 表示
	/*
	printf("MessegeID => %d\n", MesseID);
	printf("RepInd => %d\n", RepInd);
	printf("MMSI => %d\n", Mmsi);
	printf("DateTime => %d-%d-%d %d:%d:%d\n", Year, Month, Day, Hour, Min, Sec);
	printf("FixQua => %d\n", FixQua);
	printf("Lon => %f\n", Lon);
	printf("Lat => %f\n", Lat);
	printf("Epfd => %d\n", Epfd);
	printf("Spare => %d\n", Spare);
	printf("Raim => %d\n", Raim);
	printf("Sotdma = %d\n", Sotdma);
	*/
}

//===========================
// 船情報
//===========================
void AnaMesseTypeShipInfo(char *BitCode_,int kouji_id)
{
	char MesseIDCode[64] = "";
	char RepIndCode[64] = "";
	char MmsiCode[64] = "";
	char AisVerCode[64] = "";
	char ImoNumCode[64] = "";
	char CallSignCode[64] = "";
	char ShipNameCode[128] = "";
	char ShipTypeCode[64] = "";
	char DimBowCode[64] = "";
	char DimSternCode[64] = "";
	char DimPortCode[64] = "";
	char DimStarBoardCode[64] = "";
	char PosiFixCode[64] = "";
	char EtaMonthCode[64] = "";
	char EtaDayCode[64] = "";
	char EtaHourCode[64] = "";
	char EtaMinCode[64] = "";
	char DraughtCode[64] = "";
	char DestCode[128] = "";
	char DteCode[64] = "";
	char SpareCode[64] = "";
	
	// コードを切り出し
	strncpy(MesseIDCode, BitCode_ + 0, 6);
	strncpy(RepIndCode, BitCode_ + 6, 2);
	strncpy(MmsiCode, BitCode_ + 8, 30);
	strncpy(AisVerCode, BitCode_ + 38, 2);
	strncpy(ImoNumCode, BitCode_ + 40, 30);
	strncpy(CallSignCode, BitCode_ + 70, 42);
	strncpy(ShipNameCode, BitCode_ + 112, 120);
	strncpy(ShipTypeCode, BitCode_ + 232, 8);
	strncpy(DimBowCode, BitCode_ + 240, 9);
	strncpy(DimSternCode, BitCode_ + 249, 9);
	strncpy(DimPortCode, BitCode_ + 258, 6);
	strncpy(DimStarBoardCode, BitCode_ + 264, 6);
	strncpy(PosiFixCode, BitCode_ + 270, 4);
	strncpy(EtaMonthCode, BitCode_ + 274, 4);
	strncpy(EtaDayCode, BitCode_ + 278, 5);
	strncpy(EtaHourCode, BitCode_ + 283, 5);
	strncpy(EtaMinCode, BitCode_ + 288, 6);
	strncpy(DraughtCode, BitCode_ + 294, 8);
	strncpy(DestCode, BitCode_ + 302, 120);
	strncpy(DteCode, BitCode_ + 422, 1);
	strncpy(SpareCode, BitCode_ + 423, 1);
	
	// 各規約に従・ﾄ変換
	int MesseID = strtol(MesseIDCode, NULL, 2);
	int RepInd = strtol(RepIndCode, NULL, 2);
	int Mmsi = strtol(MmsiCode, NULL, 2);
	int AisVer = strtol(AisVerCode, NULL, 2);
	int ImoNum = strtol(ImoNumCode, NULL, 2);
	char CallSign[512] = "";
	SixBit2Char(CallSignCode, CallSign);
	char ShipName[512] = "";
	SixBit2Char(ShipNameCode, ShipName);
	int ShipType = strtol(ShipTypeCode, NULL, 2);
	int DimBow = strtol(DimBowCode, NULL, 2);
	int DimStern = strtol(DimSternCode, NULL, 2);
	int DimPort = strtol(DimPortCode, NULL, 2);
	int DimStarBoard = strtol(DimStarBoardCode, NULL, 2);
	int PosiFix = strtol(PosiFixCode, NULL, 2);
	int EtaMonth = strtol(EtaMonthCode, NULL, 2);
	int EtaDay = strtol(EtaDayCode, NULL, 2);
	int EtaHour = strtol(EtaHourCode, NULL, 2);
	int EtaMin = strtol(EtaMinCode, NULL, 2);
	int Draught = strtol(DraughtCode, NULL, 2);
	char Dest[512] = "";
	SixBit2Char(DestCode, Dest);
	int Dte = strtol(DteCode, NULL, 2);
	int Spare = strtol(SpareCode, NULL, 2);
	
	
	int ShipLength = DimBow + DimStern;
	int ShipWidth = DimPort + DimStarBoard;
//***********************************************************************//
	// Debug 表示
	//printf("MessegeID => %d\n", MesseID);
	//printf("RepInd => %d\n", RepInd);
	//printf("MMSI => %d\n", Mmsi);
	//printf("AisVer => %d\n", AisVer);
	//printf("ImoNum => %d\n", ImoNum);
	//printf("CallSign => %s\n", CallSign);
	//printf("ShipName => %s\n", ShipName);
	//printf("ShipType => %d\n", ShipType);
	//printf("DimBow => %d\n", DimBow);
	//printf("DimStern => %d\n", DimStern);
	//printf("DimPort => %d\n", DimPort);
	//printf("DimStarBoard => %d\n", DimStarBoard);
	//printf("PosiFix => %d\n", PosiFix);
	//printf("EtaTime => %d-%d %d:%d\n", EtaMonth, EtaDay, EtaHour, EtaMin);
	//printf("Draught => %f\n", Draught);
	//printf("Dest => %s\n", Dest);
	//printf("Dte => %d\n", Dte);
	//printf("Spare => %d\n", Spare);
//***********************************************************************//
	//時間関係定義
  	//time_t timer;
   	//struct tm *t_st;
	//char db_time[256];
	
	//値の初期化
	int rows;
	int TypeFlag = 2;
	int UpFlag;
	fp = fopen("./log.txt", "a");
	PGresult *res;				//SQLを実行した戻り値
	
	memset(&TsTable, 0x00, sizeof(TsTable));
	memset(&HisTable, 0x00, sizeof(HisTable));
	sprintf(TsTable,"qgis.ais_terminal");
	sprintf(HisTable,"qgis.ais_his_measure");
	
	
	// データーベースへ接続
	memset(&conn_info, 0x00, sizeof(conn_info));
	//sprintf(conn_info,"host=localhost dbname=%s user=%s password=%s", dbname, user, password);
	sprintf(conn_info,"host=localhost dbname=qgis user=posgre password=posgre");
	conn = PQconnectdb(conn_info);
	
	// データベース接続確認処理(成功/失敗)
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		// err出力
		fprintf(fp, "%s\r\n", PQerrorMessage(conn));
		fprintf(fp, "DB接続にerrがありました\r\n");
		fprintf(fp, "接続を解除して終了します\r\n");
		
		// データーベースとの接続の解除
		PQfinish(conn);
		
		fclose(fp);
		
		exit(-1);
	}
	else
	{
		// 現在時刻の取得
		//time(&timer);
		// 現在時刻を構造体に変換
		//t_st = localtime(&timer);

		// 時刻代入
		//memset(&db_time, 0x00, sizeof(db_time));
		//sprintf(db_time,"%d-%d-%d %d:%d:%d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
		//printf("現在の時刻==%s\n", db_time);
		
		//■新規データか確認
		//SELECT
		PGresult *res;
		memset(&SqlSelect, 0x00, sizeof(SqlSelect));
		sprintf(SqlSelect, "SELECT terminal_id FROM %s WHERE kouji_id = %d AND terminal_id = %d;", TsTable, kouji_id ,Mmsi);
		res = PQexec(conn, SqlSelect);

		//insert
		if (PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(fp, "SELECTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", SqlSelect);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
		else
		{
			//printf("SQL実行OK\n");					//デバック用
			rows = PQntuples(res);

			if (rows != 0)
			{
				//printf("データ登録済です\n");			//デバック用
				UpFlag = 1;
				ShipInfo_Regist(fp,conn,kouji_id, Mmsi,ShipName, ShipType, ShipLength, ShipWidth, Dest,TsTable,UpFlag,TypeFlag);
			}
			else
			{
				//printf("データが未登録です\n");		//デバック用
				UpFlag = 0;
				ShipInfo_Regist(fp,conn,kouji_id, Mmsi,ShipName, ShipType, ShipLength, ShipWidth, Dest,TsTable ,UpFlag,TypeFlag);
			}
		}

		//■ais_terminalをXML出力
		XML_output(fp,fpx,conn,kouji_id,TsTable);
		fclose(fp);
		PQfinish(conn);
	}
//***********************************************************************//
}

//===========================
// クラスB
//===========================
void AnaMesseTypeClassB(char *BitCode_,int kouji_id)
{
	char MesseIDCode[64] = "";
	char RepIndCode[64] = "";
	char MmsiCode[64] = "";
	char ReserveCode[64] = "";
	char SogCode[64] = "";
	char PosiAccCode[64] = "";
	char LonCode[64] = "";
	char LatCode[64] = "";
	char CogCode[64] = "";
	char THeadCode[64] = "";
	char TimeStCode[64] = "";
	char RegionalCode[64] = "";
	char CsUnitCode[64] = "";
	char DisplayCoed[64] = "";
	char DscCode[64] = "";
	char BandCode[64] = "";
	char Messe22Code[64] = "";
	char AssignedCode[64] = "";
	char RaimCode[64] = "";
	char RadioCode[64] = "";
	
	// コードを切り出し
	strncpy(MesseIDCode, BitCode_ + 0, 6);
	strncpy(RepIndCode, BitCode_ + 6, 2);
	strncpy(MmsiCode, BitCode_ + 8, 30);
	strncpy(ReserveCode, BitCode_ + 38, 8);
	strncpy(SogCode, BitCode_ + 46, 10);
	strncpy(PosiAccCode, BitCode_ + 56, 1);
	strncpy(LonCode, BitCode_ + 57, 28);
	strncpy(LatCode, BitCode_ + 85, 27);
	strncpy(CogCode, BitCode_ + 112, 12);
	strncpy(THeadCode, BitCode_ + 124, 9);
	strncpy(TimeStCode, BitCode_ + 133, 6);
	strncpy(RegionalCode, BitCode_ + 139, 2);
	strncpy(CsUnitCode, BitCode_ + 141, 1);
	strncpy(DisplayCoed, BitCode_ + 142, 1);
	strncpy(DscCode, BitCode_ + 143, 1);
	strncpy(BandCode, BitCode_ + 144, 1);
	strncpy(Messe22Code, BitCode_ + 145, 1);
	strncpy(AssignedCode, BitCode_ + 146, 1);
	strncpy(RaimCode, BitCode_ + 147, 1);
	strncpy(RadioCode, BitCode_ + 148, 20);	
	
	// 各規約に従い変換
	int MesseID = strtol(MesseIDCode, NULL, 2);
	int RepInd = strtol(RepIndCode, NULL, 2);
	int Mmsi = strtol(MmsiCode, NULL, 2);
	int Reserve = strtol(ReserveCode, NULL, 2);
	double Sog = strtol(SogCode, NULL, 2) / 10;
	int PosiAcc = strtol(PosiAccCode, NULL, 2);
	double Lon = strtol(LonCode, NULL, 2) / 10000.0 / 60.0;
	double Lat = strtol(LatCode, NULL, 2) / 10000.0 / 60.0;
	double Cog = strtol(CogCode, NULL, 2) /10.0;
	double THead = strtol(THeadCode, NULL, 2);
	int TimeSt = strtol(TimeStCode, NULL, 2);
	int Regional = strtol(RegionalCode, NULL, 2);
	int CsUnit = strtol(CsUnitCode, NULL, 2);
	int Display = strtol(DisplayCoed, NULL, 2);
	int Dsc = strtol(DscCode, NULL, 2);
	int Band = strtol(BandCode, NULL, 2);
	int Messe22 = strtol(Messe22Code, NULL, 2);
	int Assigned = strtol(AssignedCode, NULL, 2);
	int Raim = strtol(RaimCode, NULL, 2);
	int Radio = strtol(RaimCode, NULL, 2);
	
	// Debug 表示
	/*
	printf("MessegeID => %d\n", MesseID);
	printf("RepInd => %d\n", RepInd);
	printf("MMSI => %d\n", Mmsi);
	printf("Reserve => %d\n", Reserve);
	printf("Sog => %f\n", Sog);
	printf("PosiAcc => %s\n", PosiAcc);
	printf("Lon => %f\n", Lon);
	printf("Lat => %f\n", Lat);
	printf("Cog => %f\n", Cog);
	printf("THead => %f\n", THead);
	printf("TimeSt => %d\n", TimeSt);
	printf("Regional => %d\n", Regional);
	printf("CsUnit => %d\n", CsUnit);
	printf("Display => %d\n", Display);
	printf("Dsc => %d\n", Dsc);
	printf("Band => %d\n", Band);
	printf("Messe22 => %d\n", Messe22);
	printf("Assigned => %d\n", Assigned);
	printf("Raim => %d\n", Raim);
	printf("Radio => %d\n", Radio);
	*/
//***********************************************************************//
	//SQLに登録用の変数の定義(不足分)
	char measure_info[128];		//現在の座標
	//int NaviSt=0;
	//double Rot=0;

	
	//時間関係定義
  	//time_t timer;
   	//struct tm *t_st;
	//char db_time[256];
	int NaviSt;
	int Rot;
	int rows;
	int TypeFlag = 3;

	fp = fopen("./log.txt", "a");
	PGresult *res;				//SQLを実行した戻り値

	memset(&TsTable, 0x00, sizeof(TsTable));
	memset(&HisTable, 0x00, sizeof(HisTable));
	sprintf(TsTable,"qgis.ais_terminal");
	sprintf(HisTable,"qgis.ais_his_measure");
	
	//●データーベースへ接続
	memset(&conn_info, 0x00, sizeof(conn_info));
	sprintf(conn_info,"host=localhost dbname=qgis user=posgre password=posgre");
	conn = PQconnectdb(conn_info);
	
	//●データベース接続確認処理(成功/失敗)
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		//--err出力
		fprintf(fp, "%s\r\n", PQerrorMessage(conn));
		fprintf(fp, "DB接続にerrがありました\r\n");
		fprintf(fp, "接続を解除して終了します\r\n");
		
		//--データーベースとの接続の解除
		PQfinish(conn);
		fclose(fp);
		exit(-1);
	}
	else
	{
		// 現在時刻の取得
		//time(&timer);
		// 現在時刻を構造体に変換
		//t_st = localtime(&timer);

		// 時刻代入
		//memset(&db_time, 0x00, sizeof(db_time));
		//memset(&db_time2, 0x00, sizeof(db_time2));
		//sprintf(db_time,"%d-%d-%d %d:%d:%d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
		
		//■新規データか確認
		//SELECT
		memset(&SqlSelect, 0x00, sizeof(SqlSelect));
		sprintf(SqlSelect, "SELECT terminal_id,measure_info[0],measure_info[1] FROM %s WHERE kouji_id = %d AND terminal_id = %d;", TsTable, kouji_id ,Mmsi);
		res = PQexec(conn, SqlSelect);

		if (PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(fp, "SELECTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", SqlSelect);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
		else
		{
			//printf("SQL実行OK\n");					//デバック用
			rows = PQntuples(res);

			if (rows != 0)
			{
				//printf("データ登録済です\n");			//デバック用
				UpFlag = 1;
				MeasureInfo_Regist(fp,conn,kouji_id,PosiAcc,Mmsi,NaviSt,Rot,Sog,Lat,Lon,Cog,THead,TsTable,UpFlag,TypeFlag);
			}
			else
			{
				//printf("データが未登録です\n");		//デバック用
				UpFlag = 0;
				MeasureInfo_Regist(fp,conn,kouji_id,PosiAcc,Mmsi,NaviSt,Rot,Sog,Lat,Lon,Cog,THead,TsTable,UpFlag,TypeFlag);
				//printf("Mmsi===%d::::Rot==%f:::Navist==%d\n",Mmsi,Rot,NaviSt);
				//printf("Mmsi===%d\n",Mmsi);
			}
		}
		UpFlag = 0;
		MeasureInfo_Regist(fp,conn,kouji_id,PosiAcc,Mmsi,NaviSt,9999,Sog,Lat,Lon,Cog,THead,HisTable,UpFlag,TypeFlag);

		//■ais_terminalをXML出力
		XML_output(fp,fpx,conn,kouji_id,TsTable);
		fclose(fp);
		PQfinish(conn);
	}
//***********************************************************************//
}

//===========================
// クラスB[CS]
//===========================
void AnaMesseTypeClassBCS(char *BitCode_,int kouji_id)
{
	char MesseIDCode[64] = "";
	char RepIndCode[64] = "";
	char MmsiCode[64] = "";
	char PartNoCode[64] = "";
	int TypeFlag = 0;
	
	// PartNoまでを解析
	strncpy(MesseIDCode, BitCode_ + 0, 6);
	strncpy(RepIndCode, BitCode_ + 6, 2);
	strncpy(MmsiCode, BitCode_ + 8, 30);
	strncpy(PartNoCode, BitCode_ + 38, 2);
	
	int MesseID = strtol(MesseIDCode, NULL, 2);
	int RepInd = strtol(RepIndCode, NULL, 2);
	int Mmsi = strtol(MmsiCode, NULL, 2);
	int PartNo = strtol(PartNoCode, NULL, 2);
	

	//printf("MessegeID => %d\n", MesseID);
	//printf("RepInd => %d\n", RepInd);
	//printf("Mmsi => %d\n", Mmsi);
	//printf("PartNo => %d\n", PartNo);

	//●テーブル登録に使用する変数のみ最初に定義
	char ShipName[512] = "";
	int ShipType = 0;
	int DimBow = 0;
	int DimStern = 0;
	int DimPort = 0;
	char Dest[512];
	
	int ShipLength = 0;
	int ShipWidth = 0;
	
	if (PartNo == 0)
	{
		char ShipNameCode[128] = "";
		char SpareCode[64] = "";
		TypeFlag = 4;
		
		strncpy(ShipNameCode, BitCode_ + 40, 120);
		strncpy(SpareCode, BitCode_ + 160, 8);
		
		char ShipName[512] = "";
		SixBit2Char(ShipNameCode, ShipName);
		int Spare = strtol(SpareCode, NULL, 2);
		
		//printf("ShipName => %s\n", ShipName);
		//printf("Spare => %d\n", Spare);
	}
	else if (PartNo == 1)
	{
		char ShipTypeCode[64] = "";
		char VenderIDCode[64] = "";
		char CallSignCode[64] = "";
		char DimBowCode[64] = "";
		char DimSternCode[64] = "";
		char DimPortCode[64] = "";
		char DimStarBoardCode[64] = "";
		char MoShipMmsiCode[64] = "";
		char SpareCode[64] = "";
		TypeFlag = 5;
		
		strncpy(ShipTypeCode, BitCode_ + 40, 8);
		strncpy(VenderIDCode, BitCode_ + 48, 42);
		strncpy(CallSignCode, BitCode_ + 90, 42);
		strncpy(DimBowCode, BitCode_ + 132, 9);
		strncpy(DimSternCode, BitCode_ + 141, 9);
		strncpy(DimPortCode, BitCode_ + 150, 6);
		strncpy(DimStarBoardCode, BitCode_ + 156, 6);
		strncpy(MoShipMmsiCode, BitCode_ + 132, 30);
		strncpy(SpareCode, BitCode_ + 162, 6);
		
		int ShipType = strtol(ShipTypeCode, NULL, 2);
		char VenderID[512] = "";
		SixBit2Char(VenderIDCode, VenderID);
		int CallSign = strtol(CallSignCode, NULL, 2);
		int DimBow = strtol(DimBowCode, NULL, 2);
		int DimStern = strtol(DimSternCode, NULL, 2);
		int DimPort = strtol(DimPortCode, NULL, 2);
		int DimStarBoard = strtol(DimStarBoardCode, NULL, 2);
		int MoShipMmsi = strtol(MoShipMmsiCode, NULL, 2);
		int Spare = strtol(SpareCode, NULL, 2);
		
		ShipLength = DimBow + DimStern;
		ShipWidth = DimPort + DimStarBoard;
		
		//printf("ShipType => %d\n", ShipType);
		//printf("VenderID => %s\n", VenderID);
		//printf("CallSign => %d\n", CallSign);
		//printf("DimBow => %d\n", DimBow);
		//printf("DimStern => %d\n", DimStern);
		//printf("DimPort => %d\n", DimPort);
		//printf("DimStarBoard => %d\n", DimStarBoard);
		//printf("MoShipMmsi => %d\n", MoShipMmsi);
		//printf("Spare => %d\n", Spare);
	}
	
	//***********************************************************************//
	//時間関係定義
  	//time_t timer;
   	//struct tm *t_st;
	//char db_time[256];

	//値の初期化
	int rows;
	int UpFlag;
	fp = fopen("./log.txt", "a");
	PGresult *res;				//SQLを実行した戻り値
	
	memset(&TsTable, 0x00, sizeof(TsTable));
	memset(&HisTable, 0x00, sizeof(HisTable));
	sprintf(TsTable,"qgis.ais_terminal");
	sprintf(HisTable,"qgis.ais_his_measure");
	
	
	// データーベースへ接続
	memset(&conn_info, 0x00, sizeof(conn_info));
	//sprintf(conn_info,"host=localhost dbname=%s user=%s password=%s", dbname, user, password);
	sprintf(conn_info,"host=localhost dbname=qgis user=posgre password=posgre");
	conn = PQconnectdb(conn_info);
	
	// データベース接続確認処理(成功/失敗)
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		// err出力
		fprintf(fp, "%s\r\n", PQerrorMessage(conn));
		fprintf(fp, "DB接続にerrがありました\r\n");
		fprintf(fp, "接続を解除して終了します\r\n");
		
		// データーベースとの接続の解除
		PQfinish(conn);
		
		fclose(fp);
		
		exit(-1);
	}
	else
	{
		// 現在時刻の取得
		//time(&timer);
		// 現在時刻を構造体に変換
		//t_st = localtime(&timer);

		// 時刻代入
		//memset(&db_time, 0x00, sizeof(db_time));
		//sprintf(db_time,"%d-%d-%d %d:%d:%d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
		//printf("現在の時刻==%s\n", db_time);
		
		//■新規データか確認
		//SELECT
		PGresult *res;
		memset(&SqlSelect, 0x00, sizeof(SqlSelect));
		sprintf(SqlSelect, "SELECT terminal_id FROM %s WHERE kouji_id = %d AND terminal_id = %d;", TsTable, kouji_id ,Mmsi);
		res = PQexec(conn, SqlSelect);

		//insert
		if (PQresultStatus(res) != PGRES_TUPLES_OK)
		{
			fprintf(fp, "SELECTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", SqlSelect);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
		else
		{
			//printf("SQL実行OK\n");					//デバック用
			rows = PQntuples(res);

			if (rows != 0)
			{
				//printf("データ登録済です\n");			//デバック用
				UpFlag = 1;
				ShipInfo_Regist(fp,conn,kouji_id, Mmsi,ShipName, ShipType, ShipLength, ShipWidth, Dest,TsTable,UpFlag,TypeFlag);
			}
			else
			{
				//printf("データが未登録です\n");		//デバック用
				UpFlag = 0;
				ShipInfo_Regist(fp,conn,kouji_id, Mmsi,ShipName, ShipType, ShipLength, ShipWidth, Dest,TsTable ,UpFlag,TypeFlag);
			}
		}

		//■ais_terminalをXML出力
		XML_output(fp,fpx,conn,kouji_id,TsTable);
		fclose(fp);
		PQfinish(conn);
	}

//***********************************************************************//
	
}

//■■■船舶の位置情報をais_terminalに新規登録または更新,his_measureへの新規登録■■■
int MeasureInfo_Regist(FILE *fp, PGconn *conn , int kouji_id, int PosiAc, int Mmsi, int NaviSt, double Rot, double Sog, double Lat, double Lon, double Cog, double THead, char *TsTable, int UpFlag, int TypeFlag)
{
	//SQL文用変数
	char sql[2048];
	PGresult *res;
   
   if((PosiAc != 9999) && (Mmsi != 0))
   {
		memset(&sql, 0x00, sizeof(sql));
	
		if(UpFlag == 0)
		{
			//printf("measure_INSERT:::::::Mmsi========%d\n",Mmsi);
			if(TypeFlag == 1)
			{
				sprintf(sql, "INSERT INTO %s (terminal_id,kouji_id, navigation_st ,posi_acc, measure_info, rot, sog, cog, hdg, regdatetime, upddatetime) VALUES ('%d','%d', '%d', '%d','(%f,%f)', '%f', '%f', '%f', '%f', current_timestamp, current_timestamp);", TsTable, Mmsi, kouji_id,NaviSt, PosiAc, Lon, Lat, Rot, Sog, Cog, THead);
			}
			else if(TypeFlag == 3)
			{
				sprintf(sql, "INSERT INTO %s (terminal_id,kouji_id,posi_acc, measure_info, sog, cog, hdg, regdatetime, upddatetime) VALUES ('%d','%d', '%d','(%f,%f)', '%f', '%f', '%f', current_timestamp, current_timestamp);", TsTable, Mmsi, kouji_id, PosiAc, Lon, Lat, Rot, Sog, Cog, THead);
			}
		}
		else
		{
			//printf("measure_UPDATW:::::::Mmsi========%d\n",Mmsi);
			if(TypeFlag == 1)
			{
				sprintf(sql, "UPDATE %s SET navigation_st = '%d' ,posi_acc = '%d', measure_info = '(%f,%f)' , rot = '%f', sog = '%f', cog = '%f', hdg = '%f', upddatetime = current_timestamp WHERE terminal_id = %d;", TsTable,NaviSt, PosiAc, Lon, Lat, Rot, Sog, Cog, THead, Mmsi);
			}
			else if(TypeFlag == 3)
			{
				sprintf(sql, "UPDATE %s SET posi_acc = '%d', measure_info = '(%f,%f)' , sog = '%f', cog = '%f', hdg = '%f', upddatetime = current_timestamp WHERE terminal_id = %d;", TsTable, PosiAc, Lon, Lat, Rot, Sog, Cog, THead, Mmsi);
			}
		}

		res = PQexec(conn, sql);

		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(fp, "Term_INSERTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", sql);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
	}
	return 0;
}

//■■■船舶情報をais_terminalに新規登録または更新■■■
int ShipInfo_Regist(FILE *fp, PGconn *conn , int kouji_id, int Mmsi ,char *ShipName ,int ShipType, int ShipLength, int ShipWidth, char *Dest, char *TsTable, int UpFlag, int TypeFlag)
{
	//SQL文用変数
	char sql[2048];
	PGresult *res;

   if(Mmsi != 0)
   {
		memset(&sql, 0x00, sizeof(sql));
	
		if(UpFlag == 0)
		{
			//printf("Ship_INSERT:::::::Mmsi========%d\n",Mmsi);
			if(TypeFlag == 2)
			{
				sprintf(sql, "INSERT INTO %s (terminal_id,kouji_id, ship_name ,ship_type, ship_width, ship_height, destination, regdatetime, upddatetime) VALUES ('%d','%d', '%s', '%d', '%d', '%d', '%s', current_timestamp, current_timestamp);", TsTable, Mmsi, kouji_id,ShipName, ShipType, ShipWidth, ShipLength, Dest);
				//printf("sql======%s\n" ,sql);
				//fprintf(fp, "%s\n", sql);
			}
			else if(TypeFlag == 4)
			{
				sprintf(sql, "INSERT INTO %s (terminal_id,kouji_id, ship_name ,regdatetime, upddatetime) VALUES ('%d','%d', '%s', current_timestamp, current_timestamp);", TsTable, Mmsi, kouji_id,ShipName);
			}
			else if(TypeFlag == 5)
			{
				sprintf(sql, "INSERT INTO %s (terminal_id,kouji_id,ship_type, ship_width, ship_height, regdatetime, upddatetime) VALUES ('%d','%d', '%d', '%d', '%d', current_timestamp, current_timestamp);", TsTable, Mmsi, kouji_id, ShipType, ShipWidth, ShipLength);
			}
		}
		else
		{
			//printf("measure_UPDATW:::::::Mmsi========%d\n",Mmsi);
			if(TypeFlag == 2)
			{
				sprintf(sql, "UPDATE %s SET ship_name = '%s' ,ship_type = '%d', ship_width = '%d' , ship_height = '%d', destination = '%s', upddatetime = current_timestamp WHERE terminal_id = %d;", TsTable,ShipName, ShipType, ShipWidth, ShipLength, Dest, Mmsi);
			}
			else if(TypeFlag == 4)
			{
				sprintf(sql, "UPDATE %s SET ship_name = '%s' , upddatetime = current_timestamp WHERE terminal_id = %d;", TsTable,ShipName, Mmsi);
			}
			else if(TypeFlag == 5)
			{
				sprintf(sql, "UPDATE %s SET ship_type = '%d', ship_width = '%d' , ship_height = '%d', upddatetime = current_timestamp WHERE terminal_id = %d;", TsTable,ShipType, ShipWidth, ShipLength, Mmsi);
			}
		}

		res = PQexec(conn, sql);

		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(fp, "Term_INSERTの実行に失敗しました。%s\n", PQerrorMessage(conn));
			fprintf(fp, "%s\n", sql);
			PQclear(res);
			PQfinish(conn);
			exit(1);
		}
	}
	fclose(fp);
	return 0;
}

//■■■ais_terminalをXMLファイルに出力■■■
int XML_output(FILE *fp,FILE *fpx, PGconn *conn , int kouji_id, char *TsTable)
{
	//SQL文用変数
	char sql[2048];
	PGresult *res;
	int rows;
	int ii;
	
	memset(&sql, 0x00, sizeof(sql));
//	printf("sql = %s\n" ,sql);
	sprintf(sql, "SELECT * FROM %s WHERE kouji_id = %d AND upddatetime > current_timestamp + '-7 days' ORDER BY upddatetime desc;", TsTable, kouji_id);
	res = PQexec(conn, sql);

	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(fp, "SELECTの実行に失敗しました。%s\n", PQerrorMessage(conn));
		fprintf(fp, "%s\n", sql);
		PQclear(res);
		PQfinish(conn);
		exit(1);
	}
	else
	{
		rows = PQntuples(res);

		if (rows != 0)
		{
			fpx = fopen(ToFolder, "w");
			fprintf(fpx, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			fprintf(fpx, "<rss version=\"2.0\">\n\n");

			for(ii = 0;ii < rows;ii++)
			{
				fprintf(fpx, "\t<term>\n");
				fprintf(fpx, "\t\t<terminal_id>%s</terminal_id>\n",PQgetvalue(res, ii, 0));
				fprintf(fpx, "\t\t<kouji_id>%s</kouji_id>\n",PQgetvalue(res, ii, 1));
				fprintf(fpx, "\t\t<navigation_st>%s</navigation_st>\n",PQgetvalue(res, ii, 2));
				fprintf(fpx, "\t\t<rot>%s</rot>\n",PQgetvalue(res, ii, 3));
				fprintf(fpx, "\t\t<sog>%s</sog>\n",PQgetvalue(res, ii, 4));
				fprintf(fpx, "\t\t<cog>%s</cog>\n",PQgetvalue(res, ii, 5));
				fprintf(fpx, "\t\t<hdg>%s</hdg>\n",PQgetvalue(res, ii, 6));
				fprintf(fpx, "\t\t<posi_acc>%s</posi_acc>\n",PQgetvalue(res, ii, 7));
				fprintf(fpx, "\t\t<measure_info>%s</measure_info>\n",PQgetvalue(res, ii, 8));
				fprintf(fpx, "\t\t<ship_name>%s</ship_name>\n",PQgetvalue(res, ii, 9));
				fprintf(fpx, "\t\t<ship_type>%s</ship_type>\n",PQgetvalue(res, ii, 10));
				fprintf(fpx, "\t\t<ship_width>%s</ship_width>\n",PQgetvalue(res, ii, 11));
				fprintf(fpx, "\t\t<ship_height>%s</ship_height>\n",PQgetvalue(res, ii, 12));
				fprintf(fpx, "\t\t<destination>%s</destination>\n",PQgetvalue(res, ii, 13));
				fprintf(fpx, "\t\t<upddatetime>%s</upddatetime>\n",PQgetvalue(res, ii, 14));
				fprintf(fpx, "\t\t<regdatetime>%s</regdatetime>\n",PQgetvalue(res, ii, 15));
				fprintf(fpx, "\t</term>\n");
				//strcpy(TermID, PQgetvalue(res, 0, 0));
				//strcpy(Longi, PQgetvalue(res, 0, 1));
				//strcpy(Lati, PQgetvalue(res, 0, 2));
			}
			fprintf(fpx, "</rss>\n");
			fclose(fpx);
		}
	}
	return 0;
}

