/*** fwild() and fnext()
 * Wild-card file opens.
 *
 * By Ray Van Tassle	Feb 26, 1986
*/
#include <stdio.h>
#include <descrip.h>        
#include <RMSDEF.H>


static char buf[FILSPC_L] = "";
static char nam_buf[FILSPC_L] = "";
static struct dsc$descriptor_d nam = {sizeof(buf), DSC$K_DTYPE_T,
DSC$K_CLASS_S, &buf};	/* Next name */
static $DESCRIPTOR(wc, "*.com");/* Wildcarded name. */
static int *context = 0;	/* Context (saved) */
static FILE *fp = 0;		/* The fp to use. */
static char *w_mode;		/* Mode to open.  */

FILE *fnext();

FILE *fwild(fn, mode)
char *fn;		/* File name (with wildcards) to find. */
char *mode;		/* Open mode. */
{
   int i;

   if (context)
      lib$find_file_end(&context);	/* Clean-up from prev series. */
   if (fp)       			/* Better close the prev file. */
      fclose(fp);
   fp = NULL;                 
   strcpy(nam_buf, fn);
   wc.dsc$w_length = strlen(fn);	/* Save (wildcarded) filename. */
   wc.dsc$a_pointer = nam_buf;
   w_mode = mode;			/* Save the open mode */
   i = lib$find_file(&wc, &nam, &context);
   lib$find_file_end(&context);
   if (i != RMS$_NORMAL)
      return(NULL);		       
   return(1);
}


/*********************************************/
/******** Get the next file. Close the current
 * one first.  Open with same modes, etc. */
FILE *fnext()		/* Don't need any parms!!!! */
{
   int i;
   register char *s;

   if (fp)       			/* Better close the prev file. */
      fclose(fp);
   fp = NULL;
   i = lib$find_file(&wc, &nam, &context);	/* Find next one. */
   /*
   printf("fnext--0x%x\n", i);
   printf(" 0x%x %d %d >%s< \n", nam.dsc$w_length,
	nam.dsc$b_dtype, nam.dsc$b_class, nam.dsc$a_pointer);
   */  
   if (i != RMS$_NORMAL)
      return(NULL);			/* No good. */
                                          
   for (s = nam.dsc$a_pointer; *s != ' '; ++s) /* Null trail it */
      ;
   *s = NULL;

   fp = fopen(nam.dsc$a_pointer, w_mode);
   return(fp);
};

#ifdef TESTING
/*********************** to test it *****************/
main(argc, argv)
int argc;
char **argv;
{
   FILE *fp;
   static char b[256];
   static char fn[256];

   if (argc <= 1) {
      puts("No parms");
      exit();
   }

   for (fp = fwild(argv[1], "r"); fp = fnext(fp); ) {
      fgetname(fp, fn);
      printf("Filename >%s<\n", fn);
      b[0] = NULL;
 fgets(b, 78, fp);
 puts(b);
   }
}
#endif
