/*=-=-=-=-=-=-=-=-=-=-  RCCL/RCI Notice of Copyright  -=-=-=-=-=-=-=-=-=-=-=*
 *									    *
 *	Copyright (C) 1987 by Mike Parker. Permission to use, distribute    *
 *	and copy is granted for non-commercial and research purposes only,  *
 *	providing the authors are acknowledged and this copyright notice is *
 *	displayed. The authors provide this software in hope that it will   *
 *	useful, but do not assume responsibility for its use.		    *
 *									    *
 *	This software was developed using the facilities of the McGill 	    *
 *	University Research Center for Intelligent Machines, Montreal,	    *
 *	Canada, for a project undertaken and supported by the RCA Advanced  *
 *	Technology Laboratories, Moorestown, New Jersey.		    *
 *									    *
 *=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/

#include <stdio.h>
#include <ctype.h>
#include <pwd.h>


char *cfn = "foo";

char *fileNameExpand(name)
char *name;
{
	/* expands a file name. Assumes that the file name contains no
	   white space. Expands leading ~'s, plus environment
	   variables
	 */
 	
	char buf[1024];
	register char *cp, *np;
	char *base;
	char *tildedir;
	char *tildetemp;
	struct passwd *pwd;

	cp = name;
	np = buf;
	*np = '\0';
	
	/* If the first character is ~, do home directory expansion */

	if (*cp == '~')
	 { int tdlen;
	   base = cp;
	   for (cp = base+1; *cp && (*cp != '/'); cp++)
	      ;
	   if (cp == base+1)
	    { if ((tildedir = getenv("HOME")) == NULL)
	       { fatalMsg (-1, 
"Config file %s: bare ~ used without HOME environment variable\n", cfn);
	       }
	    }
	   else
	    { char savec;
	      savec = *cp;
	      *cp = '\0';
	      if ((pwd = getpwnam(base+1)) == NULL)
	       { fatalMsg (-1,
"Config file %s: no such user '%s'\n", cfn, base+1);
	       }
	      tildedir = pwd->pw_dir;
	      *cp = savec;
	    }
	   strcpy (np, tildedir);
	   np += strlen (np);
	 }

	/* Now proceed with regular expansion */

	while (*cp)
	 { if (*cp == '\\')
	    { cp++;
	      if (*cp)
	       { *np++ = *cp++;
	       }
	    }
	   else if (*cp == '$')
	    { char savec;
	      char *env;

	      cp++;
	      base = cp;
	      for (; *cp && (isalnum(*cp) || *cp == '_'); cp++)
		 ;
	      savec = *cp;
	      *cp = '\0';
	      if (cp == base)
	       { fatalMsg (-1,
"Conf file %s: NULL environment variable in file name\n", cfn);
	       }
	      if ((env = getenv(base)) == NULL)
	       { fatalMsg (-1,
"Conf file %s: environment variable %s not defined\n", cfn, base);
	       }
	      strcpy (np, env);
	      np += strlen(np);
	      *cp = savec;
	    }
	   else
	    { *np++ = *cp++;
	    }
	 }
	*np = '\0';
	return ((char*)strcpy (malloc(strlen(buf)+1), buf));
}

main()
{
	char buf[256];

	while(1)
	 { scanf ("%s", buf);
	   printf ("%s\n", fileNameExpand (buf));
	 }
}
