#include	"tree.h"
#include	"treefunc.h"

extern int		option;
extern u_int	depth;

extern	unsigned long	allfiles;
extern	unsigned long	allsize;

/***** ファイルを得る *****/
Tree	*MakeTree( dir,tree, wild )
Dir 	*dir;
Tree	*tree;
char	*wild;
{
	int 		len;
	find_t		buf;
	char		*file;
	unsigned	attr;
	
	dir->matchfile = dir->files = dir->size = 0;
	
	file=(char *)xmalloc( FILENAME_MAX+1 );
	
	/** ディレクトリを先に検索 **/
	mk_FilePath( file, dir->path,dir->name );
	len=strlen(file);
	
	strcat( file,"*.*" );
	/* ↓残念ながらこのようには検索してくれない :-( */
	attr = (_A_SUBDIR );
	
	if( !_dos_findfirst( file, attr, &buf) )
	do
	{
#if 0
		if( (buf.name[0]=='.' )		/* 将来のため(?)チェック */
			&& ( buf.name[1]==NULLP
				|| (buf.name[1]=='.' && buf.name[2]==NULLP) ) );
#endif
		if( (buf.name[0]=='.' ) );
		else if( buf.attrib & _A_SUBDIR )
		{	tree=AddTree( tree, &buf );
			dir->matchfile++;
		}
	}while( !_dos_findnext(&buf) );
	
	if( dir->depth > depth )		goto MakeTreeEnd;
	
	
	/** 続いて通常ファイルの検索 **/
	file[len]=NULLP;
	strcat ( file, wild );
	
	attr = (_A_NORMAL |_A_SYSTEM |_A_RDONLY |_A_HIDDEN );
	
	if( !_dos_findfirst( file, attr, &buf) )
	do
	{	if( option & OPT_FILE )
		{	tree=AddTree( tree, &buf );
			dir->matchfile++;
		}
		dir->files++;
		allfiles++;
		dir->size += buf.size;
		allsize   += buf.size;
		
	}while( !_dos_findnext(&buf) );
	
	
MakeTreeEnd:
	free(file);
	return tree;
}

/*** データの格納 ***/
Tree	*AddTree( tree, buf )
Tree	*tree;
find_t	*buf;
{
	if( tree == NULLP )
	{
		tree      = (Tree *)fmalloc( sizeof( FileTree ) );
		tree->attr= buf->attrib;		/* ファイル名と属性のみ格納 */
		far_strcpy( tree->name,buf->name );
		
		tree->right = tree->left = NULLP;
	}
	else if( far_strcmp( tree->name , buf->name )
		 + ((tree->attr & _A_SUBDIR) - (buf->attrib & _A_SUBDIR))*0x100 <= 0 )
		tree->right = AddTree( tree->right, buf );
	else
		tree->left  = AddTree( tree->left , buf );
	
	return tree;
}

