#include <direct.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>
#include <dos.h>
#include <ext1/item.h>
#include "sftlib.h"

#define DOCFILEP   "DOCFILE"
#define INITSMP    "SYSTEM\\INITSMP.DAT"
#define EXBUFSIZ   (BUFSIZ*20)

char *copyf[]={		SFTLIBCFG, SFTLIBEXP ,
					"PALET.PAL",
					"SYSTEM\\HELP0.TXT",	"SYSTEM\\HELP1.TXT",
					"SYSTEM\\HELP2.TXT",	"SYSTEM\\HELP3.TXT",
					"SYSTEM\\HELP4.TXT",	"SYSTEM\\TOOLS3.TIF",
					DOCFILEP"\\SFTLIB.DOC"
				};

int dispalert(char *s1, char *s2 , char *b1 , char *b2);
int dispok(char *s1, char *s2 );
/*int get_inst_path( char *inst_path );*/ /* 組み込み先のディレクトリ設定 */
int get_inst_number( int *num );


int fcopy( char from[], char dist[])
{
	char path[_MAX_PATH];
	FILE *fr, *fw;
	int ret, ret2, len;
	char  filebuf[EXBUFSIZ];

	strcpy(path, dist);
	if( path[strlen(path)-1]!='\\' ) strcat( path, "\\");
	strcat( path, from);

	DB_work_put( path );

	ret=0;
	fr=fopen( from, "rb+");
	if( fr==NULL ) {ret=-1;goto RET1;}
	errno=EZERO;
	ret2=_access( path, 0 );
	if( ret2==0 ) 	{
		ret2=dispalert("ファイルを上書きします。いいですか", 
			path, "は  い","だ  め");
		if( ret2!=1 ) {ret=-2; goto RET1;}
	}
	_dos_setfileattr(path, _A_NORMAL );
	fw=fopen( path, "wb+"); 
	if( fw==NULL ) {ret=-3; goto RET1;}
	while( feof(fr)==0) {
		len=fread(filebuf, 1, EXBUFSIZ, fr);
		if( fwrite(filebuf, 1, len, fw)!=len ) {ret=-3;break;}
	}
	fclose(fw);
RET2:
	fclose(fr);
RET1:
	if( ret!=0 ) dispok("ごめんなさい。複写がうまくいきませんでした",path);
	return ret;
}



int set_textpath()
{
	int ret=0;
	return ret;
}



int mak_inst_path( char inst_path[] ) /* ディレクトリを作る           */
{
	int ret=0;
	unsigned attr;
	char path[_MAX_PATH];
	char path2[_MAX_PATH];
	
	strcpy(path, inst_path );
	
	if(*inst_path==0) {dispok("ディレクトリを設定してください",""); return -1;}

	ret=_dos_getfileattr( path, &attr);
	if( ret!=0 ) {
		ret=dispalert( "ディレクトリを作ってもいいですか",
			inst_path,"は  い","い い え" );
		if( ret==0 ) return -1;
		ret=_mkdir( path );
		if ( ret!=0 ) {
			dispok("ディレクトリが作れませんでした",path);
			return -1;
		}
	} else 	if( (attr & _A_SUBDIR)==0 ) {
		 dispok("ディレクトリじゃありません",path);
		return -2;
	}
	strcpy( path2, path);
	if( path2[strlen(path2)-1]!='\\' ) strcat( path2, "\\");
	strcat( path2, "system");
	ret=_mkdir( path2 );
	if ( ret!=0  && (errno!=EACCES) ) {
		dispok("ディレクトリが作れませんでした",path2);
		return -3;
	}
	strcpy( path2, path);
	if( path2[strlen(path2)-1]!='\\' ) strcat( path2, "\\");
	strcat( path2, DOCFILEP );
	ret=_mkdir( path2 );
	if ( ret!=0  && (errno!=EACCES) ) {
		dispok("ディレクトリが作れませんでした",path2);
		return -4;
	}
	return 0;
}

int cpy_inst_path( char inst_path[] ) /* ファイルの複写               */
{
	int ret=0;
	int i;
	char *errfile="";

	DB_work_open("ファイルの複写をしています","");
	for( i=0; i< sizeof(copyf)/sizeof(copyf[0]); i++ ){
		errfile=copyf[i];
		ret=fcopy( errfile , inst_path); 
		if( ret!=0 ) { ret=-1; break; }
	}
	DB_work_close( );
	return ret;
}

int mak_sftlibdat( char inst_path[] ) /* データファイルを作る         */
{
	int ret=0, ret2;
	int i, num ;
	char path[_MAX_PATH];
	char strnum[80];
	FILE *fp;
	soft data;

	strcpy( path, inst_path);
	if( path[strlen(path)-1]!='\\' ) strcat( path, "\\");
	strcat( path, SFTLIBDAT );
	get_inst_number( &num );

/*	sprintf( strnum, "%d 件のデータファイルを作ります｡", num);
**	ret2=dispalert( strnum, path, "い い よ","や め る");
**	if( ret2==0 ) { return -3; }
*/

	fp=fopen(path, "wb");
	if(fp==NULL) { return -1; }

	DB_work_open("データファイルを作っています",path);
	getsmplredata( &data, 1 );
	ret2=fwrite( &data, sizeof(data), 1, fp );
	if( ret2!=1 ) { ret=-2; goto RET1;	}

	DB_work_put( "1" );
    for( i=2; i<=num; i++)
    {
		sprintf(strnum, "%d",i);
		DB_work_put( strnum );
		getcldata( &data );
		ret2=fwrite( &data, sizeof(data), 1, fp );
		if( ret2!=1 ) { ret=-2; break;	}
    }
	fclose(fp);	

RET1:
	DB_work_close( );
	return ret;
}


int mak_indexdata( char inst_path[] ) /* インデックスファイルを作る   */
{
	int ret=0, ret2;
	char pathin[_MAX_PATH], pathout[_MAX_PATH];
	FILE *fpr, *fpw;
	soft data;
	index ind; int n;
	
	strcpy( pathout, inst_path);
	if( pathout[strlen(pathout)-1]!='\\' ) strcat( pathout, "\\");
	strcat( pathout, SFTLIBIND );
	DB_work_open("インデックスファイルを作っています",pathout);
	strcpy( pathin, inst_path);
	if( pathin[strlen(pathin)-1]!='\\' ) strcat( pathin, "\\");
	strcat( pathin, SFTLIBDAT );

	fpr=fopen( pathin ,"rb");
	if( fpr==NULL) { ret=-1; goto RET0; }
	fpw=fopen( pathout, "wb");
	if( fpw==NULL) { ret=-2; goto RET1;}

	n=0;
	while( fread( &data, sizeof(data), 1, fpr )==1 ) 
	{
		char strnum[16];
		sprintf(strnum, "%d", n+1);
		DB_work_put( strnum );
		data2ind( &data, &ind );
		ind.softno=n;n++;
		ret2=fwrite( &ind, sizeof(ind),1,fpw);
		if( ret2<0) {ret=-3;break;}
	}
	fclose(fpw);

RET1:
	fclose(fpr);
RET0:	
	DB_work_close( );
	return ret;
}

int mak_sftlibsft( char inst_path[] ) /* 情報ファイルを作る           */
{
	int ret=0;
	char path[_MAX_PATH];
	FILE *fp;
	
	strcpy( path, inst_path);
	if( path[strlen(path)-1]!='\\' ) strcat( path, "\\");
	strcat( path, SFTLIBSFT );
	DB_work_open("情報ファイルを作っています",path);
	
	fp=fopen( path ,"wt");
	if( fp==NULL) { ret=-1; goto RET0; }

	fprintf(fp, "DB_sftcfgp  = \"%s\" ; # 環境ファイル\n", SFTLIBCFG);
	fprintf(fp, "DB_sftcfgm  = 1 ;      # 0:環境ファイルを保存しない 1:する 2:その他\n");
	fprintf(fp, "DB_docdir   = \"%s\\\" ;\n", DOCFILEP );
	fprintf(fp, "DB_indexp   = \"%s\" ;\n",   SFTLIBIND );
	fprintf(fp, "DB_sftlibp  = \"%s\" ;\n",   SFTLIBDAT );
	fprintf(fp, "DB_tifflp   = \"%s\" ;\n", copyf[8]);
	fprintf(fp, "DB_help0p   = \"%s\" ;\n", copyf[3]);
	fprintf(fp, "DB_help1p   = \"%s\" ;\n", copyf[4]);
	fprintf(fp, "DB_help2p   = \"%s\" ;\n", copyf[5]);
	fprintf(fp, "DB_help3p   = \"%s\" ;\n", copyf[6]);
	fprintf(fp, "DB_help4p   = \"%s\" ;\n", copyf[7]);
	fprintf(fp, "\nbunrui_mes[23]={ #24バイト以内 \n"
        "\"シューティングゲーム    \",  \"アクションゲーム      \",\n"
        "\"アドベンチャーゲーム    \",  \"ロールプレイングゲーム\",\n"
        "\"シュミレーションゲーム  \",  \"思考ゲーム            \",\n"
        "\"エンターテイメントソフト\",  \"ホームユースソフト    \",\n"
        "\"教育                    \",  \"趣味                  \",\n"
        "\"教養                    \",  \"データベースソフト    \",\n"
        "\"開発ソフト              \",  \"ワープロソフト        \",\n"
        "\"ＯＳソフト              \",  \"ミュージックソフト    \",\n"
        "\"グラフィックソフト      \",  \"通信ソフト            \",\n"
        "\"電子出版                \",  \"分析ソフト            \",\n"
        "\"ＣＤグラフィックスソフト\",  \"業務用ソフト          \",\n"
        "\"分類不能ソフト          \" };                           \n");
	fprintf(fp, "\nmedia_mes[5]={ #8バイト以内  \n"
		"   \"CD\",  \"CD+FD\",   \n"
		"   \"FD\",  \"CD 8cm\",  \n"
		"   \"IC\"  };            \n");
	fprintf( fp, "\ndate_mes[6]={ #12バイト以内 \n"
		"   \"発 売 日    \", \"購 入 日    \",\n"
		"   \"登録する日日\", \"解除する日日\",\n"
		"   \"設定日      \", \"記念日      \" \n"
		"   }; \n");

	if( fprintf(fp, "\n#END\n")<0 ) ret=-2; 
RET1:
	fclose(fp);
RET0:	
	DB_work_close( );
	return ret;
}

int sftlibmake( char inst_path[_MAX_PATH+1])
{
	int ret;
	
	if ( *inst_path==0 ) ret=-1;

	ret=mak_inst_path( inst_path ); /* ディレクトリを作る           */
	if( ret!=0 )  return -2; 

	ret=cpy_inst_path( inst_path ); /* ファイルの複写               */
	if( ret!=0 )  return -3;

	ret=mak_sftlibsft( inst_path ); /* 情報ファイルを作る           */
	if( ret!=0 )  return -6;

	ret=mak_sftlibdat( inst_path ); /* データファイルを作る         */
	if( ret!=0 )  return -4;

	ret=mak_indexdata( inst_path ); /* インデックスファイルを作る   */
	if( ret!=0 )  return -5;

	return 0;
}


int about_func(void)
{
	int loop;
	extern int TL_checkMemory( int );
	char *s1,*s2,*b1,*b2;
	char *m[]={
			"ソフトウェア検索組み込み V1.0 L11",
			"All rights Reserved, Copyright (C) White of Cat 1994 ",
			"残りメモリ",
			"了解",
			"Copyright",
			"xxxxxxxxxxK bytes フリー   ",
		};

			sprintf( m[5],"%10dK bytes フリー",TL_checkMemory(0)*4);
			s1=m[0];s2=m[1];b1=m[2];b2=m[3];
	loop=1;
	while(loop!=0) {
		loop=dispalert( s1, s2, b1, b2 );
		if( loop==1 ) {
			if( s2==m[1] )	{ s2=m[5]; b1=m[4];}
				else 		{ s2=m[1]; b1=m[2];}
		}
	}

	return 0;
}

int getsmplredata( soft *x, int n)
{
	FILE *fp;
	int i,readnum;
	fp=fopen( INITSMP, "rb");
	if( fp==NULL ) return 0;
	readnum=fread( x, sizeof(soft), n, fp);
	fclose(fp);
	for(i=0; i< readnum; i++){
		time(&(x[i].d_date1));  /* データ作成日    */
		x[i].d_date2=0x0;       /* データ更新日    */
	}
	return readnum;
}


int itemmit( char *item_path)
{
	int ret;
	AMI_PATH_t ps;
	char ipath[_MAX_PATH];
	char xpath[_MAX_PATH];
	char opath[_MAX_PATH];
	ITMFRM frm={300+0,120+0,300+24,120+24};
	char *p;

	AMI_pathsplit( &ps, item_path);
	strcpy( ipath, ps.drive);
	strcat( ipath, "\\tmenu.itm");

	ret=_access( ipath, 0 );
	if( ret!=0 ) ITM_CreateItemFile( ipath );
	ret=_access( ipath, 3 );
	if( ret!=0 ) {
		if( dispalert("書き込みできません。属性を変更します｡",ipath,"いいよ","だめ") )
				_dos_setfileattr( ipath, _A_NORMAL );
	}
	
	strcpy( xpath, ps.dir);
	strcat( xpath, ps.fname);
	strcat( xpath, ps.ext);
	if( xpath[strlen(xpath)-1]!='\\' ) strcat( xpath, "\\");
	strcat( xpath, SFTLIBEXP );
	p=xpath;while( *p!='\0' ) {*p=toupper(*p);p++;}

	strcpy( opath, ps.dir);
	strcat( opath, ps.fname);
	strcat( opath, ps.ext);
	if( opath[strlen(opath)-1]!='\\' ) strcat( opath, "\\");
	strcat( opath, SFTLIBSFT );
	p=opath;while( *p!='\0' ) {*p=toupper(*p);p++;}

	ret=ITM_AddAplItem( ipath, 0, 1024, "SFTLIB", xpath, opath, 2, &frm);
	
	return ret;
}

