
/*
 * folder_pack.c -- pack the messages in a folder
 *
 * $Id$
 */

#include <h/mh.h>

/*
 * Pack the message in a folder.
 * Return -1 if error, else return 0.
 */

int
folder_pack (struct msgs **mpp, int verbose)
{
    register int hole, msgnum;
    char newmsg[BUFSIZ], oldmsg[BUFSIZ];
    struct msgs *mp;

    mp = *mpp;

    if (mp->lowmsg > 1) {
	if ((mp = folder_realloc (mp, 1, mp->hghmsg)))
	    *mpp = mp;
	else {
	    advise (NULL, "unable to allocate folder storage");
	    return -1;
	}
    }

    for (msgnum = mp->lowmsg, hole = 1; msgnum <= mp->hghmsg; msgnum++) {
	if (does_exist (mp, msgnum)) {
	    if (msgnum != hole) {
		strcpy (newmsg, m_name (hole));
		strcpy (oldmsg, m_name (msgnum));
		if (verbose)
		    printf ("message %s becomes %s\n", oldmsg, newmsg);
		if (rename (oldmsg, newmsg) == -1) {
		    advise (newmsg, "unable to rename %s to", oldmsg);
		    return -1;
		}
		if (msgnum == mp->curmsg)
		    seq_setcur (mp, mp->curmsg = hole);
		mp->msgstats[hole] = mp->msgstats[msgnum];
		mp->msgflags |= SEQMOD;
		if (msgnum == mp->lowsel)
		    mp->lowsel = hole;
		if (msgnum == mp->hghsel)
		    mp->hghsel = hole;
	    }
	    hole++;
	}
    }
    if (mp->nummsg > 0) {
	mp->lowmsg = 1;
	mp->hghmsg = hole - 1;
    }

    return 0;
}
