
/* RCS Info: $Revision: 1.1 $ on $Date: 89/03/10 10:11:10 $
 *           $Source: /yew3/faustus/src/scrabble/RCS/util.c,v $
 * Copyright (c) 1988 Wayne A. Christopher, U. C. Berkeley CAD Group 
 *      faustus@cad.berkeley.edu, ucbvax!faustus
 * Permission is granted to modify and re-distribute this code in any manner
 * as long as this notice is preserved.  All standard disclaimers apply.
 *
 */

#include "util.h"
#include <pwd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>

extern char *malloc();
extern char *realloc();

char *
strsav(str)
       char *str;
{
       char *p;
       
       p = malloc(strlen(str) + 1);
       if (p)
               strcpy(p, str);
       return (p);
}

char *
util_datestring()
{
       register char *tzn;
       struct tm *tp;
       static char tbuf[40];
       char *ap;
       struct timeval tv;
       struct timezone tz;
       char *timezone(), *asctime();
       int i;
       struct tm *localtime();

       (void) gettimeofday(&tv, &tz);
       tp = localtime((time_t *) &tv.tv_sec);
       ap = asctime(tp);
       tzn = timezone(tz.tz_minuteswest, tp->tm_isdst);
       sprintf(tbuf, "%.20s", ap);
       if (tzn)
               strcat(tbuf, tzn);
       strcat(tbuf, ap + 19);
       i = strlen(tbuf);
       tbuf[i - 1] = '\0';
       return (tbuf);
}

int
util_seconds()
{
       struct rusage ruse;

       getrusage(RUSAGE_SELF, &ruse);
       return (ruse.ru_utime.tv_sec);
}

char *
util_tildexpand(s)
       char *s;
{
       struct passwd *pw;
       char *n, buf[64];
       int i;

       if (*s != '~') {
               n = malloc(strlen(s) + 1);
               strcpy(n, s);
               return (n);
       }

       for (s++, i = 0; *s != '/'; s++, i++)
               buf[i] = *s;
       buf[i] = '\0';
       if (!i)
               pw = getpwuid(getuid());
       else
               pw = getpwnam(buf);
       if (!pw)
               return (s);
       n = malloc(strlen(s) + strlen(pw->pw_dir) + 1);
       strcpy(n, pw->pw_dir);
       strcat(n, s);
       return (n);
}

char *
util_malloc(num)
       int num;
{
       char *s;

       s = malloc((unsigned) num);
       if (!s) {
               fprintf(stderr, "malloc: can't allocate %d bytes", num);
               exit(1);
       }
       bzero(s, num);
       return (s);
}

char *
util_realloc(ptr, num)
       char *ptr;
       int num;
{
       char *s;

       s = realloc(ptr, (unsigned) num);
       if (!s) {
               fprintf(stderr, "realloc: can't allocate %d bytes", num);
               exit(1);
       }
       return (s);
}

