/*

  sshgetcwd.c

  Author:
        Sami Lehtinen <sjl@ssh.com>

  Copyright (C) 1999-2000 SSH Communications Security Corp, Helsinki, Finland
  All rights reserved.

  Get current working directory, and allocate the needed space for it.
*/

#include "sshincludes.h"
#ifdef WIN32
#include <direct.h> /* header for getcwd() */
#endif /* WIN32 */

#define SSH_DEBUG_MODULE "SshGetCwd"

#define SSH_GETCWD_INITIAL_BUFFER_SIZE 512

char *ssh_getcwd(void)
{
  char *cwd, *buf;
  int allocated = SSH_GETCWD_INITIAL_BUFFER_SIZE;

  buf = ssh_xmalloc(allocated);
  
  while (1)
    {
      if (!(cwd = getcwd(buf, allocated)))
        {
          if (errno == ERANGE)
            {
              /* Buffer wasn't large enough. */
              allocated *= 2;
              SSH_DEBUG(4, ("Allocating more space (now %d bytes).",    \
                            allocated));
              buf = ssh_xrealloc(buf, allocated);
              continue;
            }
          else
            {
              /* Some other error. */
              ssh_xfree(buf);
              return NULL;
            }
        }
      else
        {
          return cwd;
        }
    }
}
