/* cond.c -- contains HEif and HEselect */
#include "he.h"

/* HEif -- executes commands if predicates are satisfied */
int HEif(cmd)
    HE_CMD *cmd;
{
    HE_PRED *pred;		/* predicates */
    HE_CMD *cmdTail;		/* last cmd we've seen in the sublist */

    if (cmd->argc == 2 && !strcmp(cmd->argv[1],"-help"))
    {
	puts("if [<prediactes>]");
	puts("  <commands>*");
	puts("end");
	puts("\tExecutes commands if predicates are satisfied by element");
	return HE_OK;
    }

    /* parse the predicates on this command */
    pred = parsePred(cmd->argc, cmd->argv);
    if (!pred) return HE_FAIL;

    /* execute the sub list only is the predicates are satisfied */
    if (satPred(currDesc(), pred))
    {
	/* go through sub-list until an end is encountered */
	for (cmdTail = cmd->sub; strcmp(cmdTail->argv[0], "end");
	     cmdTail = cmdTail->next)
	    if (cmdTail->func)
		he_status = (*cmdTail->func) (cmdTail);
	    else
	    {
		fprintf(stderr, "Unrecognized command: %s\n", cmd->argv[0]);
		return HE_FAIL;
	    }
    }
    return HE_OK;
}

/* HEselect -- step through all the elements in a file and execute if
   predicates are satisfied */
int HEselect(cmd)
    HE_CMD *cmd;
{
    int t_currDesc;		/* tmp var */
    HE_PRED *pred;		/* predicate structure */
    HE_CMD *cmdTail;		/* last cmd we've seen in the sublist */

    if (cmd->argc == 2 && !strcmp(cmd->argv[1],"-help"))
    {
	puts("select [<prediactes>]");
	puts("  <commands>*");
	puts("end");
	puts("\tSteps through all elements in the file that satisfies the");
	puts("\tprediactes and execute the commands on them.");
	return HE_OK;
    }

    /* generate predicate structure for this predicate list */
    pred = parsePred(cmd->argc, cmd->argv);
    if (!pred) return HE_FAIL;

    /* save the curr desc index */
    t_currDesc = he_currDesc;

    /* step through all elements */
    for (he_currDesc = 0; he_currDesc < he_numDesc; he_currDesc++)
	if (currTag() != DFTAG_NULL && satPred(currDesc(), pred))
	    for (cmdTail = cmd->sub; strcmp(cmdTail->argv[0], "end");
		 cmdTail = cmdTail->next)
		if (cmdTail->func)
		    he_status = (*cmdTail->func) (cmdTail);
		else
		{
		    fprintf(stderr, "Unrecognized command: %s\n",
			    cmdTail->argv[0]);
		    he_status = HE_FAIL;
		}

    /* restore he_currDesc */
    he_currDesc = t_currDesc;

    return HE_OK;
}

/* end of cond.c */
