/**********************************************************************
 * do_scan.c  -- SS command for getting list of questions
 * tty lucy client using SS library
 *
 * $Author: brlewis $
 * $Source: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_scan.c,v $
 * $Header: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_scan.c,v 1.1 91/09/24 14:47:05 brlewis Exp Locker: brlewis $
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid_do_scan_c[] = "$Header: /afs/athena.mit.edu/astaff/project/lucydev/src/tty/do_scan.c,v 1.1 91/09/24 14:47:05 brlewis Exp Locker: brlewis $";
#endif /* lint */

#include <stdio.h>
#include <ss/ss.h>
#include <lucy/lucy.h>
#include <sys/wait.h>
#include "config.h"

void
do_scan(argc, argv)
     int argc;
     char *argv[];
{
  long code;
  int i;
  ltrn *t;
  FILE *fp;
  char fname[32];
  char call[64];

  if (argc > 2)
    {
      printf("Usage:  %s [question number]\n", argv[0]);
      return;
    }

  fp = stdout;		/* change if we need to |more */

  /* Make sure cached transaction info is up-to-date. */
  code = luc_reset_mtg(luv_curmtgp);
  if (code)
    {
      com_err(argv[0], code, luv_context);
      return;
    }

  /* Decide whether we're listing all questions or just one. */
  if (argc == 2)
    {
      /* listing just one question */
      if (code=luc_trn_info(luv_curmtgp, atoi(argv[1]), &t)) {
	com_err(argv[0], code, "(%s)", luv_context);
	return;
      }
      i = t->fref;
    }
  else
    {
      /* dealing with all questions; we need the pager */
      sprintf(fname, "%s/scan", luv_topdir);
      fp = fopen(fname, "w");
      if (fp)
	{
	  printf("Scanning...");
	  fflush(stdout);
	}
      else
	{
	  fp = stdout;
	}
      code = luc_next(luv_curmtgp, LUCY_NULLQ, &i);
      if (code) {
	com_err(argv[0], code, luv_context);
	return;
      }
    }

  while(i)
    {
      code = luc_trn_info(luv_curmtgp, i, &t);
      if (code)
	{
	  com_err(argv[0], code, luv_context);
	  return;
	}
      fprintf(fp, "%s\n", list_trn(t));
      if (argc == 2)
	{
	  i = t->nref;
	}
      else
	{
	  code = luc_next(luv_curmtgp, i, &i);
	  if (code) {
	    com_err(argv[0], code, luv_context);
	    return;
	  }
	}
    }

  if (argc < 2 && fp != stdout)
    {
      if (fclose(fp) == EOF) perror(fname);
      else printf("done\n");
      sprintf(call, "MORE=d more %s", fname);
      system(call);
    }
  return;
}
