/* a filter that removes multiple sequences of the form

	../h/../h/../h/ 

   The reason we have this is for using make depend to createw
   Makefiles: cc -M does not fold path cycles.

*/

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

#include "../h/cdefs.h"

char nextChar;

main()
{
	char linebuf1[256];
	char linebuf2[256];

	while (fgets (linebuf1, 256, stdin))
	 { dofold (linebuf2, linebuf1);
	   fputs (linebuf2, stdout);
	 }
}

dofold(out, in)
char *out, *in;
{
	char *cp2 = in;
	char *cp1 = out;
	int n1;
	int n2;

	while(1)
	 { while (isspace(*cp2))
	    { *cp1++ = *cp2++;
	    }
	   copyPath(cp1, &n1, cp2, &n2);
	   cp2 += n2;
	   cp1 += n1;
	   if (*cp2 == '\0')
	    { *cp1++ = *cp2++;
	      return;
	    }
	 }
}

copyPath(s1, n1, s2, n2)
char *s1;
int *n1;
char *s2;
int *n2;
{
	int count = 0;
	int swallow = 0;
	int newname = 0;
	char *parts[64];
	int length[64];
	int index = 0;
	int k;

	int absolute = 0;
	int tail = 0;

	if (!(isspace(*s2)) && *s2 != '\0')
	 { if (*s2 != '/')
	    { newname = 1;
	    }
	   else
	    { absolute = 1;
	    }
	 }
	while (!isspace(*s2) && *s2 != '\0')
	 { if (newname)
	    { parts[index++] = s2;
	      count = 0;
	      newname = 0;
	    }
	   if (*s2 == '/')
	    { if (index > 0)
	       { length[index-1] = count;
	       }
	      newname = 1;
	    }
	   else
	    { count++;
	    }
	   s2++;
	 }
	if (index > 0)
	 { length[index-1] = count;
	   if (newname)
	    { tail = 1;
	    }
	 }

	count = 0;
	if (absolute)
	 { *s1++ = '/';
	   count++;
	 }
	for (k=0; k<index; k++)
	 { if (k > 0)
	    { *s1++ = '/';
	      count++;
	    }
	   bcopy (parts[k], s1, length[k]);
	   s1 += length[k];
	   count += length[k];

	   while (1)
	    { if (k+2 < index &&
		 !match (parts[k], length[k], "..", 2) &&
		  match (parts[k+1], length[k+1], "..", 2) &&
		  match (parts[k+2], length[k+2], parts[k], length[k]) )
	       { k += 2;
		 swallow += 4 + length[k];
	       }
	      else
	       { break;
	       }
	    }
	 }
	if (tail)
	 { *s1++ = '/';
	   count++;
	 }
	*n1 = count;
	*n2 = count+swallow;
}

match (s1, n1, s2, n2)
char *s1, *s2;
int n1, n2;
{
	if (n1 == n2 && strncmp(s1,s2,n1) == 0)
	 { return(1);
	 }
	else
	 { return(0);
	 }
}

scanName (s)
register char *s;
{
	char *cp = s;
	
	while (*cp != '\0' && !(isspace(*cp)) && *cp != '/')
	 { cp++;
	 }
	return (cp - s);
}
