
/*
 * whatnowproc.c -- exec whatnowproc
 *
 * $Id$
 */

#include <h/mh.h>


int
what_now (char *ed, int nedit, int use, char *file, char *altmsg, int dist,
          struct msgs *mp, char *text, int inplace, char *cwd)
{
    int found, k, msgnum, vecp;
    register char *bp;
    char buffer[BUFSIZ], *vec[MAXARGS];

    vecp = 0;
    vec[vecp++] = r1bindex (whatnowproc, '/');
    vec[vecp] = NULL;

    m_putenv ("mhdraft", file);
    if (mp)
	m_putenv ("mhfolder", mp->foldpath);
    else
	unputenv ("mhfolder");
    if (altmsg)
	if (mp == NULL || *altmsg == '/' || cwd == NULL)
	    m_putenv ("mhaltmsg", altmsg);
	else {
	    sprintf (buffer, "%s/%s", mp->foldpath, altmsg);
	    m_putenv ("mhaltmsg", buffer);
	}
    else
	unputenv ("mhaltmsg");
    if ((bp = getenv ("mhaltmsg")))/* XXX */
	m_putenv ("editalt", bp);
    sprintf (buffer, "%d", dist);
    m_putenv ("mhdist", buffer);
    if (nedit)
	unputenv ("mheditor");
    else
	m_putenv ("mheditor", ed ? ed : (ed = m_find ("editor")) ? ed : sysed);
    sprintf (buffer, "%d", use);
    m_putenv ("mhuse", buffer);

    unputenv ("mhmessages");
    unputenv ("mhannotate");
    unputenv ("mhinplace");
    if (text && mp && !(mp->msgflags & READONLY)) {
	found = 0;
	bp = buffer;
	for (msgnum = mp->lowmsg; msgnum <= mp->hghmsg; msgnum++)
	    if (mp->msgstats[msgnum] & SELECTED) {
		sprintf (bp, "%s%s", found ? " " : "", m_name (msgnum));
		bp += strlen (bp);
		for (k = msgnum + 1;
			k <= mp->hghmsg && mp->msgstats[k] & SELECTED;
			k++)
		    continue;
		if (--k > msgnum) {
		    sprintf (bp, "-%s", m_name (k));
		    bp += strlen (bp);
		}
		msgnum = k + 1;
		found++;
	    }
	if (found) {
	    m_putenv ("mhmessages", buffer);
	    m_putenv ("mhannotate", text);
	    sprintf (buffer, "%d", inplace);
	    m_putenv ("mhinplace", buffer);
	}
    }

    m_update ();
    fflush (stdout);

    if (cwd)
	chdir (cwd);

    if (strcmp (vec[0], "whatnow") == 0) {
	WhatNow (vecp, vec);
	done (0);
    }

    execvp (whatnowproc, vec);
    fprintf (stderr, "unable to exec ");
    perror (whatnowproc);

    return 0;
}
