#ident "@(#)librfc2822: :strip_whitespace.c,v 1.2 2004/08/14 02:50:25 woods Exp "

/*
 * Copyright (c) 2004	Greg A. Woods <woods@planix.com>
 */

#include <sys/cdefs.h>

#include <ctype.h>
#include <stdio.h>			/* for FILE in rfc2822.h */
#include <string.h>

#include "rfc2822.h"

/*
 * rfc822_strip_whitespace - destructively strip *extra* whitespace from a string
 */
void
rfc2822_strip_whitespace(s)
	char           *s;
{
	char           *p;
	char           *q;
	int             c;
	int             level;
	static char     delims[] = "@:;<>().,";
	int             space = 0;

	p = q = s;
	while ((c = *p++)) {
		if (isspace(c)) {
			space = 1;
			continue;
		}
		if (space) {
			space = 0;
			if (q > s && !strchr(delims, *(q - 1)) && !strchr(delims, c))
				*q++ = ' ';
		}
		if (c == '(') {
			level = 1;
			
			while ((c = *p++)) {
				*q++ = c;
				if (c == '(') {
					level++;
					continue;
				}
				if (c == ')') {
					--level;
					if (level == 0)
						break;

					continue;
				}
				if (c == '\\') {
					if (*p) {
						*q++ = c;
						p++;
					}
				}
			}
			continue;
		}
		if (c == '\\') {
			*q++ = c;
			if ((c = *p)) {
				*q++ = c;
				p++;
			}
			continue;
		}
		if (c == '"') {
			*q++ = c;
			while ((c = *p)) {
				p++;
				*q++ = c;
				if (c == '"')
					break;

				if (c == '\\') {
					if ((c = *p)) {
						*q++ = c;
						p++;
					}
				}
			}
			continue;
		}
		*q++ = c;
	}
	*q++ = '\0';

	return;
}
