#ident "@(#)librfc2822: :strip_comments.c,v 1.1 2004/08/09 06:13:05 woods Exp "

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

#include <sys/cdefs.h>

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

#include "rfc2822.h"

/*
 * rfc822_strip_comments - destructively strip RFC822 comments from a string
 */
void
rfc2822_strip_comments(s)
	char           *s;
{
	char           *p;
	char           *q;
	int             c;
	int             level;

	p = q = s;
	while ((c = *p++)) {
		if (c == '(') {
			level = 1;

			while ((c = *p)) {
				p++;
				if (c == '(') {
					level++;
					continue;
				}
				if (c == ')') {
					--level;
					if (level == 0)
						break;

					continue;
				}
				if (c == '\\') {
					if (*p)
						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;
}
