/*************************************
   List 関連の処理をするmodule
**************************************/
#include<string.h>
#include<direct.h>
#include<dos.h>
#include<direct.h>
#include<stdlib.h>
#include<stddef.h>
#include<stdio.h>
#include"list.h"
#include"chain.h"

#define	TRUE	(-1)
#define FALSE	0

extern	LIST	head;

/*******************************
 File のlistを作ってその数を返す
 *******************************/
int MakeList(PARA inf)
{
	unsigned int dmy=0,stat=0,count=0;
	char ter[13];
	struct _find_t	fb;
	LIST	*prev,*t;
	
	head.next=NULL;
	_dos_setdrive(inf.drive,&dmy);
	if(inf.path[0] != '\0')
		if (_chdir(inf.path)==ERR){
			printf("ディレクトリの指定が違います.");
			exit(1);
		}
	
	if(inf.file[0]=='\0'){
		strcpy(ter,"*.doc");
	}else{
		strcpy(ter,inf.file);
	}
	
	prev=&head;
	stat = _dos_findfirst(ter,ALL_ATTRIBUTE,&fb);
	while(stat==0){
		count++;
		t=(LIST *)malloc(sizeof(LIST));
		if(t==NULL){
			printf("Memory allocation error. \n");
			exit(1);
		}
		prev->next=t;
		t->next=NULL;
		t->size=fb.size; 
		t->wr_time=fb.wr_time;
		t->wr_date=fb.wr_date;
		t->line=0;
		t->flag=FALSE;
		strcpy(t->file,fb.name);
		prev=t;
		stat=_dos_findnext(&fb);
	}
	return(count);
}

/*********************************************
purpose:
  ファイルサイズの合計がsizeに近くなるように
  flagをたてる｡
return:
  フラグを立てたファイル数
  
 n --> 目次のファイル数 
**********************************************/
int SetFlag(int size)
{
	int sum=HEADERSIZE,count=0;
	LIST	*p;
	
	
	for(p=head.next,count=0;p!=NULL;p=p->next){
		if ((sum + (p->size) + HEADERSIZE+80+INDEXLINE*80) < size ){
			p -> flag = TRUE;
			sum=sum+p->size+HEADERSIZE+INDEXLINE*80+80;
			count++;
		}
	}
	return(count);
}

/***************************************
purpose:
	既に連結が終わったファイルをリスト
	から削除する関数
return:
	削除したファイル数
****************************************/
int ClearFlag(void)
{
	LIST *p,*prev,*del;
	int count=0;
	
	p=head.next;
	prev=&head;
	while(p!=NULL){
		if( p->flag == TRUE){
			prev->next=p->next;
			del=p;
			p=p->next;
			count++;
			free(del->bf);
			free(del);
		}else{
			prev=prev->next;
			p=p->next;
		}
	}
	return(count);
}
