/*
   Remove unwanted characters from the beginning and end of a string.
   
   <kbd>
   <b>environ - C programming support functions</b><br>
   Copyright (C) 2005  Martin C Gregorie
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Lesser GNU General Public License.
   
   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 Lesser 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.
   </kbd>
  
   <p>Contact Martin Gregorie at <i>martin@gregorie.org</i></p>
*/

#include "environ.h"

#ifdef OS9
#include <strings.h>
#endif

#ifdef MSDOS
#include <string.h>
#endif

#ifdef LINUX
#include <string.h>
#endif

/*
   Trims any characters in the <i>u</i> string from the beginning
   and end of <i>s</i> and leaves the cleaned up string in
   <i>trimmed</i>, which must be at least as long as <i>s</i>.

   It is the caller's responsibility to make sure
   that <i>trimmed</i> is big enough to contain the trimmed string.
*/ 
void trimchars(char *trimmed, char *s, char *u)
{
   char buff[MAXLINE];
   int n; 
   int start;
   int end;

   strcpy(buff, s);
   n = strlen(buff);
   for (start = 0; start < n; start++)
      if (!strchr(u, buff[start]))
         break;
         
   for (end = n-1; end >= start; end--)
      if (!strchr(u, buff[end]))
         break;

   if (end < n-1)
      buff[end+1] = '\0';
      
   strcpy(trimmed, buff+start);
}

/*
   Trims any whitespace from the beginning and end of <i>s</i> and
   leaves the cleaned up string in <i>trimmed</i>, which must be at
   least as long as <i>s</i>.

   It is the caller's responsibility to make sure
   that <i>trimmed</i> is big enough to contain the trimmed string.
*/ 
void trim(char *trimmed, char *s)
{
   char u[6];

   u[0] = ' '; u[1] = '\t'; u[2] = '\n'; u[3] = '\r'; u[4] = '\f'; u[5] = '\0';
   trimchars(trimmed, s, u);
}
