/**********************************************************************
 * lucy_unpost.c -- unpost-answer routine for lucy
 *
 * $Source$
 * $Author$
 * $Header$
 *
 * Copyright 1990 by the Massachusetts Institute of Technology.
 * For copying and distribution information, see the file
 * "mit-copyright.h".
 **********************************************************************/
#include "mit-copyright.h"

#ifndef lint
static char rcsid_lucy_unpost_c[] = "$Header$";
#endif /* lint */

#include <stdio.h>
#include <ctype.h>
#include "lucy/lucy.h"
tfile unix_tfile();		/* XXX should be in discuss .h file */

void
lucy_unpost(argc, argv)
     int argc;
     char *argv[];
{
  long code;
  FILE *fp;
  tfile tf;
  lucy_qident i;
  name_blk *nb, nb2;

  i = atoi(argv[1]);		/* XXX more error checking */

  /* XXX use better way of getting username */
  dsc_get_mtg(getenv("USER"), LUCY_BROWSER, &nb2, &code);
  if (code) {
    com_err(argv[0], code, LUCY_BROWSER);
    return;
  }

  code = lucy_qnb(&nb);
  if (code) {
    com_err(argv[0], code, LUCY_INBOX);
    return;
  }

  fp = popen("more", "w");
  if (!fp) {
    perror(argv[0]);
    return;
  }

  tf = unix_tfile(fp->_file);
  dsc_get_trn(&nb2, i, tf, &code);

  pclose(fp);
  if (!say_yes("Unpost this transaction?")) return;
  dsc_delete_trn(&nb2, i, &code);
  if (code) {
    com_err(argv[0], code, "while unposting %d", i);
    return;
  }
  printf("Unposted transaction %d\n", i);
  return;
}

/**********************************************************************
 * say_yes(question, d)
 *    char *question
 *    int d;  [default TRUE or FALSE]
 *
 *   + prints question
 *   + gets yes or no answer
 *
 * Returns:
 *   + TRUE if yes
 *   + FALSE if no
 **********************************************************************/

int
say_yes(question, d)

     char *question;
     int d;
{
  char answer[256];

  printf("%s (y/n, default: %c) ", question, d ? 'y' : 'n');
  switch(gets(answer)[0]) {
  case 'y':
  case 'Y':
    return(TRUE);
  case 'n':
  case 'N':
    return(FALSE);
  default:
    return(d);
  }
}

/**********************************************************************
 * promptfor(prompt, s)
 *    char *prompt, *s
 *
 *   + prints "prompt:  "
 *   + puts answer in s
 **********************************************************************/

promptfor(prompt, s)

     char *prompt, *s;
{
  int i;

  printf("%s:  ", prompt);
  if (strlen(gets(s)) == 0) return;

  /* remove trailing blanks */
  for(i=strlen(s)-1; i>0; i--) {
    if (isspace(s[i]))
      s[i] = '\0';
    else break;
  }

  /* remove leading blanks */
  for(i=0; i<strlen(s); i++)
    if (! isspace(s[i]))
      break;
  (void) strcpy(s, s+i);

  return;
}
