/*
  parse.c - Simple string parser.

  Copyright (C) 2003, Colin Walsh <c_walsh@roadrunner.nf.net>
  See the file COPYING for more details

  Author: Colin Walsh <c_walsh@roadrunner.nf.net>
  Created on: February 7, 2003

  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.

  This program 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 this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include <stdlib.h>
#include <string.h>
#include "parse.h"

/*
  Splits a string into substrings divided by token
  Last string is a single \0.
*/
int argcount(char **strsplit)
{
  int count=0;
  if(strsplit[0][0] == 0) count=1; /* workaround for the absolute path bug */
  while(strsplit[count][0]!=0)
    {
      count++;
    }
  return count;
}
void freeargs(char **args)
{
  int i;
  for(i=0;i<argcount(args);i++)
    {
      free(args[i]);
    }
  free(args);
}
/* this function returns with the first element set to 0 if the path from the command line is absolute */
char **split(char *instring, char *token)
{
  int t_count=0, last, i;
  char **outstring;
  for(i=0;i<(int)strlen(instring);i++)
    {
      if(strncmp(&instring[i],token,strlen(token))==0)
	{
	  t_count++;
	}
    }
  outstring=(char **)malloc((t_count+2)*sizeof(char *));
  outstring[t_count+1]=(char *)malloc(1);
  outstring[t_count+1][0]=0;
  last=0;
  t_count=0;
  for(i=0;i<=(int)strlen(instring);i++)
    {
      if(strncmp(&instring[i],token,strlen(token))==0||i==(int)strlen(instring))/*problem?*/
	{
	  outstring[t_count]=(char *)malloc(i-last+1);
	  memcpy(outstring[t_count],&instring[last],i-last);
	  outstring[t_count][i-last]=0;
	  last=i+strlen(token);
	  t_count++;
	}
    }
  return outstring;
}
