/* directory functions-- mainly unix stuff, needs work for VMS */
#ifndef VMS
#include <sys/types.h>
#include <sys/dir.h>
#endif

#include "buffer.h"
#include "window.h"
#include "file.h"

void get_cdir(char *dir)
{
    int i;
#ifndef VMS
    getwd(dir);
    i = strlen(dir); dir[i] = '/'; dir[i] = '\0';
#else
    getcwd(dir,80);
#endif
}


#ifndef VMS
/* This is a cheap routine-- should be replaced!!!! */
bubble_sort()
{
    unsigned char *this, *next, *save;
    char tmp[80], *t;
    int change;
    
    change = 1;
    while(change)
      {
          next = this = BEG;
          while((next < EOB) && (*next++ != 0));
          if (next == EOB) return;
          change = 0;
          while(next < EOB)
            {
                if (strcmp((char *)this,(char *) next) > 0)
                  {
                      change = 1;
                      strcpy(tmp,(char *) this);
                      t = tmp;
                      while(*next != 0) *this++ = *next++;
                      *this++ = 0;
                      save = this;
                      /* now next points at a null */
                      next++;
                      while(*t != 0) *this++ = *t++;
                      *this = 0;
                      this = save;
                  }
                else
                  {
                      this = next;
                      while(next < EOB && *next++ != 0);
                  }
            }
      }
}

void get_dir(char *dir)
{
    DIR *dirp;
    struct direct *dp;
    char *p;
    unsigned char *pos;
    int dsize, len, size = 4096, i;
    
    if (*dir == 0)
      dirp = opendir(".");
    else
      dirp = opendir(dir);

    if (dirp == NULL)
      {
          message("Unable to open directory.",1);
          return;
      }
    
          
    BEG = (unsigned char *) malloc(size);
    strcpy(BUF->file,dir);
    pos = BEG;
    dsize = size;
    EOB = BEG + size;
    
    for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp))
      {
          p = dp->d_name;
          len = dp->d_namlen;
          if (pos + len >= EOB - 1)
            {
                size += dsize;
                BEG = (unsigned char *) realloc(BEG,size);
                
                EOB = BEG + size;
                pos = EOB - dsize;
            }
          strcpy(pos,p);
          pos += len;
          /*           *pos++ = '\n'; */
          *pos++ = '\0';
      }

    BUF->end = EOB = pos;
    BUF->beg = BEG;
    closedir(dirp);
    bubble_sort();
    i = 0;
    for (pos = BEG; pos < EOB; pos++)
      if (*pos == '\0')
        {
            if (i = !i, i) *pos = '\t'; else *pos = '\n';
        }
    
}
#endif


