/*  c_next_file_unix.c - return file names in order  */

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

#define     NAME_LENGTH     256
#define     MAX_FILES     10000

static int  wild, count, out, max_len;
static char *fp[MAX_FILES];

int c_next_file_init(char *name)  /*  initialization routine  */
{
    char    file[NAME_LENGTH];
    int     shell$to_vms();
    void    vms_name();

    /*  clean up old pointers and initialize counters  */

    while (count >= 0) {
        free(fp[count]);
        fp[count--] = (char *) NULL;
    }

    count = out = max_len = 0;

    /*  check for wild card and process names  */

    if (strpbrk(name,"*?") == NULL) {
        wild = 0;
        if (access(name,0) != EOF) count = shell$to_vms(name,vms_name,0);
        else perror(name);
    }
    else {
        wild = 1;
        strncpy(file,name,NAME_LENGTH);
        strncat(file,";",NAME_LENGTH);
        count = shell$to_vms(file,vms_name,1);
    }
    return (count);
}


void vms_name(char *file, int type)     /*  process the vms file name  */
{
    int     i, shell$from_vms();
    void    unix_name();

    /*  if wildcard, cut off the version number  */

    if (wild && type != 2) {
        for (i=strlen(file); file[i] != '.'; i--);
        file[i] = '\0';
    }

    /*  convert back to unix  */

    shell$from_vms(file,unix_name,1);
}


void unix_name(char *name)      /*  save the file name  */
{
    int     len;
    char    *cp, *tp;

    /*  do we have room?  */

    if (count >= MAX_FILES) {
        fprintf(stderr,"too many files\n");
        exit(1);
    }

    /*  add ".DIR" to directories!  */

    cp = name;
    while ( (tp=strstr(cp,"/")) ) cp = ++tp;
    if (strstr(cp,".") == NULL) strcat(cp,".DIR");

    /*  convert to lower case  */

    for (cp=name; *cp != '\0'; cp++) *cp = tolower(*cp);

    /*  calculate length and check maximum length  */

    len = cp - name;
    max_len = (len > max_len) ? len : max_len;

    /*  move to other storage  */

    if ((fp[count] = malloc(len+1)) == NULL) {
        fprintf(stderr,"memory problem\n");
        exit(1);
    }
    else strcpy(fp[count++],name);
}


char *c_next_file()   /*  return file names in order  */
{
    /*  return the next file name  */

    if (out <= count) return(fp[out++]);
    else return((char *) NULL);
}    


int c_next_file_maxlen()        /*  return the maximum file name length  */
{
    return (max_len);
}


char **c_next_file_list()       /*  return pointer to file pointers  */
{
    return (fp);
}

/* eof */
