
#include <errno.h>
#include <string.h>

#include "rc.h"

void b_pwd2( char ** av )
{
	char * cwd = NULL;
	size_t size = 1024;	/* A large initial guess. */

	/* The start of the cwd. Used to avoid a string move when we turn
	** `home' at the start of a path into ~. */
	char * start;

	/* A pointer into the cwd. */
	char * p;

	/* The last three path elements. */
	char * p1 = NULL;
	char * p2 = NULL;
	char * p3 = NULL;

	List * s;	/* The value of home. (Not your mum.) */

	/* Work out where we are... */
	while ( 1 ) {
		cwd = (char *)malloc (size);
		if ( cwd == NULL ) {
			/* Couldn't get any memory. */
			uerror ("cd");
			set (FALSE);
			return;
		}

		if ( getcwd(cwd,size-1) != NULL ) break;
		else {
			if ( errno != ERANGE ) {
				/* Couldn't get current working directory. */
				uerror ("cd");
				set (FALSE);
				return;
			} else {
				free (cwd);
				size *= 2;
			}
		}
	}

	/* Check for $HOME as a prefix... */
	s = varlookup ("home");
	p = start = cwd;
	if ( s != NULL && !strncmp(p,s->w,strlen(s->w)) ) {
		p += strlen (s->w) - 1;
		start += strlen (s->w) - 1;
		*p = '~';
	}

	/* Cut the cwd up... */
	p3 = p2 = p1 = p;
	while ( *p ) {
		if ( *p == '/' ) {
			p3 = p2;
			p2 = p1;
			p1 = p + 1;
		}

		p++;
	}

	/* Print the cwd... */
	if ( strlen (p3)+3 >= strlen (start) ) {
		(void)fprint ( STDOUT_FILENO, "%s\n", start );
	} else {
		(void)fprint ( STDOUT_FILENO, "...%s\n", p3 );
	}
	free (cwd);

	set (TRUE);
}
