/* pathops.c - pathname operations package from the net
 * todo:
 * modified(zilla)
 * 26sep
 * 18feb        logic change in getpath (Beware!)
 * sep/1        more lisp compatible
 * 1. make separator char independent of os
 * 2. return pointer to statically allocated string
 *
 * pathnam operations
 * returns an allocated string representing:
 * 
 * ext	- the file extension                    (getext)
 * root	- everything but the extension          (delext) 
 * tail	- the file and extension less the path  (getname) delpath
 * head	- the path less the file                (getpath) delname
 *
 */

# include <theusual.h>
# include <constants.h>

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#if Emac
 static char sepchar = ':';
 static char *sepchars = ":";
#endif
#if Eunix
 static char sepchar = '/';
 static char *sepchars = "/";
#endif

static char *myalloc Zproto((char *));

static char *myalloc(str)
  char *str;
{
  static char path[CMAXPATH];
  str_cpy(path,str);
  return(path);
}

/*forward*/ char *Zpathop Zproto((char *,Dchar));

char *
Zpathgetpath(pathname)
  char *pathname;
{
  return Zpathop(pathname,'h');
}

char *
Zpathgetext(pathname)
  char *pathname;
{
  return Zpathop(pathname,'e');
}


char *
Zpathgetname(pathname)
  char *pathname;
{
  return Zpathop(pathname,'t');
}

char *
Zpathdelext(pathname)
  char *pathname;
{
  return Zpathop(pathname,'r');
}

/* now returns a pointer to a static string! */
char *
Zpathop(cp, type)
  char *cp;
  register Dchar type;
{
    register char *wp, *xp;

    switch (type) {

    case 'h':
    case 't':
	if (!str_any(cp,sepchars)) {
          if (type == 'h')              /*&z added this feb*/
            return myalloc(""); /*((char *)0);*/
          else
            return (myalloc(cp));
        }
	wp = str_end(cp);
	while (*--wp != sepchar)
	    continue;
	if (type == 'h') {
	    xp = myalloc(cp);
	    xp[wp - cp] = 0;
	}
	else
	    xp = myalloc(wp + 1);
	return (xp);

    case 'e':
    case 'r':
	wp = str_end(cp);
	for (wp--; wp >= cp && *wp != sepchar; wp--)
	    if (*wp == '.') {
		if (type == 'e')
		    xp = myalloc(wp + 1);
		else {
		    xp = myalloc(cp);
		    xp[wp - cp] = 0;
		}
		return (xp);
	    }
	return (myalloc(type == 'e' ? "" : cp));
    }
    return ((char *)0);    /*default*/
}


#ifdef TESTIT
/*% cc % %*/
#include <stdio.h>

main() {
    char str[80];
    char c,*f;
    while(1) {
	printf("> ");
	scanf("%s %c",str,&c);
	printf(":%s: :%c:\n",str,c);
	f = file(str,c);
	printf("==>%s\n\n",f);
    }
}


getline(buf,fp)
  register char *buf;
  register FILE *fp;
{
    register char c;
    while((c = getc(fp)) != '\n' && (c != EOF))
    *buf++ = c;
    *buf = NULL;
}

#endif /*TESTIT*/
