/***************************************************************************
 *   copyright           : (C) 2002 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "helper.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>

str_array_t* str_split (char* str, char* split, unsigned long count) {
  unsigned int i = 0;
  char* temp = str;
  char* temp2 = str;
  char** retval = NULL;
  size_t len = str_len(split);

  while (temp2 != NULL) {
    ++i;
    temp2 = strstr(temp,split);
    if (temp2 != NULL) temp = temp2 + len;
  }
  if (count == 0 || i < count) count = i;
  retval = mem_alloc((count+1)*sizeof(*retval),0);
  retval[count] = NULL;
  
  for (i = 0; i < count; ++i) {
    retval[i] = str;
    str = strstr(retval[i],split);
    if (str != NULL) {
      memset(str,0,len);
      str += len;
    }
  }
  return retval;
}

void str_array_uniq (str_array_t* array) {
  size_t i = 0, k = 0, l = 0;

  while (array[i] != NULL) ++i;
  for (; k < i; ++k)
    if (array[k] != NULL)
      for (l = k+1; l < i; ++l)
	if (array[l] != NULL && strcmp(array[l],array[k]) == 0)
	  array[l] = NULL;
  l = 0;
  for (k = 0; k < i; ++k) {
    if (array[k] == NULL) {
      if (l <= k) l = k+1;
      while (array[l] == NULL && l < i) ++l;
      if (l == i) break;
      array[k] = array[l];
      array[l++] = NULL;
    }
  }
}

str_array_t* str_array_append (str_array_t* array1, size_t size1,
			       str_array_t* array2, size_t size2)
{
  if (size2 > 0) {
    array1 = mem_realloc(array1,(size1+size2+1)*sizeof(array1));
    array1[size1+size2] = NULL;
    do {
      --size2;
      array1[size1+size2] = array2[size2];
    } while (size2 > 0);
  }
  return array1;
}

static int str_array_qsort_cb (const void* a, const void* b) {
  return strcmp((const char*)a,(const char*)b);
}

void str_array_sort (str_array_t* array) {
  size_t i = 0;

  while(array[i] != NULL) ++i;
  qsort((void*)array[0],i,sizeof(*array),str_array_qsort_cb);
}
