#include "basic.h"
#include "errlog.h"
#include "pstr.h"
#include <malloc.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <ctype.h>
#include <stdlib.h>

pstr
pstr_create(const char *s1, ...)
{
  va_list ap;                   /* Arglist-Iterator                          */
  const char *cp;
  size_t len;                   /* Gesamtlaenge                              */
  char *res;                    /* res. String                               */

  /* Gesamtlaenge bestimmen                                                  */
  len = 1;
  va_start(ap, s1);
  for (cp = s1; cp != NULL; cp = va_arg(ap, const char *))
    len += strlen(cp);
  va_end(ap);

  /* entsprechend Speicherplatz anfordern                                    */
  res = cmalloc(len);
  if (res == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  /* Strings in neuen Speicherplatz kopieren                                 */
  res[0] = '\0';
  va_start(ap, s1);
  for (cp = s1; cp != NULL; cp = va_arg(ap, const char *))
    strcat(res, cp);
  va_end(ap);

  return res;
}

void
pstr_delete(pstr s)
{
  if (s)
    free((void *)s);
}

void
strlower(char *s)
{
  AssertStr(s);
  while (*s)
    {
      *s = tolower(*s);
      s++;
    }
}

void
pstr_lower(pstr str)
{
  strlower((char *)str);
}

void
strupper(char *s)
{
  AssertStr(s);
  while (*s)
    {
      *s = toupper(*s);
      s++;
    }
}

void
pstr_upper(pstr s)
{
  strupper((char *)s);
}
