/**********************************************************************
*  Project: sdf2ogr
* Purpose:   OGR Library  use Simple and Quick  Convert SDF file 
*  Author: t.nishioka
* file name :sdf_read.c
*discription : read SDF file and create OGR Datasource

 ******************************************************************************
 * Copyright (c) 2004 Takaaki Nishioka
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************
 *
 **********************************************************************/
#define MAX_LINE_SIZE 1024
#include "ogr_api.h"
#include "sdf_ogr.h"
#include "string.h"

#ifdef USE_ICONV
#include <iconv.h>
#endif


/*------------------------------------------------------
*
*道路の属性データのファイルごとに構造体に入力する
*void readAtrFiletoObjecttoObjecttoObject(char *filename)
-------------------------------------------------------*/
atr_P *readAtrFiletoObject(const char *filename)
{
   FILE *fp;
   char buf[MAX_LINE_SIZE];
   arch_P ah;//arc用のheader構造体
   atr_P *atrH,*begin;
   if( (atrH = malloc(sizeof(atr_P) )) == NULL ){
      perror("malloc");
      exit(1);
   }
   begin = atrH;
	atrH->next = NULL;
   if(!(fp = fopen(filename,"r"))){
      perror("fopen");
      exit(1);
   }

    //一行目を取得
    if(fgets(buf,MAX_LINE_SIZE,fp) == NULL){
       perror("fgets");
	}
	replaceSpace(buf);//カンマをスペースに変換
    if( (sscanf(buf,"%s %s %s %d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf"
       ,
    ah.FH,ah.zumei,ah.filename
    ,&ah.recordC,&ah.fieldC,&ah.CoordFlag,&ah.Coordinate,&ah.kubun
    ,&ah.llx,&ah.lly,&ah.rux,&ah.ruy
    ,&ah.lux,&ah.luy,&ah.rlx,&ah.rly) )== EOF ){
          perror("sscanf");
          exit(1);
       }
       

	while(fgets(buf,MAX_LINE_SIZE,fp) ){//ファイルの読み込み
		replaceSpace(buf);//カンマをスペースに変換
		sscanf(buf,"%s %s %d %s %s %s %s",atrH->code,atrH->pubKey,&atrH->count,atrH->field1, atrH->field2,atrH->field3, atrH->field4 );
		if( (atrH->next = malloc(sizeof(atr_P) )) == NULL ){
			perror("malloc");
			exit(1);
		}

       atrH = atrH->next;
       atrH->next = NULL;

   }

   fclose(fp);
   return begin;//先頭ポインタを返す
}
/*------------------------------------------------------
*
*PGNデータのファイルを構造体に入力する
*void readPgnFiletoObject(char *filename)
-------------------------------------------------------*/
pgn_P *readPgnFiletoObject(const char *filename,const  arc_P  *arcH)
{
   FILE *fp;
   char buf[MAX_LINE_SIZE];
   arch_P ah;//header構造体
	const arc_P  *ahead;//ARCデータの先頭
	pgn_P *pgnH,*begin;//PGNデータの構造体
	int i,j,rtn;
	char tempArc[20];
	int signs;
	int polygonCounter =0;//ポリゴンの線分数
	int charLength = 0;
	
//	ahead = arcH;//先頭を記憶
	
	if( (pgnH =  malloc(sizeof(pgn_P) )) == NULL ){
      perror("malloc");
      exit(1);
	}

   begin = pgnH;//先頭を記憶
   pgnH->next = NULL;
   if(!(fp = fopen(filename,"r"))){
      perror("fopen");
      exit(1);
   }

    //一行目を取得
    if(fgets(buf,MAX_LINE_SIZE,fp) == NULL){
       perror("fgets");
	}

	replaceSpace(buf);//カンマをスペースに変換
    if( (sscanf(buf,"%s %s %s %d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf"
       ,
    ah.FH,ah.zumei,ah.filename
    ,&ah.recordC,&ah.fieldC,&ah.CoordFlag,&ah.Coordinate,&ah.kubun
    ,&ah.llx,&ah.lly,&ah.rux,&ah.ruy
    ,&ah.lux,&ah.luy,&ah.rlx,&ah.rly) )== EOF ){
          perror("sscanf");
          exit(1);
	}

#ifdef DEBUG
	printf("%s %d\n",ah.filename,ah.fieldC);
#endif

	while(fgets(buf,MAX_LINE_SIZE,fp)  != NULL){//ファイルの読み込み

		polygonCounter =0;
		replaceSpace(buf);//カンマをスペースに変換
		rtn = sscanf(buf,"%s %s %d %lf %lf",pgnH->code,pgnH->pubKey, &pgnH->count , &pgnH->cX, &pgnH->cY);
		//入力のチェック
		if( 0 == pgnH->count ){
			continue;
		}
				
		for(i=0;i<pgnH->count;i++){
			if(fgets(buf,MAX_LINE_SIZE,fp)!=NULL){

				replaceSpace(buf);//カンマをスペースに変換
				sscanf(buf,"%s",tempArc);
				if( tempArc[0]  < 0x2b && tempArc[0]  > 0x3a  )//
						break;
				
				if( tempArc[0] == '-' ){//逆周りかどうかの確認;
					signs = 0;

					for(charLength=0;charLength<strlen(tempArc);charLength++){//数字の値
						tempArc[charLength] = tempArc[charLength+1];
						// - を抜き取る
					}
				//逆周り;
				}else
					signs = 1;

				ahead = arcH;

				while(ahead != NULL ){
					
					if( 0 == strcmp(ahead->pubKey , tempArc) ){//Pgnの構成要素を見つけた場合
							
						if( signs ==1 ){
							for(j=0;j<ahead->count;j++){
								pgnH->pX[polygonCounter] =  ahead->pX[j];
								pgnH->pY[polygonCounter] =  ahead->pY[j];
								polygonCounter++;
							}
						}else{
							for(j=ahead->count;j > 0 ;j--){
								pgnH->pX[polygonCounter] =  ahead->pX[j-1];
								pgnH->pY[polygonCounter] =  ahead->pY[j-1];
								polygonCounter++;
							}
						}
						break;
					}

					ahead = ahead->next;
				}

			}

       }
       if( (pgnH->next = malloc(sizeof(pgn_P) )) == NULL ){
          perror("malloc");
          exit(1);
		}
		pgnH->maxPoints = polygonCounter;
       pgnH = pgnH->next;
       pgnH->next = NULL;

   }
	

	fclose(fp);//ファイルポインタを閉じる
   return begin;//先頭ポインタを返す
}
/*------------------------------------------------------
*
*ARCデータのファイルを構造体に入力する
*void readArcFiletoObject(char *filename)
-------------------------------------------------------*/
arc_P *readArcFiletoObject(const char *filename)
{
   FILE *fp;
   char buf[MAX_LINE_SIZE];
   arch_P ah;//header構造体
	arc_P *arcH,*begin;//図形データの構造体
	int i,rtn;
	double tmpx,tmpy;
	
	if( (arcH =  malloc(sizeof(arc_P) )) == NULL ){
      perror("malloc");
      exit(1);
	}

   begin = arcH;
   arcH->next = NULL;
   if(!(fp = fopen(filename,"r"))){
      perror("fopen");
      exit(1);
   }

    //一行目を取得
    if(fgets(buf,MAX_LINE_SIZE,fp) == NULL){
       perror("fgets");
	}
	replaceSpace(buf);//カンマをスペースに変換
    if( (sscanf(buf,"%s %s %s %d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf"
       ,
    ah.FH,ah.zumei,ah.filename
    ,&ah.recordC,&ah.fieldC,&ah.CoordFlag,&ah.Coordinate,&ah.kubun
    ,&ah.llx,&ah.lly,&ah.rux,&ah.ruy
    ,&ah.lux,&ah.luy,&ah.rlx,&ah.rly) )== EOF ){
          perror("sscanf");
          exit(1);
	}

#ifdef DEBUG
	printf("%s %d\n",ah.filename,ah.fieldC);
#endif

	while(fgets(buf,MAX_LINE_SIZE,fp)  != NULL){//ファイルの読み込み

		replaceSpace(buf);//カンマをスペースに変換
		rtn = sscanf(buf,"%s %d %s %d",arcH->code, &arcH->lineTag,arcH->pubKey, &arcH->count );

		//入力のチェック
		if( 0 == arcH->count ){
			continue;
		}
				
		for(i=0;i<arcH->count;i++){
          if(fgets(buf,MAX_LINE_SIZE,fp)!=NULL){
				replaceSpace(buf);//カンマをスペースに変換
				sscanf(buf,"%lf %lf",&tmpx, &tmpy);

				arcH->pY[i] =  ah.llx + tmpx;
				arcH->pX[i] =  ah.lly + tmpy;
//OGRのXYと数値地図のXYは逆
          }
       }
       if( (arcH->next = malloc(sizeof(arc_P) )) == NULL ){
          perror("malloc");
          exit(1);
		}
		arcH = arcH->next;
		arcH->next = NULL;
	}

	fclose(fp);//ファイルポインタを閉じる
	return begin;//先頭ポインタを返す
}
/*------------------------------------------------------
*
*属性データのメモリ解放
*void reeAtrFile(atr_P *);
返り値なし
引数　解放するメモリの先頭ポインタ
-------------------------------------------------------*/
void freeAtrFile(atr_P  *atrH)
{
	atr_P  *begin;
	begin = atrH;
   while( begin->next != NULL ){//mallocで確保したメモリの開放※オマジナイ
//      printf("%s\n",begin->field1);
      atrH = begin;
      begin = begin->next;
      free(atrH);
   }

	return ;
}
/*------------------------------------------------------
*
*ARCデータのメモリ解放
*void freeArcFile(atr_P *);
返り値なし
引数　解放するメモリの先頭ポインタ
-------------------------------------------------------*/
void freeArcFile(arc_P  *arcH)
{
	arc_P  *begin;
	begin = arcH;
   while( begin->next != NULL ){//mallocで確保したメモリの開放※オマジナイ
//      printf("%s\n",begin->field1);
      arcH = begin;
      begin = begin->next;
      free(arcH);
   }
	return ;
}
/*------------------------------------------------------
*
*Polygonデータのメモリ解放
void freePgnFile(pgn_P  *pgnH)
返り値なし
引数　解放するメモリの先頭ポインタ
-------------------------------------------------------*/
void freePgnFile(pgn_P  *pgnH)
{
	pgn_P  *begin;
	begin = pgnH;
   while( begin->next != NULL ){//mallocで確保したメモリの開放※オマジナイ
//      printf("%s\n",begin->field1);
      pgnH = begin;
      begin = begin->next;
      free(pgnH);
   }
	return ;
}
/*------------------------------------------------------
*
*道路のarcデータのファイルごとに構造体に入力する
*void readAtrFile(OGRDataSourceH datasource,char *attfile,char *arcfile)
返り値なし
引数　道路ファイルのパス、道路ファイルの属性パス
-------------------------------------------------------*/
void readAtrFile(OGRDataSourceH datasource,const char *attfile,const char *arcfile)
{
	arc_P *arcH;//図形データの構造体
	atr_P *atrH;//属性データの構造体
	int  rtn;
	
	arcH = readArcFiletoObject(arcfile);
	atrH = readAtrFiletoObject(attfile);//属性データの読み込み
	
	//データの書き出し
	rtn = createOGRLinstringObjectFromAtr(datasource,arcH,atrH);
	
	freeAtrFile(atrH);//属性データのmemory解放
	freeArcFile(arcH);
	
   return ;
}
/*------------------------------------------------------
*
*道路のarcデータのファイルごとに構造体に入力する
*void readArcFile(OGRDataSourceH datasource,char *filename,char *attfile)
返り値なし
引数　道路ファイルのパス、道路ファイルの属性パス
-------------------------------------------------------*/
void readArcFile(OGRDataSourceH datasource,const char *arcfile,const char *attfile)
{
	arc_P *arcH;//図形データの構造体
	atr_P *atrH;//属性データの構造体
	int rtn;
	
	arcH = readArcFiletoObject(arcfile);
	atrH = readAtrFiletoObject(attfile);//属性データの読み込み
	
	//データの書き出し
	rtn = createOGRLinstringObject(datasource,arcH,atrH);
	
	freeAtrFile(atrH);//属性データのmemory解放
	freeArcFile(arcH);
	
   return ;
}
/*------------------------------------------------------
*
*道路のarcデータのファイルごとに構造体に入力する
*void readPgnFile(char *filename,char *attfile)
返り値なし
引数　道路ファイルのパス、道路ファイルの属性パス
-------------------------------------------------------*/
void readPgnFile(OGRDataSourceH datasource,const char *pgnfile ,const char *arcfile,const char *attfile)
{

	pgn_P *pgnH;//arcデータの構造体
	arc_P *arcH;//arcデータの構造体
	atr_P *atrH;//属性データの構造体
	
	int rtn;


	arcH = readArcFiletoObject(arcfile);
	pgnH = readPgnFiletoObject(pgnfile,arcH);
	
	atrH = readAtrFiletoObject(attfile);//属性データの読み込み

	
	rtn = createOGRPolygonObject(datasource,pgnH,atrH);

	freeAtrFile(atrH);//属性データのmemory解放
	freeArcFile(arcH);//ArcData is free memory
	freePgnFile(pgnH);//ArcData is free memory
	return ;
}
/*------------------------------------------------------
*
Pointデータのファイルごとに構造体に入力する
*void readPntFile(char *filename,char *attfile)
返り値なし
引数　Pointファイルのパス、Pointファイルの属性パス
-------------------------------------------------------*/
void readPntFile( OGRDataSourceH datasource,const char *filename,const char *attfile)
{
   FILE *fp;
   char buf[MAX_LINE_SIZE];
   arch_P ah;//header構造体
	pnt_P *pntH,*begin;//図形データの構造体
	atr_P *atrH;//属性データの構造体
	int rtn;
	double tmpx,tmpy;

	if( (pntH =  malloc(sizeof(pnt_P) )) == NULL ){
      perror("malloc");
      exit(1);
	}

   begin = pntH;
	pntH->next = NULL;

   if(!(fp = fopen(filename,"r"))){
      perror("fopen");
      exit(1);
   }

    //一行目を取得
    if(fgets(buf,MAX_LINE_SIZE,fp) == NULL){
       perror("fgets");
	}
	replaceSpace(buf);//カンマをスペースに変換
    if( (sscanf(buf,"%s %s %s %d %d %d %d %d %lf %lf %lf %lf %lf %lf %lf %lf"
       ,
    ah.FH,ah.zumei,ah.filename
    ,&ah.recordC,&ah.fieldC,&ah.CoordFlag,&ah.Coordinate,&ah.kubun
    ,&ah.llx,&ah.lly,&ah.rux,&ah.ruy
    ,&ah.lux,&ah.luy,&ah.rlx,&ah.rly) )== EOF ){
          perror("sscanf");
          exit(1);
	}

#ifdef DEBUG
	printf("%s %d\n",ah.filename,ah.fieldC);
#endif
  
   while(fgets(buf,MAX_LINE_SIZE,fp)  != NULL){//ファイルの読み込み
		replaceSpace(buf);//カンマをスペースに変換
		rtn = sscanf(buf,"%s %s %lf %lf",pntH->code, pntH->pubKey,&tmpx, &tmpy );
		pntH->pY =  ah.llx + tmpx;
		pntH->pX =  ah.lly + tmpy;
       if( (pntH->next = malloc(sizeof(arc_P) )) == NULL ){//次のポイント領域の確保
          perror("malloc");
          exit(1);
		}
       pntH = pntH->next;
       pntH->next = NULL;

   }

	rtn = fclose(fp);//ファイルポインタを閉じる	
	atrH = readAtrFiletoObject(attfile);//属性データの読み込み
	
	rtn = createOGRPointObject(datasource,begin,atrH);
	freeAtrFile(atrH);//属性データのmemory解放
	
   while( begin != NULL ){//mallocで確保したメモリの開放
      pntH = begin;
      begin = begin->next;
      free(pntH);
	}

   return ;
}
/*------------------------------------------------------
*
*
OGRLayerH createOGRLinstringObject(const arc_P * arcH,const atr_P * atrH)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　道路ファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
int createOGRLinstringObject(OGRDataSourceH datasource ,const arc_P * arcH,const atr_P * atrH){
    int             i;
    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFeatureH     feature;
	OGRGeometryH    geometry;
	
	const atr_P *begin;
	begin = atrH;

    /* MapInfo data sources are created with one empty layer.
	Fetch the layer handle */
    layer = OGR_DS_GetLayer(datasource, 0);
    if (layer == NULL)
    {
        printf("Unable to create new layer in  RoadObj\n");
        return -1;
    }
	layerDefn = OGR_L_GetLayerDefn( layer );

    /* Create a new line */

	//地図データの作成
	while( arcH->next != NULL){//
		geometry = OGR_G_CreateGeometry( wkbLineString );

		for(i=0;i<arcH->count;i++){
			OGR_G_AddPoint(geometry, arcH->pX[i], arcH->pY[i],0);
		}

		feature = OGR_F_Create( layerDefn );
		//該当する属性を検索する
		while(  atrH->next != NULL ){
			if(  0 == strcmp( arcH->pubKey , atrH->pubKey)){
            


				OGR_F_SetFieldString( feature, 0, atrH->code);
				OGR_F_SetFieldString( feature, 1, atrH->pubKey);
				OGR_F_SetFieldInteger( feature, 2, atrH->count);
				OGR_F_SetFieldString( feature, 3, atrH->field1);
				OGR_F_SetFieldString( feature, 4, atrH->field2);
				OGR_F_SetFieldString( feature, 5, atrH->field3);
				OGR_F_SetFieldString( feature, 6, atrH->field4);
				OGR_F_SetFieldString( feature, 7, NULL);
			}
			atrH = atrH->next;
		}

		OGR_F_SetGeometryDirectly(feature, geometry);
		OGR_L_CreateFeature( layer, feature );
		arcH = arcH->next;
		atrH = begin;
		if(arcH == NULL  || atrH == NULL )
				break;
	}

    return 0;
}
/*------------------------------------------------------
*
*
char *convertEncoding(const char *str)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　道路ファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
char *convertEncodingEUC(const char *str)
{
#ifdef USE_ICONV
  iconv_t cd = NULL;
  char *in, *inp;
  char *outp, *out = NULL;
  size_t len, bufsize, bufleft, status;

  cd = iconv_open("EUC-JP", "SJIS");
  if(cd == (iconv_t)-1) {
    msSetError(MS_IDENTERR, "Encoding not supported by libiconv (SJIS).",
               "msGetEncodedString()");
    return NULL;
  }
  
  len = strlen(string);
  bufsize = len * 4;
  in = strdup(string);
  inp = in;
  out = (char*) malloc(bufsize);
  if(in == NULL || out == NULL){
    msSetError(MS_MEMERR, NULL, "msGetEncodedString()");
    msFree(in);
    iconv_close(cd);
    return NULL;
  }
  strcpy(out, in);
  outp = out;

  bufleft = bufsize;
  status = -1;

  while (len > 0){
    status = iconv(cd, &inp, &len, &outp, &bufleft);
    if(status == -1){
      msFree(in);
      msFree(out);
      iconv_close(cd);
      return strdup(string);
    }
  }
  out[bufsize - bufleft] = '\0';

  msFree(in);
  iconv_close(cd);

  return out;

#endif
   return *str;
}
/*------------------------------------------------------
*
*
OGRLayerH createOGRLinstringObjectFromAtr(const arc_P * arcH,const atr_P * atrH)
*鉄道データは、鉄道属性ファイルからしか線情報を持ってくることができない
返り値 OGRLayerH　OGRのレイヤハンドル
引数　道路ファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
int createOGRLinstringObjectFromAtr(OGRDataSourceH datasource ,const arc_P * arcH,const atr_P * atrH){
    int             i;
    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFeatureH     feature;
	OGRGeometryH    geometry;
	const arc_P *begin;
	begin = arcH;

    /* MapInfo data sources are created with one empty layer.
	Fetch the layer handle */
    layer = OGR_DS_GetLayer(datasource, 0);
    if (layer == NULL)
    {
        printf("Unable to create new layer in  RoadObj\n");
        return -1;
    }
	layerDefn = OGR_L_GetLayerDefn( layer );

    /* Create a new line */

	//地図データの作成
	while( atrH->next != NULL){//
		geometry = OGR_G_CreateGeometry( wkbLineString );
		
		//該当する属性を検索する
		while(  arcH->next != NULL ){
			if(  0 == strcmp( arcH->pubKey , atrH->pubKey)){
				
				for(i=0;i<arcH->count;i++){
					OGR_G_AddPoint(geometry, arcH->pX[i], arcH->pY[i],0);
				}
			}
			arcH = arcH->next;
		}

		feature = OGR_F_Create( layerDefn );

		OGR_F_SetFieldString( feature, 0, atrH->code);
		OGR_F_SetFieldString( feature, 1, atrH->pubKey);
		OGR_F_SetFieldInteger( feature, 2, atrH->count);
		OGR_F_SetFieldString( feature, 3, atrH->field1);
		OGR_F_SetFieldString( feature, 4, atrH->field2);
		OGR_F_SetFieldString( feature, 5, atrH->field3);
		OGR_F_SetFieldString( feature, 6, atrH->field4);
		OGR_F_SetFieldString( feature, 7, NULL);

		OGR_F_SetGeometryDirectly(feature, geometry);
		OGR_L_CreateFeature( layer, feature );
		atrH = atrH->next;
		arcH = begin;
		if(arcH == NULL  || atrH == NULL )
				break;
	}

    return 0;
}
/*------------------------------------------------------
*
*OGRを用いてPolygonデータを作成する
int createOGRPolygonObject( OGRDataSourceH datasource ,const pgn_P * pgnH,const atr_P * atrH)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　TABfileのデータソース、道路ファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
int createOGRPolygonObject( OGRDataSourceH datasource ,const pgn_P * pgnH,const atr_P * atrH){
	long i;
    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFeatureH     feature;
	OGRGeometryH    geometry, ring;
	const atr_P *begin;
	
	begin = atrH;

    /* MapInfo data sources are created with one empty layer.
	Fetch the layer handle */
    layer = OGR_DS_GetLayer(datasource, 0);
    if (layer == NULL)
    {
        printf("Unable to create new layer in  Obj\n");
        return -1;
	}

	layerDefn = OGR_L_GetLayerDefn( layer );

    /* Create a new line */

	//Pointデータの作成
	while( pgnH->next != NULL ){//
	
		geometry = OGR_G_CreateGeometry( wkbPolygon );
		ring = OGR_G_CreateGeometry( wkbLinearRing );
		i =0;
		for(i=0; i < pgnH->maxPoints;i++){
			 OGR_G_AddPoint(ring, pgnH->pX[i], pgnH->pY[i], 0);
		}
	
		feature = OGR_F_Create( layerDefn );
		//該当する属性を検索する
		while(  atrH->next != NULL ){
			if(  0 == strcmp( pgnH->pubKey , atrH->pubKey)){
				OGR_F_SetFieldString( feature, 0, atrH->code);
				OGR_F_SetFieldString( feature, 1, atrH->pubKey);
				OGR_F_SetFieldInteger( feature, 2, atrH->count);
				OGR_F_SetFieldString( feature, 3, atrH->field1);
				OGR_F_SetFieldString( feature, 4, atrH->field2);
				OGR_F_SetFieldString( feature, 5, atrH->field3);
				OGR_F_SetFieldString( feature, 6, atrH->field4);
				OGR_F_SetFieldString( feature, 7, NULL);
			}
			atrH = atrH->next;
		}

			
		atrH = begin;
		pgnH = pgnH->next;
		
		OGR_G_AddGeometryDirectly(geometry, ring);
		OGR_F_SetGeometryDirectly(feature, geometry);
		OGR_L_CreateFeature( layer, feature );
				
	}

    /* Close data source */

    return 0;
}
/*------------------------------------------------------
*
*OGRを用いてポイントデータを作成する
OGRLayerH createOGRPointObject(OGRDataSourceH datasource,const pnt_P * pntH,const atr_P * atrH)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　TABfileのデータソース、pointファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
int createOGRPointObject( OGRDataSourceH datasource ,const pnt_P * pntH,const atr_P * atrH){
	int             i;
    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFeatureH     feature;
	OGRGeometryH    geometry;
//	arc_P *begin = arcH;
	
	const atr_P *begin;
	begin = atrH;

    /* MapInfo data sources are created with one empty layer.
	Fetch the layer handle */
    layer = OGR_DS_GetLayer(datasource, 0);
    if (layer == NULL)
    {
        printf("Unable to create new layer in  RoadObj\n");
        return -1;
	}

	layerDefn = OGR_L_GetLayerDefn( layer );

    /* Create a new line */

	//Pointデータの作成
	while( pntH->next != NULL ){//
		geometry = OGR_G_CreateGeometry( wkbPoint );
		i =0;
    
		OGR_G_SetPoint(geometry, 0, pntH->pX, pntH->pY, 0);
		feature = OGR_F_Create( layerDefn );
		//該当する属性を検索する
		while(  atrH->next != NULL ){
			if(  0 == strcmp( pntH->pubKey , atrH->pubKey)){
				OGR_F_SetFieldString( feature, 0, atrH->code);
				OGR_F_SetFieldString( feature, 1, atrH->pubKey);
				OGR_F_SetFieldInteger( feature, 2, atrH->count);
				OGR_F_SetFieldString( feature, 3, atrH->field1);
				OGR_F_SetFieldString( feature, 4, atrH->field2);
				OGR_F_SetFieldString( feature, 5, atrH->field3);
				OGR_F_SetFieldString( feature, 6, atrH->field4);
				OGR_F_SetFieldString( feature, 7, NULL);
			}
			atrH = atrH->next;
		}
			
		atrH = begin;
		pntH = pntH->next;
		OGR_F_SetGeometryDirectly(feature, geometry);
		OGR_L_CreateFeature( layer, feature );
	}

    /* Close data source */
    return 0;
}
/*------------------------------------------------------

OGRLayerH createDataSouce(createDataresouce)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　OGRresourceファイルのパス、
-------------------------------------------------------*/
OGRDataSourceH createDataSouce(OGRDataSourceH datasource,const char *pszName
 , const	OGRSpatialReferenceH sRef){
	//
    OGRSFDriverH    driver;
    int             i, numDrivers;

    OGRLayerH       layer;
    OGRFeatureDefnH layerDefn;
    OGRFieldDefnH   fieldDefn;
//	arc_P *begin = arcH;
	char     *papszOptions;

    /* Register all OGR drivers */
    OGRRegisterAll();

    /* Fetch MITAB driver - we want to create a TAB file */
    numDrivers = OGRGetDriverCount();
    for(i=0; i<numDrivers; i++)
    {
		driver = OGRGetDriver(i);
        if (EQUAL("MapInfo File", OGR_Dr_GetName(driver)))
            break;  /* Found it! */
        driver = NULL;
    }

    if (!driver)
    {
        printf("Driver not found!\n");
        exit(1);
    }

    /* Create new file using this driver */
    datasource = OGR_Dr_CreateDataSource(driver, pszName, NULL);

    if (datasource == NULL)
    {
        printf("Unable to create %s\n", pszName);
		exit(1);
    }
    layer = OGR_DS_CreateLayer( datasource, "layer1", sRef, wkbUnknown,
                                     papszOptions );
    /* MapInfo data sources are created with one empty layer.
       Fetch the layer handle */
//    layer = OGR_DS_GetLayer(datasource, 0);

    if (layer == NULL)
    {
        printf("Unable to create new layer in %s\n", pszName);
        exit(1);
    }

    /* Add a few fields to the layer defn */
    fieldDefn = OGR_Fld_Create( "code", OFTString );
    OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "number", OFTString );
    OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "count", OFTInteger );
    OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "opt1", OFTString );
	OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "opt2", OFTString );
	OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "opt3", OFTString );
	OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "opt4", OFTString );
	OGR_L_CreateField(layer, fieldDefn, 0);
    fieldDefn = OGR_Fld_Create( "opt5", OFTString );
    OGR_L_CreateField(layer, fieldDefn, 0);
    /* We'll need the layerDefn handle to create new features in this layer */
	layerDefn = OGR_L_GetLayerDefn( layer );
	
      return datasource;
}
/*------------------------------------------------------
*
*
OGRLayerH createOGRObject(const arc_P * arcH,const atr_P * atrH)
返り値 OGRLayerH　OGRのレイヤハンドル
引数　道路ファイルのパス、道路ファイルの属性
-------------------------------------------------------*/
void closeRoadDataresoutce(OGRDataSourceH datasource){
    OGR_DS_Destroy( datasource );
}
