/*
	getfile.c	DOS filename list subroutine
*/

/*
	Copyright 1988, Jeffrey J. Nonken
	Released to the Public Domain ... *no* rights reserved.
*/
/*
Updates:
    20 Aug 1988, M. J. Housky
	Modified to used DIRFN.C routines instead of assembler subroutine.
	Also added comments for the curious.
*/

#include <stdio.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>

#include "dirfn.h"

/*
	get_files:	Build array of disk filenames matching a given
			filespec and attributes.

	Returns number of matched files in list:
	    0 if none matched, -1 if out of memory.
*/

int get_files( char*, int, FILE_TYPE** );

int get_files(name,attrib,filez)
    char	*name;		/* filespec to match */
    int		attrib;		/* attributes to match */
    FILE_TYPE	**filez;	/* where to store pointer to malloced */
    				/* result array. */

{
    register int i;
    register int j;
    FILE_TYPE	*files;		/* file list pointer */
    FIND_DTA	fdta,		/* DTA for dir_sscan/dir_cscan */
		*pdta;		/* pointer returned by sscan/cscan */

    files = (FILE_TYPE *)malloc(sizeof(FILE_TYPE) * 100);
    if (files == NULL)
	return(-1);
    i = 0;
    j = 100;

    pdta = dir_sscan( &fdta, name, attrib );
    if ( pdta != NULL )
    {
	memcpy((char *)&files[i++],fdta.name,sizeof(FILE_TYPE));
	do
	{
	    pdta = dir_cscan( &fdta );
	    if ( pdta != NULL )
	    {
		memcpy((char *)&files[i++],fdta.name,sizeof(FILE_TYPE));
		if (i >= j)
		{
		    j += 100;
		    files = (FILE_TYPE *)realloc((char *)files,
				j * sizeof(FILE_TYPE));
		    if (files == NULL)
			return(-1);
		}
	    }
	} while (pdta != NULL);
    }
    files = (FILE_TYPE *)realloc((char *)files,i * sizeof(FILE_TYPE));
    *filez = files;
    return i;
}
