
/*
 * mscan - Scan directories and return a sorted list of file names,
 *	    one at a time.
 *
 *  This code originally taken from sysdep.c:
 *
 *  (C) Copyright 1987 by John Gilmore
 *  Copying and use of this program are controlled by the terms of the Free
 *  Software Foundation's GNU Emacs General Public License.
 *
 * Amiga Changes Copyright 1988 by William Loftus. All rights reserved.
 *
 * Rewrite for use with manx (or lattice), and Anews.
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXFILES    512

static char names[MAXFILES*10];
static char *pointers[MAXFILES];

int file_pointer;  /* External so that it can be read/written */

static valid = 0;

char *
read_directory(dir)
char *dir;
{
    int count, mycmp();
    char *scdir();
    char path[128];

    file_pointer = 0;
    if (dir) {
	getcwd(path,127);
	chdir(dir);
    }

    count = getfnl("#?", names, sizeof(names), 0);

    if (dir) chdir(path);

    if (count > 0) {
      if (strbpl(pointers, MAXFILES, names) != count) {
	 printf("Too many files\n");
	 return (char *)NULL;
      }
    } else {
      return (char *)NULL;
    }

    qsort((char *)pointers, count, sizeof(char *), mycmp);

    valid = 1;	/* We have some files, and more important, some space has
		   been malloc'd */

    return (char *)1;
}

char *
get_next_file()
{
 char *p;

  if ( (p=pointers[file_pointer++]) == NULL )
	file_pointer=0;
  return p;
}

free_directory()
{
   int i;
   if (valid) {
	for(i=0;pointers[i] != NULL;i++)
		free(pointers[i]);

	valid = 0;
    }
	return(0);
}

mycmp(a,b)
char **a,**b;
{
	return (atol(*a)-atol(*b));
}


