#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <errno.h>

static int expand_env_prefixed_string(char * path, char *tmp)
{
  int location_of_slash = strchr(path, '/') - path;
  char * translation;
  int translation_length;

  /* Failure mode #1 -- name of environment variable won't
     fit in the temporary char array. */

  if (location_of_slash > PATH_MAX)
    return 0;

  /* Make a copy of the environment variable name. */
  strncpy(tmp, path+1, location_of_slash-1);
  tmp[location_of_slash-1] = 0;
  
  translation = getenv(tmp);

  /* Failure mode #2 -- no translation. */
  if (translation == 0)
    return 0;

  translation_length = strlen(translation);

  /* Failure mode #3 -- translation + suffix too long. */
  if (translation_length +
      strlen(path) -
      location_of_slash > PATH_MAX)
    return 0; 

  strcpy(tmp, translation);
  strcpy(tmp+location_of_slash, path+location_of_slash);

  return 1;
}

main() {
  char tmp [PATH_MAX+1];
  char buf [PATH_MAX+1];

  while(1)
    {
      int rc;
      scanf("%s", buf);
     rc = expand_env_prefixed_string(buf, tmp);
      printf("subr returns %d, '%s'\n", rc, tmp);
    }
}
