/* 
   Copyright 2001-2003 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
   02111-1307, USA.  

   You may contact the author at:

   mailto::camille@bluegrass.net

   or by snail mail at:

   David Lindauer
   850 Washburn Ave Apt 99
   Louisville, KY 40222
*/
#include <string.h>

char szProjectName[256] ;
void abspath(char *name)
{
  char projname[256],*p,*nname = name ;
   if (!strstr(name,"..\\"))
      return ;
   strcpy(projname,szProjectName) ;
   p = strrchr(projname,'\\') ;
   if (!p)
      return ;
   p-- ;
   while (!strncmp(name,"..\\",3)) {
      while (p> projname && *p-- != '\\') ;
      name += 3 ;
   }
   *++p = '\\' ;
   p++ ;
   strcpy(p,name) ;
   strcpy(nname,projname) ;
}
char *relpath(char *name)
{
   static char projname[256],localname[256] ;
   char *p = localname, *q = projname,*r,*s;
   if (toupper(name[0]) != toupper(szProjectName[0]))
      return name ;
   
   strcpy(localname,name) ;
   strcpy(projname,szProjectName) ;
   r= strrchr(localname,'\\') ;
   *r++ = 0 ; // r has the point to the file name
   s = strrchr(projname,'\\') ;
   if (*s)
      *s = 0 ;


   while (*p && *q && toupper(*p) == toupper(*q)) 
      p++,q++ ;
   if (!(*p | *q)) 
      return r ;
   else if (*(p-1) == '\\' && *(p-2) == ':')
      return name ;
   else {
      int count = *q != 0 ;
      while (p > localname && *p != '\\')
         p-- ;
      while (*q && (q = strchr(q+1,'\\')))
         count++ ;
      projname[0] = 0 ;
      while (count--)
         strcat(projname,"..\\") ;
      strcat(projname,p+1) ;
      strcat(projname,"\\") ;
      strcat(projname,r) ;
      return projname ;
   }
}
main(int argc, char **argv)
{
   char * p,buf[256] ;
   if (argc < 3)
      return ;
   strcpy(szProjectName,argv[1]) ;
   if (argc == 3) {
      p = relpath(argv[2]) ;
      printf("%s\n",p) ;
   } else
      p = argv[2] ;
   strcpy(buf,p) ;
   abspath(buf) ;
   printf("%s\n",buf) ;
}
