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

#include <h/mh.h>

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

    if (mp->lowmsg > 1 && (mp = m_remsg (mp, 1, mp->hghmsg)) == NULL)
	adios (NULL, "unable to allocate folder storage");

    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) == NOTOK)
		    adios (newmsg, "unable to rename %s to", oldmsg);
		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 mp;
}
