/* tag: Scott Parish Sun Feb  10 13:01:05 2002 (misc.c)
 */
/* misc.c -
 *
 ****************************************************************
 * Copyright (C) 2002 Scott Parish
 * 
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */

#include <string.h>
#include "hackerlab/mem/mem.h"
#include "hackerlab/char/str.h"
#include "ftp-utils/clients/misc.h"


/*
 * dirfold: take a directory and "fold" out all the '.' and '..'s
 *
 * example: dirfold(limits, "/tmp/.././home/srp/images/..")
 * should return "/home/srp"
 *
 * Note: this function modifies the string passed in, it does not return a
 * new string
 */
char *
dirfold (alloc_limits limits, char *dir)
{
  char *buf, *this, *next;
  int dir_i = 0;

  this = next = buf = str_save (limits, dir);
  while ((this = strsep (&next, "/")) != NULL)
    {
      if (str_length (this) == 0 || (str_length (this) == 1 && this[0] == '.'))
	continue;
      else if (str_length (this) == 2 && *this == '.' && this[1] == '.')
	{
	  if (dir_i > 0)
	    dir_i = strrchr (dir, '/') - dir;
	  dir[dir_i] = 0;
	}
      else
	{
	  dir[dir_i++] = '/';
	  strcpy (dir + dir_i, this);
	  dir_i += str_length (this);
	}
    }
  lim_free (limits, buf);

  if (!str_length (dir))
      str_cpy (dir, "/");

  return dir;
}
