/* list.c  94.07.29
 * Copyright 1983-1992   Albert Davis
 * list and save commands.
 * save is list with direction to file
 */
#include "ecah.h"
#include "branch.h"
#include "error.h"
#include "io.h"
#include "declare.h"
/*--------------------------------------------------------------------------*/
	void	cmd_list(const char*,int*);
	void	cmd_save(const char*,int*);
static	void	list_save(const char*,int*);
/*--------------------------------------------------------------------------*/
extern struct ioctrl io;
extern const char head[];
/*--------------------------------------------------------------------------*/
void cmd_list(const char *cmd, int *cnt)
{
 io.where = io.mstdout;
 list_save(cmd,cnt);
}
/*--------------------------------------------------------------------------*/
void cmd_save(const char *cmd, int *cnt)
{
 *cnt = 0;			  /* back up to beginning of input line	    */
 (void)outset(cmd,cnt,"","");
				  /* (outset will re-eat words save or list)*/
				  /* its purpose is to set up where to send */
				  /* the stuff.				    */
 list_save(cmd,cnt);
}
/*--------------------------------------------------------------------------*/
static void list_save(const char *cmd, int *cnt)
{
 branch_t *brh;

 mprintf(io.where&~io.mstdout, "%s\n", head);

 if (!cmd[*cnt]){			/* no args: list all		    */
    branch_t *stop;
    brh = firstbranch_all();
    if (!exists(brh)){
       error(bERROR, "no circuit\n");
    }
    stop = lastbranch_all();
    for (;;){
       print_branch(brh, io.where, NO);
       if (brh == stop)
          break;
       brh = nextbranch_all(brh);
    };
 }else{					/* some args: be selective	    */
    int arg;
    arg = *cnt;
    brh = findbranch(cmd,cnt, firstbranch_all(), lastbranch_all());
    if (!exists(brh)){
       syntax_msg(cmd,cnt,bERROR);
    }

    if (cmd[*cnt] == '-'){		/* there is a dash:  a range	    */
       branch_t *stop;
       (*cnt)++;
       stop = findbranch(cmd,cnt, brh, lastbranch_all());
       if (!exists(stop)){
	  syntax_check(cmd,cnt,bERROR);
	  stop = lastbranch_all();
       }
       for (;;){
	  print_branch(brh, io.where, NO);
	  if (brh == stop)
	     break;
	  brh = nextbranch_all(brh);
       }
    }else{				/* no dash: a list		    */
       int next;
       do {				/* each arg			    */
	  next = *cnt;
	  for (;;){			/* all that match this arg	    */
	     print_branch(brh, io.where, YES);
	     if (brh == lastbranch_all())
	        break;
	     *cnt = arg;
	     brh = findbranch(cmd, cnt, nextbranch_all(brh), lastbranch_all());
	     if (!exists(brh))
	        break;
	  }
       } while (*cnt = arg = next,
	     brh = findbranch(cmd, cnt, firstbranch_all(), lastbranch_all()),
	     exists(brh));
    }
 }
}
/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/
