/*
 * scandir.c -- File list handling routines
 *
 * 88Jul17 orc	Created.
 */

#include "ctdl.h"
#include "dirlist.h"
#include "dateread.h"
#include "citlib.h"
#include "citadel.h"	/* Declarations specific to citadel.tos */

/*
 * * filedate()		convert a file date
 * scandir()		gets list of files.
 * freedir()		Free file list.
 */

/*
 * filedate() -- convert a file date
 */
static time_t
filedate(struct dirList *p)
{
    zero_struct(now);
    now.tm_mday = p->fd_date.mday;
    now.tm_mon  = p->fd_date.mon;
    now.tm_year = p->fd_date.year;
    return mktime(&now);
}

/*
 * scandir() - Get a list of files from the current directory
 */
int
scandir(char *mask, struct dirList **list)
{
    register count = 0;
    int size;
    struct dirList *p, *temp, *ptr;
    char tmask[80];
    char *file;

    p = *list = NULL;

    if (strchr(mask, ':') || strchr(mask, '\\'))
	return 0;

    strcpy(tmask, mask);

    /*
     * Incredibly ugly code follows.
     */
    for (file=strtok(tmask,"\t "); file; file=strtok(NULL,"\t ")) {
	for (ptr=getdirentry(file); ptr; ptr=getdirentry(NULL)) {
	    if (dPass != dEVERY && !dateok(filedate(ptr)))
		continue;
	    if (count%50 == 0) {
		size = (50+count) * sizeof ptr[0];
		temp = p ? realloc(p, size) : (struct dirList *)malloc(size);
		if (!temp) {
		    mprintf("Out of memory!\r");
		    break;
		}
		p = temp;
	    }
	    copy_struct(*ptr, p[count]);
	    ++count;
	}
    }
    *list = p;
    return count;
}

/*
 * freedir() - Frees the file list generated by scandir
 */
void
freedir(struct dirList *list, int count)
{
    if (count>0)
	free(list);
}
