/* 
  xgetcwd - implimentation of limitless getcwd 
  By Nick Rusnov <nick@grawk.net> 
  This is in the public domain.  
  Do what thou wilt and it shall be the whole of the law.
*/
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include "xgetcwd.h"


char 
*xgetcwd(void)
{
  char *mycwd = 0, *tmpcwd = 0;
#if PATH_MAX
  int mylen = PATH_MAX;
#else
#if MAXPATHLEN
  int mylen = MAXPATHLEN;
#else
  int mylen = 256; /* else arbitrary starting value */
#endif /* MAXPATHLEN */
#endif /* PATH_MAX */

  while (1)
    {
      tmpcwd = realloc (mycwd,mylen);
      if (tmpcwd == NULL)
	{
	  if (mycwd)
	    free (mycwd);

	  return 0;
	}
      mycwd = tmpcwd;
      if (!getcwd (mycwd,mylen) && (errno == ERANGE))
	{
	  mylen *= 2;
	}
      else
	{
	  tmpcwd = realloc (mycwd,strlen(mycwd)+1);
	  if (tmpcwd == NULL)
	    {
	      if (mycwd)
		free (mycwd);
	      return 0;
	    }
	  return tmpcwd;
	}
    }
}


