/**********************************************************************
 * luc_unarchive.c -- unarchive a chain of transactions
 *
 * $Author: brlewis $
 * $Source: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_unarchive.c,v $
 * $Header: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_unarchive.c,v 1.1 91/09/24 14:37:46 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_luc_unarchive_c[] = "$Header: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_unarchive.c,v 1.1 91/09/24 14:37:46 brlewis Exp Locker: brlewis $";
#endif /* lint */

#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/errno.h>
#include "lucy/lucy.h"

/**********************************************************************
 * luc_archvive(lmeeting *mp, int n, int *np)
 *	caller sets mp (usually luv_curmtgp) to specify meeting
 *	caller sets n to first transaction number in archive
 *
 * - reads summary of archived transactions
 * - undeletes transactions
 * - points np at first unarchived transaction
 * - returns error code
 **********************************************************************/

long
luc_unarchive(mp, n, np)
     LMEETING *mp;
     int n, *np;
{
  long code;
  char *fname;
  FILE *fp;
  int i, foo=0;
  char buf[512];
  ltrn *t;

  /* get filename for summary */
  if (code=luc_trn_file(&luv_amtg, n, &fname)) return(code);

  /* open file */
  fp = fopen(fname, "r");
  luc_free_file(&fname);
  if (!fp) {
    strcpy(luv_context, fname);
    return((long) errno);
  }

  /* verify that it is indeed the summary transaction */
  if (!fgets(buf, 511, fp)) return((long) EINVAL);
  if (strncmp(buf, LUCY_ARCHIVE, strlen(LUCY_ARCHIVE)))
    return((long) EINVAL);

  /* look for lines that begin with a digit */
  while (fgets(buf, 511, fp)) {
    if (buf[0] < '0' || buf[0] > '9') continue;
    i = atoi(buf);
    if (code = luc_undelete(mp, i)) break;
    /* point np at first unarchived trn */
    if (!foo) { foo=1; *np=i; };
  }

  /* close the file and check for errors */
  (void) fclose(fp);
  if (code) return(code);

  /* ok to delete from archives now */
  for(i=n; i; i=t->nref) {
    /* get info on trn */
    if (code=luc_trn_info(&luv_amtg, i, &t)) break;
    if (code=luc_delete(&luv_amtg, i)) break;
  }
  return(code);
}
