/* This file is part of GNU Pies.
   Copyright (C) 2007-2019 Sergey Poznyakoff

   GNU Pies 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 3, or (at your option)
   any later version.

   GNU Pies 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 GNU Pies.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "libpies.h"

static int
split3 (const char *input, char *res[3], int flag)
{
  size_t len;
  char *p;

  p = strchr (input, ' ');
  if (!p)
    return 1;

  len = p - input;
  res[0] = malloc (len + 1);
  if (!res[0])
    return -1;
  memcpy (res[0], input, len);
  res[0][len] = 0;

  input = p + 1;

  p = (flag ? strrchr : strchr) (input, ' ');

  if (!p)
    return 1;

  len = p - input;
  res[1] = malloc (len + 1);
  if (!res[1])
    return -1;
  memcpy (res[1], input, len);
  res[1][len] = 0;
  
  res[2] = strdup (p + 1);
  if (!res[2])
    return -1;

  return 0;
}

int
strsplit3 (const char *input, char *result[3], int flag)
{
  char *tmp[3] = { NULL, NULL, NULL };
  int rc = split3 (input, tmp, flag);
  if (rc)
    {
      int ec = errno;
      free (tmp[0]);
      free (tmp[1]);
      free (tmp[2]);
      errno = ec;
    }
  else
    {
      result[0] = tmp[0];
      result[1] = tmp[1];
      result[2] = tmp[2];
    }
  return rc;
}
