/*
 *  hap -- a mail notification program
 * 
 *  copyright 1995 by Eric Fischer, etaoin@uchicago.edu
 * 
 *  copies of hap may be redistributed under the terms of the
 *  GNU public license, copies of which are available from
 *  the Free Software Foundation, 59 Temple Place, Boston, MA
 *  02111 USA.
 *
 */

#include "hap.h"

#ifdef HAVE_DIRENT_H
#	include <dirent.h>
#else
#	include <sys/types.h>
#	include <sys/dir.h>
#endif

/* remove a carriage return and anything following it from a string.
   return the end of the new string, for whatever that's worth.
*/

char *
stripcr (s)
	char *s;
{
	while (*s) {
		if (*s == '\012') {
			*s = 0;
			return s;
		}
		s++;
	}
	return s;
}

/* return a linked list of filenames in the directory s. */

flist *
lookdir(s)
	char *s;
{
	flist *ret = 0;
	DIR *thedir;
#ifdef HAVE_DIRENT_H
	struct dirent *rec;
#else
	struct direct *rec;
#endif

	thedir = opendir (s);
	if (thedir == 0) return 0;

	while ((rec = readdir (thedir))) {
		char c = rec->d_name[0];

		/* exclude deleted messages from the list we're
		   interested in.
		*/

		if (c != '.'
		&&  c != ','     /* soren says current mh uses this */
		&&  c != '#') {
			flist *new = (flist *) xmalloc (sizeof (flist));

			new->name = strdupe (rec->d_name);
			new->next = ret;

			ret = new;
		}
	}

	closedir (thedir);
	return ret;
}

/* return true if the node 'it' is also found in the list 'new' */

int
isin (new, it)
	flist *new;
	flist *it;
{
	while (new) {
		if (strcmp (new->name, it->name) == 0) return 1;
		new = new->next;
	}
	return 0;
}

/* return a linked list of all the elements of new which aren't in old */

flist *
diffdir (old, new)
	flist *old;
	flist *new;
{
	flist *ret = 0;

	while (new) {
		if (!isin (old, new)) {
			flist *n = (flist *) xmalloc (sizeof (flist));

			n->next = ret;
			n->name = strdupe (new->name);
			ret = n;
		}

		new = new->next;
	}
	return ret;
}

/* free each element of the linked list 'it' */

void
freelist (it)
	flist *it;
{
	while (it) {
		flist *tmp = it->next;

		free (it->name);
		free (it);

		it = tmp;
	}
}
