Пример #1
0
static void
syspipe(void)
{
	u32int fd, *fdt;
	int buffered;
	
	fd = arg(0);
	if(systrace)
		fprint(2, "pipe(%#ux)\n", fd);
	fdt = bufifnec(fd, 8, &buffered);
	P->R[0] = noteerr(pipe((int *) fdt), 0);
	if(buffered)
		copyback(fd, 8, fdt);
}
Пример #2
0
static void
sysawait(void)
{
	u32int s, n;
	void *st;
	int buffered;
	
	s = arg(0);
	n = arg(1);
	st = bufifnec(s, n, &buffered);
	if(systrace)
		fprint(2, "await(%#ux, %d)\n", s, n);
	P->R[0] = noteerr(await(st, n), 0);
	if(buffered)
		copyback(s, P->R[0], st);
}
Пример #3
0
static void
syserrstr(void)
{
	char buf[ERRMAX], *srct;
	u32int src, len;
	int copied;
	
	src = arg(0);
	len = arg(1);
	srct = copyifnec(src, len, &copied);
	strcpy(buf, P->errbuf);
	utfecpy(P->errbuf, P->errbuf + ERRMAX, srct);
	utfecpy(srct, srct + len, buf);
	if(copied)
		copyback(src, len, srct);
	P->R[0] = 0;
}
Пример #4
0
static void
sysfstat(void)
{
	u32int fd, edir, nedir;
	void *edirt;
	int buffered;
	
	fd = arg(0);
	edir = arg(1);
	nedir = arg(2);
	edirt = bufifnec(edir, nedir, &buffered);
	if(systrace)
		fprint(2, "fstat(%d, %#ux, %d)\n", fd, edir, nedir);
	P->R[0] = noteerr(fstat(fd, edirt, nedir), nedir);
	if(buffered)
		copyback(edir, P->R[0], edirt);
}
Пример #5
0
static void
sysfd2path(void)
{
	u32int fd, buf, nbuf;
	void *buft;
	int buffered;
	
	fd = arg(0);
	buf = arg(1);
	nbuf = arg(2);
	buft = bufifnec(buf, nbuf, &buffered);
	if(systrace)
		fprint(2, "fd2path(%d, %#ux, %d)\n", fd, buf, nbuf);
	P->R[0] = noteerr(fd2path(fd, buft, nbuf), 0);
	if(buffered)
		copyback(buf, nbuf, buft);
}
Пример #6
0
static void
syspread(void)
{
	int buffered;
	u32int fd, size, buf;
	u64int off;
	void *targ;
	
	fd = arg(0);
	buf = arg(1);
	size = arg(2);
	off = argv(3);
	if(systrace)
		fprint(2, "pread(%d, %#ux, %ud, %#ullx)\n", fd, buf, size, off);
	targ = bufifnec(buf, size, &buffered);
	P->R[0] = noteerr(pread(fd, targ, size, off), size);
	if(buffered)
		copyback(buf, P->R[0], targ);
}
Пример #7
0
static void
sysstat(void)
{
	u32int name, edir, nedir;
	char *namet;
	void *edirt;
	int copied, buffered;
	
	name = arg(0);
	namet = copyifnec(name, -1, &copied);
	edir = arg(1);
	nedir = arg(2);
	edirt = bufifnec(edir, nedir, &buffered);
	if(systrace)
		fprint(2, "stat(%#ux=\"%s\", %#ux, %ud)\n", name, namet, edir, nedir);
	P->R[0] = noteerr(stat(namet, edirt, nedir), nedir);
	if(copied)
		free(namet);
	if(buffered)
		copyback(edir, P->R[0], edirt);
}
Пример #8
0
/*
 *	Print mail entries
 */
void
printmail()
{
	static char pn[] = "printmail";
	int	flg, curlet, showlet, k, print, aret, stret, rc;
	int	nsmbox = 0;	/* 1 ==> mailbox is in non-standard place */
	int	sav_j = -1;
	char	*p, *getarg();
	struct	stat stbuf;
	struct	stat *stbufp;
	int ttyf = isatty(1) ? TTY : ORDINARY;
	char	readbuf[LSIZE];	/* holds user's response in interactive mode */
	char	*resp;
	gid_t	savedegid;

	stbufp = &stbuf;

	/*
	 *	create working directory mbox name
	 */
	if ((hmbox = malloc(strlen(home) + strlen(mbox) + 1)) == NULL) {
		errmsg(E_MBOX, "");
		return;
	}
	cat(hmbox, home, mbox);

	/*
	 *	If we are not using an alternate mailfile, then get
	 *	the $MAIL value and build the filename for the mailfile.
	 *	If $MAIL is set, but is NOT the 'standard' place, then
	 *	use it but set flgf to circumvent :saved processing.
	 */
	if (!flgf) {
		if ((p = malloc(strlen(maildir) + strlen(my_name) + 1))
								== NULL) {
			errmsg(E_MEM, "");
			return;
		}
		cat(p, maildir, my_name);
		if (((mailfile = getenv("MAIL")) == NULL) ||
		    (strlen(mailfile) == 0)) {
			/* $MAIL not set, use standard path to mailfile */
			mailfile = p;
		} else {
			if (strcmp(mailfile, p) != 0) {
			    flgf = 1;
			    nsmbox = 1;
			    Dout(pn, 0, "$MAIL ('%s') != standard path\n",
				mailfile);
			    Dout("", 0, "\tSetting flgf to 1.\n");
			}
			free(p);
		}
	}

	/*
	 *	Get ACCESS and MODIFICATION times of mailfile BEFORE we
	 *	use it. This allows us to put them back when we are
	 *	done. If we didn't, the shell would think NEW mail had
	 *	arrived since the file times would have changed.
	 */
	stret = CERROR;
	if (access(mailfile, A_EXIST) == A_OK) {
		if ((stret = stat(mailfile, stbufp)) != A_OK) {
			errmsg(E_FILE, "Cannot stat mailfile");
			return;
		}
		mf_gid = stbufp->st_gid;
		mf_uid = stbufp->st_uid;
		utimep->actime = stbufp->st_atime;
		utimep->modtime = stbufp->st_mtime;
		file_size = stbufp->st_size;
	}

	/* Open the file as the real gid */
	savedegid = getegid();
	(void) setegid(getgid());
	malf = fopen(mailfile, "r");
	(void) setegid(savedegid);
	/*
	 *	stat succeeded, but we cannot access the mailfile
	 */
	if (stret == CSUCCESS && malf == NULL) {
		char buf[MAXFILENAME+50];
		(void) snprintf(buf, sizeof (buf),
		    "Invalid permissions on %s", mailfile);
		errmsg(E_PERM, buf);
		return;
	} else
	/*
	 *	using an alternate mailfile, but we failed on access
	 */
	if (!nsmbox && flgf && (malf == NULL)) {
		errmsg(E_FILE, "Cannot open mailfile");
		return;
	}
	/*
	 *	we failed to access OR the file is empty
	 */
	else if ((malf == NULL) || (stbuf.st_size == 0)) {
		if (!flge && !flgE) {
			printf("No mail.\n");
		}
		error = E_FLGE;
		Dout(pn, 0, "error set to %d\n", error);
		return;
	}
	if (flge)
		return;

	if (flgE) {
		if (utimep->modtime < utimep->actime) {
			error = E_FLGE_OM;
			Dout(pn, 0, "error set to %d\n", error);
		}
		return;
	}
	/*
	 *	Secure the mailfile to guarantee integrity
	 */
	lock(my_name);

	/*
	 *	copy mail to temp file and mark each letter in the
	 *	let array --- mailfile is still locked !!!
	 */
	mktmp();
	copymt(malf, tmpf);
	onlet = nlet;
	fclose(malf);
	fclose(tmpf);
	unlock();	/* All done, OK to unlock now */
	tmpf = doopen(lettmp, "r+", E_TMP);
	changed = 0;
	print = 1;
	curlet = 0;
	while (curlet < nlet) {
		/*
		 *	reverse order ?
		 */
		showlet = flgr ? curlet : nlet - curlet - 1;

		if (setjmp(sjbuf) == 0 && print != 0) {
				/* -h says to print the headers first */
				if (flgh) {
					gethead(showlet, 0);
					flgh = 0;	/* Only once */
					/* set letter # to invalid # */
					curlet--;
					showlet =
					    flgr ? curlet : nlet - curlet - 1;
				} else {
					if (showlet != sav_j) {
						/* Looking at new message. */
						/* Reset flag to override */
						/* non-display of binary */
						/* contents */
						sav_j = showlet;
						pflg = 0;
						Pflg = flgP;
					}
					copylet(showlet, stdout, ttyf);
				}
		}

		/*
		 *	print only
		 */
		if (flgp) {
			curlet++;
			continue;
		}
		/*
		 *	Interactive
		 */
		interactive = 1;
		setjmp(sjbuf);
		stat(mailfile, stbufp);
		if (stbufp->st_size != file_size) {
			/*
			 *	New mail has arrived, load it
			 */
			k = nlet;
			lock(my_name);
			malf = doopen(mailfile, "r", E_FILE);
			fclose(tmpf);
			tmpf = doopen(lettmp, "a", E_TMP);
			fseek(malf, let[nlet].adr, 0);
			copymt(malf, tmpf);
			file_size = stbufp->st_size;
			fclose(malf);
			fclose(tmpf);
			unlock();
			tmpf = doopen(lettmp, "r+", E_TMP);
			if (++k < nlet)
				printf("New mail loaded into letters %d - %d\n",
				    k, nlet);
			else
				printf("New mail loaded into letter %d\n",
				    nlet);
		}

		/* read the command */
		printf("? ");
		fflush(stdout);
		fflush(stderr);
		if (fgets(readbuf, sizeof (readbuf), stdin) == NULL) break;
		resp = readbuf;
		while (*resp == ' ' || *resp == '\t') resp++;
		print = 1;
		Dout(pn, 0, "resp = '%s'\n", resp);
		if ((rc = atoi(resp)) != 0) {
			if (!validmsg(rc)) print = 0;
			else curlet = flgr ? rc - 1 : nlet - rc;
		} else switch (resp[0]) {
			default:
				printf("Usage:\n");
			/*
			 *	help
			 */
			case '?':
				print = 0;
				for (rc = 0; help[rc]; rc++)
					printf("%s", help[rc]);
				break;
			/*
			 *	print message number of current message
			 */
			case '#':
				print = 0;
				if ((showlet == nlet) || (showlet < 0)) {
					printf("No message selected yet.\n");
				} else {
					printf("Current message number is %d\n",
					    showlet+1);
				}
				break;
			/*
			 *	headers
			 */
			case 'h':
				print = 0;
				if (resp[2] != 'd' &&
				    resp[2] != 'a' &&
				    (rc = getnumbr(resp+1)) > 0) {
					showlet = rc - 1;
					curlet = flgr ? rc - 1 : nlet - rc- 1;
				}
				if (rc == -1 && resp[2] != 'a' &&
				    resp[2] != 'd')
					break;
				if (resp[2] == 'a') rc = 1;
				else if (resp[2] == 'd') rc = 2;
					else rc = 0;

/*
 *				if (!validmsg(showlet)) break;
 */
				gethead(showlet, rc);
				break;
			/*
			 *	skip entry
			 */
			case '+':
			case 'n':
			case '\n':
				curlet++;
				break;
			case 'P':
				Pflg++;
				break;
			case 'p':
				pflg++;
				break;
			case 'x':
				changed = 0;
			case 'q':
				goto donep;
			/*
			 *	Previous entry
			 */
			case '^':
			case '-':
				if (--curlet < 0) curlet = 0;
				break;
			/*
			 *	Save in file without header
			 */
			case 'y':
			case 'w':
			/*
			 *	Save mail with header
			 */
			case 's':
				print = 0;
				if (!validmsg(curlet)) break;
				if (resp[1] == '\n' || resp[1] == '\0') {
					cat(resp+1, hmbox, "");
				} else if (resp[1] != ' ') {
					printf("Invalid command\n");
					break;
				}
				umask(umsave);
				flg = 0;
				if (getarg(lfil, resp + 1) == NULL) {
					cat(resp + 1, hmbox, "");
				}
				malf = (FILE *)NULL;
				p = resp + 1;
				while ((p = getarg(lfil, p)) != NULL) {
					if (flg) {
					    fprintf(stderr,
						"%s: File '%s' skipped\n",
						program, lfil);
					    continue;
					}
					malf = NULL;
					if ((aret = legal(lfil))) {
						malf = fopen(lfil, "a");
					}
					if ((malf == NULL) || (aret == 0)) {
					    fprintf(stderr,
						"%s: Cannot append to %s\n",
						program, lfil);
					    flg++;
					} else if (aret == 2) {
						chown(lfil, my_euid, my_gid);
					}
					if (!flg &&
					    copylet(showlet, malf, resp[0] ==
					    's'? ORDINARY: ZAP) == FALSE) {
						fprintf(stderr,
					    "%s: Cannot save mail to '%s'\n",
						    program, lfil);
						flg++;
					} else
						Dout(pn, 0, "!saved\n");
					if (malf != (FILE *)NULL) {
						fclose(malf);
					}
				}
				umask(7);
				if (!flg) {
					setletr(showlet, resp[0]);
					print = 1;
					curlet++;
				}
				break;
			/*
			 *	Reply to a letter
			 */
			case 'r':
				print = 0;
				if (!validmsg(curlet)) break;
				replying = 1;
				for (k = 1; resp[k] == ' ' || resp[k] == '\t';
				    ++k);
				resp[strlen(resp)-1] = '\0';
				(void) strlcpy(m_sendto, resp+k,
				    sizeof (m_sendto));
				goback(showlet);
				replying = 0;
				setletr(showlet, resp[0]);
				break;
			/*
			 *	Undelete
			 */
			case 'u':
				print = 0;
				if ((k = getnumbr(resp+1)) <= 0) k = showlet;
				else k--;
				if (!validmsg(k)) break;
				setletr(k, ' ');
				break;
			/*
			 *	Mail letter to someone else
			 */
			case 'm':
				{
				reciplist list;
				print = 0;
				if (!validmsg(curlet)) break;
				new_reciplist(&list);
				flg = 0;
				k = 0;
				if (substr(resp, " -") != -1 ||
					substr(resp, "\t-") != -1) {
					printf("Only users may be specified\n");
					break;
				}
				p = resp + 1;
				while ((p = getarg(lfil, p)) != NULL) {
					char *env;
					if (lfil[0] == '$') {
						if (!(env = getenv(&lfil[1]))) {
							fprintf(stderr,
				"%s: %s has no value or is not exported.\n",
							    program, lfil);
							flg++;
						} else
							add_recip(&list, env,
							    FALSE);
						k++;
					} else if (lfil[0] != '\0') {
						add_recip(&list, lfil, FALSE);
						k++;
					}
				}
				(void) strlcpy(Rpath, my_name, sizeof (Rpath));
				sending = TRUE;
				flg += sendlist(&list, showlet, 0);
				sending = FALSE;
				if (k) {
					if (!flg) {
						setletr(showlet, 'm');
						print = 1;
						curlet++;
					}
				} else
					printf("Invalid command\n");
				del_reciplist(&list);
				break;
				}
			/*
			 *	Read new letters
			 */
			case 'a':
				if (onlet == nlet) {
					printf("No new mail\n");
					print = 0;
					break;
				}
				curlet = 0;
				print = 1;
				break;
			/*
			 *	Escape to shell
			 */
			case '!':
				systm(resp + 1);
				printf("!\n");
				print = 0;
				break;
			/*
			 *	Delete an entry
			 */
			case 'd':
				print = 0;
				k = 0;
				if (strncmp("dq", resp, 2) != SAME &&
					strncmp("dp", resp, 2) != SAME)
					if ((k = getnumbr(resp+1)) == -1) break;
				if (k == 0) {
					k = showlet;
					if (!validmsg(curlet)) break;
					print = 1;
					curlet++;
				} else	k--;

				setletr(k, 'd');
				if (resp[1] == 'p') print = 1;
				else if (resp[1] == 'q') goto donep;
				break;
		}
	}
	/*
	 *	Copy updated mailfile back
	 */
donep:
	if (changed) {
		copyback();
		stamp();
	}
}
Пример #9
0
/*
Manage the whole stuff.
*/
void	makeit()

  {
   checkstruct		*check;
   picstruct		*dfield, *field,*pffield[MAXFLAG], *wfield,*dwfield;
   catstruct		*imacat;
   tabstruct		*imatab;
   patternstruct	*pattern;
   static time_t        thetime1, thetime2;
   struct tm		*tm;
   unsigned int		modeltype;
   int			nflag[MAXFLAG], nparam2[2],
			i, nok, ntab, next, ntabmax, forcextflag,
			nima0,nima1, nweight0,nweight1, npsf0,npsf1, npat,npat0;

   next = 0;
   nok = 1;

/* Processing start date and time */
  dtime = counter_seconds();
  thetimet = time(NULL);
  tm = localtime(&thetimet);
  sprintf(prefs.sdate_start,"%04d-%02d-%02d",
        tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
  sprintf(prefs.stime_start,"%02d:%02d:%02d",
        tm->tm_hour, tm->tm_min, tm->tm_sec);

  NFPRINTF(OUTPUT, "");
  QPRINTF(OUTPUT, "----- %s %s started on %s at %s with %d thread%s\n\n",
		BANNER,
		MYVERSION,
		prefs.sdate_start,
		prefs.stime_start,
		prefs.nthreads,
		prefs.nthreads>1? "s":"");

/* Initialize globals variables */
  initglob();

  NFPRINTF(OUTPUT, "Setting catalog parameters");
  readcatparams(prefs.param_name);
  useprefs();			/* update things accor. to prefs parameters */

/* Check if a specific extension should be loaded */
/* Never true for an NDF, although we could through all NDFs in a container, */
/* so we make selectext go away. */
  nima0 = -1;
  forcextflag = 0;

/* Do the same for other data (but do not force single extension mode) */
  nima1 = -1;    /* selectext(prefs.image_name[1]) */
  nweight0 = -1; /* selectext(prefs.wimage_name[0]) */
  nweight1 = -1; /* selectext(prefs.wimage_name[1]) */
  if (prefs.dpsf_flag)
    {
    npsf0 = -1; /* selectext(prefs.psf_name[0]) */
    npsf1 = -1; /* selectext(prefs.psf_name[1]) */
    }
  else
    npsf0 = -1; /* selectext(prefs.psf_name[0]) */
  for (i=0; i<prefs.nfimage_name; i++)
    nflag[i] = -1; /* selectext(prefs.fimage_name[i]) */

  if (prefs.psf_flag)
    {
/*-- Read the first PSF extension to set up stuff such as context parameters */
    NFPRINTF(OUTPUT, "Reading PSF information");
    if (prefs.dpsf_flag)
      {
      thedpsf = psf_load(prefs.psf_name[0],nima0<0? 1 :(npsf0<0? 1:npsf0)); 
      thepsf = psf_load(prefs.psf_name[1], nima1<0? 1 :(npsf1<0? 1:npsf1));
      }
    else
      thepsf = psf_load(prefs.psf_name[0], nima0<0? 1 :(npsf0<0? 1:npsf0)); 
 /*-- Need to check things up because of PSF context parameters */
    updateparamflags();
    useprefs();
    }

  if (prefs.prof_flag)
    {
#ifdef USE_MODEL
    fft_init(prefs.nthreads);
/* Create profiles at full resolution */
    NFPRINTF(OUTPUT, "Preparing profile models");
    modeltype = (FLAG(obj2.prof_offset_flux)? MODEL_BACK : MODEL_NONE)
	|(FLAG(obj2.prof_dirac_flux)? MODEL_DIRAC : MODEL_NONE)
	|(FLAG(obj2.prof_spheroid_flux)?
		(FLAG(obj2.prof_spheroid_sersicn)?
			MODEL_SERSIC : MODEL_DEVAUCOULEURS) : MODEL_NONE)
	|(FLAG(obj2.prof_disk_flux)? MODEL_EXPONENTIAL : MODEL_NONE)
	|(FLAG(obj2.prof_bar_flux)? MODEL_BAR : MODEL_NONE)
	|(FLAG(obj2.prof_arms_flux)? MODEL_ARMS : MODEL_NONE);
    theprofit = profit_init(thepsf, modeltype);
    changecatparamarrays("VECTOR_MODEL", &theprofit->nparam, 1);
    changecatparamarrays("VECTOR_MODELERR", &theprofit->nparam, 1);
    nparam2[0] = nparam2[1] = theprofit->nparam;
    changecatparamarrays("MATRIX_MODELERR", nparam2, 2);
    if (prefs.dprof_flag)
      thedprofit = profit_init(thedpsf, modeltype);
    if (prefs.pattern_flag)
      {
      npat0 = prefs.prof_disk_patternvectorsize;
      if (npat0<prefs.prof_disk_patternmodvectorsize)
        npat0 = prefs.prof_disk_patternmodvectorsize;
      if (npat0<prefs.prof_disk_patternargvectorsize)
        npat0 = prefs.prof_disk_patternargvectorsize;
/*---- Do a copy of the original number of pattern components */
      prefs.prof_disk_patternncomp = npat0;
      pattern = pattern_init(theprofit, prefs.pattern_type, npat0);
      if (FLAG(obj2.prof_disk_patternvector))
        {
        npat = pattern->size[2];
        changecatparamarrays("DISK_PATTERN_VECTOR", &npat, 1);
        }
      if (FLAG(obj2.prof_disk_patternmodvector))
        {
        npat = pattern->ncomp*pattern->nfreq;
        changecatparamarrays("DISK_PATTERNMOD_VECTOR", &npat, 1);
        }
      if (FLAG(obj2.prof_disk_patternargvector))
        {
        npat = pattern->ncomp*pattern->nfreq;
        changecatparamarrays("DISK_PATTERNARG_VECTOR", &npat, 1);
        }
      pattern_end(pattern);
      }
    QPRINTF(OUTPUT, "Fitting model: ");
    for (i=0; i<theprofit->nprof; i++)
      {
      if (i)
        QPRINTF(OUTPUT, "+");
      QPRINTF(OUTPUT, "%s", theprofit->prof[i]->name);
      }
    QPRINTF(OUTPUT, "\n");
    if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
      {
      thepprofit = profit_init(thepsf, MODEL_DIRAC);
      theqprofit = profit_init(thepsf, MODEL_EXPONENTIAL);
      }
#else
    error(EXIT_FAILURE,
		"*Error*: model-fitting is not supported in this build.\n",
			" Please check your configure options");
#endif
    }

  if (prefs.filter_flag)
    {
    NFPRINTF(OUTPUT, "Reading detection filter");
    getfilter(prefs.filter_name);	/* get the detection filter */
    }

  if (FLAG(obj2.sprob))
    {
    NFPRINTF(OUTPUT, "Initializing Neural Network");
    neurinit();
    NFPRINTF(OUTPUT, "Reading Neural Network Weights");
    getnnw(); 
    }

  if (prefs.somfit_flag)
    {
     int	margin;

    thesom = som_load(prefs.som_name);
    if ((margin=(thesom->inputsize[1]+1)/2) > prefs.cleanmargin)
      prefs.cleanmargin = margin;
    if (prefs.somfit_vectorsize>thesom->neurdim)
      {
      prefs.somfit_vectorsize = thesom->neurdim;
      sprintf(gstr,"%d", prefs.somfit_vectorsize);
      warning("Dimensionality of the SOM-fit vector limited to ", gstr);
      }
    }

/* Prepare growth-curve buffer */
  if (prefs.growth_flag)
    initgrowth();

/* Allocate memory for multidimensional catalog parameter arrays */
  alloccatparams();
  useprefs();

/*-- Init the CHECK-images */
  if (prefs.check_flag)
    {
      checkenum	c;
      
      NFPRINTF(OUTPUT, "Initializing check-image(s)");
      for (i=0; i<prefs.ncheck_type; i++)
        if ((c=prefs.check_type[i]) != CHECK_NONE)
          {
            if (prefs.check[c])
              error(EXIT_FAILURE,"*Error*: 2 CHECK_IMAGEs cannot have the same ",
                        " CHECK_IMAGE_TYPE");
            prefs.check[c] = initcheck(prefs.check_name[i], prefs.check_type[i],
                                       next);
            free(prefs.check_name[i]);
          }
    }

  NFPRINTF(OUTPUT, "Initializing catalog");
  initcat();
  
/* Initialize XML data */
  if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
    init_xml(next);

/* Go through all images */
/* for all images in an MEF */

/*---- Initial time measurement*/
  time(&thetime1);
  thecat.currext = nok+1;
  
  dfield = field = wfield = dwfield = NULL;

/*---- Init the Detection and Measurement-images */
  if (prefs.dimage_flag)
  {
      dfield = newfield(prefs.image_name[0], DETECT_FIELD, nok);
      field = newfield(prefs.image_name[1], MEASURE_FIELD, nok);
      if ((field->width!=dfield->width) || (field->height!=dfield->height))
          error(EXIT_FAILURE, "*Error*: Frames have different sizes","");
/*---- Prepare interpolation */
      if (prefs.dweight_flag && prefs.interp_type[0] == INTERP_ALL)
          init_interpolate(dfield, -1, -1);
      if (prefs.interp_type[1] == INTERP_ALL)
          init_interpolate(field, -1, -1);
  }
  else
  {
      field = newfield(prefs.image_name[0], DETECT_FIELD | MEASURE_FIELD, nok);
/*-- Prepare interpolation */
      if ((prefs.dweight_flag || prefs.weight_flag)
          && prefs.interp_type[0] == INTERP_ALL)
          init_interpolate(field, -1, -1);       /* 0.0 or anything else */
  }

/*-- Init the WEIGHT-images */
  if (prefs.dweight_flag || prefs.weight_flag) 
  {
      weightenum	wtype;
      PIXTYPE	interpthresh;

      if (prefs.nweight_type>1)
      {
/*------ Double-weight-map mode */
          if (prefs.weight_type[1] != WEIGHT_NONE)
          {
/*-------- First: the "measurement" weights */
              wfield = newweight(prefs.wimage_name[1],field,prefs.weight_type[1],
                                 nok);
              wtype = prefs.weight_type[1];
              interpthresh = prefs.weight_thresh[1];
/*-------- Convert the interpolation threshold to variance units */
              weight_to_var(wfield, &interpthresh, 1);
              wfield->weight_thresh = interpthresh;
              if (prefs.interp_type[1] != INTERP_NONE)
                  init_interpolate(wfield,
                                   prefs.interp_xtimeout[1], prefs.interp_ytimeout[1]);
          }
/*------ The "detection" weights */
          if (prefs.weight_type[0] != WEIGHT_NONE)
          {
              interpthresh = prefs.weight_thresh[0];
              if (prefs.weight_type[0] == WEIGHT_FROMINTERP)
              {
                  dwfield=newweight(prefs.wimage_name[0],wfield,prefs.weight_type[0], 
                                    nok);
                  weight_to_var(wfield, &interpthresh, 1);
              }
              else
              {
                  dwfield = newweight(prefs.wimage_name[0], dfield?dfield:field,
                                      prefs.weight_type[0], nok);
                  weight_to_var(dwfield, &interpthresh, 1);
              }
              dwfield->weight_thresh = interpthresh;
              if (prefs.interp_type[0] != INTERP_NONE)
                  init_interpolate(dwfield,
                                   prefs.interp_xtimeout[0], prefs.interp_ytimeout[0]);
          }
      }
      else
      {
/*------ Single-weight-map mode */
          wfield = newweight(prefs.wimage_name[0], dfield?dfield:field,
                             prefs.weight_type[0], nok);
          wtype = prefs.weight_type[0];
          interpthresh = prefs.weight_thresh[0];
/*------ Convert the interpolation threshold to variance units */
          weight_to_var(wfield, &interpthresh, 1);
          wfield->weight_thresh = interpthresh;
          if (prefs.interp_type[0] != INTERP_NONE)
              init_interpolate(wfield,
                               prefs.interp_xtimeout[0], prefs.interp_ytimeout[0]);
      }
  }

/*-- Init the FLAG-images */
  for (i=0; i<prefs.nimaflag; i++)
  {
      pffield[i] = newfield(prefs.fimage_name[i], FLAG_FIELD, nok);
      if ((pffield[i]->width!=field->width)
          || (pffield[i]->height!=field->height))
          error(EXIT_FAILURE,
                "*Error*: Incompatible FLAG-map size in ", prefs.fimage_name[i]);
  }

/*-- Compute background maps for `standard' fields */
  QPRINTF(OUTPUT, dfield? "Measurement image:"
          : "Detection+Measurement image: ");
  makeback(field, wfield, prefs.wscale_flag[1]);
  QPRINTF(OUTPUT, (dfield || (dwfield&&dwfield->flags^INTERP_FIELD))? "(M)   "
          "Background: %-10g RMS: %-10g / Threshold: %-10g \n"
          : "(M+D) "
          "Background: %-10g RMS: %-10g / Threshold: %-10g \n",
          field->backmean, field->backsig, (field->flags & DETECT_FIELD)?
          field->dthresh: field->thresh);
  if (dfield)
  {
      QPRINTF(OUTPUT, "Detection image: ");
      makeback(dfield, dwfield? dwfield
                        : (prefs.weight_type[0] == WEIGHT_NONE?NULL:wfield),
                prefs.wscale_flag[0]);
      QPRINTF(OUTPUT, "(D)   "
              "Background: %-10g RMS: %-10g / Threshold: %-10g \n",
              dfield->backmean, dfield->backsig, dfield->dthresh);
  }
  else if (dwfield && dwfield->flags^INTERP_FIELD)
  {
      makeback(field, dwfield, prefs.wscale_flag[0]);
      QPRINTF(OUTPUT, "(D)   "
              "Background: %-10g RMS: %-10g / Threshold: %-10g \n",
              field->backmean, field->backsig, field->dthresh);
  }

/*-- For interpolated weight-maps, copy the background structure */
  if (dwfield && dwfield->flags&(INTERP_FIELD|BACKRMS_FIELD))
      copyback(dwfield->reffield, dwfield);
  if (wfield && wfield->flags&(INTERP_FIELD|BACKRMS_FIELD))
      copyback(wfield->reffield, wfield);

/*-- Prepare learn and/or associations */
  if (prefs.assoc_flag)
      init_assoc(field);                  /* initialize assoc tasks */

/*-- Update the CHECK-images */
  if (prefs.check_flag)
      for (i=0; i<MAXCHECK; i++)
        if ((check=prefs.check[i]))
          reinitcheck(field, check);

    if (!forcextflag && nok>1)
      {
      if (prefs.psf_flag)
        {
/*------ Read other PSF extensions */
        NFPRINTF(OUTPUT, "Reading PSF information");
        psf_end(thepsf, thepsfit);
        if (prefs.dpsf_flag)
          {
          psf_end(thedpsf, thedpsfit);
          thedpsf = psf_load(prefs.psf_name[0], nok);
          thepsf = psf_load(prefs.psf_name[1], nok);
          }
        else
          thepsf = psf_load(prefs.psf_name[0], nok); 
        }

#ifdef USE_MODEL
      if (prefs.prof_flag)
        {
/*------ Create profiles at full resolution */
        profit_end(theprofit);
        theprofit = profit_init(thepsf, modeltype);
        if (prefs.dprof_flag)
          {
          profit_end(thedprofit);
          thedprofit = profit_init(thedpsf, modeltype);
          }
        if (prefs.pattern_flag)
          {
          pattern = pattern_init(theprofit, prefs.pattern_type, npat0);
          pattern_end(pattern);
          }
        if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
          {
          profit_end(thepprofit);
          profit_end(theqprofit);
          thepprofit = profit_init(thepsf, MODEL_DIRAC);
          theqprofit = profit_init(thepsf, MODEL_EXPONENTIAL);
          }
        }
#endif
      }

/*-- Initialize PSF contexts and workspace */
  if (prefs.psf_flag)
  {
      psf_readcontext(thepsf, field);
      psf_init();
      if (prefs.dpsf_flag)
        {
        psf_readcontext(thepsf, dfield);
        psf_init();
        }
  }

/*-- Copy field structures to static ones (for catalog info) */
  if (dfield)
  {
      thefield1 = *field;
      thefield2 = *dfield;
  }
  else
      thefield1 = thefield2 = *field;

  if (wfield)
  {
      thewfield1 = *wfield;
      thewfield2 = dwfield? *dwfield: *wfield;
  }
  else if (dwfield)
      thewfield2 = *dwfield;

  reinitcat(field);

/*-- Start the extraction pipeline */
  NFPRINTF(OUTPUT, "Scanning image");
  scanimage(field, dfield, pffield, prefs.nimaflag, wfield, dwfield);

  NFPRINTF(OUTPUT, "Closing files");

/*-- Finish the current CHECK-image processing */
  if (prefs.check_flag)
      for (i=0; i<MAXCHECK; i++)
        if ((check=prefs.check[i]))
          reendcheck(field, check);

/*-- Final time measurements*/
    if (time(&thetime2)!=-1)
      {
      if (!strftime(thecat.ext_date, 12, "%d/%m/%Y", localtime(&thetime2)))
        error(EXIT_FAILURE, "*Internal Error*: Date string too long ","");
      if (!strftime(thecat.ext_time, 10, "%H:%M:%S", localtime(&thetime2)))
          error(EXIT_FAILURE, "*Internal Error*: Time/date string too long ","");
      thecat.ext_elapsed = difftime(thetime2, thetime1);
      
  }

  reendcat();

/* Update XML data */
    if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
      update_xml(&thecat, dfield? dfield:field, field,
	dwfield? dwfield:wfield, wfield);


/*-- Close ASSOC routines */
  end_assoc(field);

  for (i=0; i<prefs.nimaflag; i++)
      endfield(pffield[i]);
  endfield(field);
  if (dfield)
      endfield(dfield);
  if (wfield)
      endfield(wfield);
  if (dwfield)
      endfield(dwfield);

    QPRINTF(OUTPUT, "      Objects: detected %-8d / sextracted %-8d        \n\n",
	thecat.ndetect, thecat.ntotal);
/* End look around all images in an MEF */

  if (nok<0)
     error(EXIT_FAILURE, "Not enough valid FITS image extensions in ",
           prefs.image_name[0]);

  NFPRINTF(OUTPUT, "Closing files");

/* End CHECK-image processing */
  if (prefs.check_flag)
    for (i=0; i<MAXCHECK; i++)
      {
      if ((check=prefs.check[i]))
        endcheck(check);
      prefs.check[i] = NULL;
      }

  if (prefs.filter_flag)
    endfilter();

  if (prefs.somfit_flag)
    som_end(thesom);

  if (prefs.growth_flag)
    endgrowth();

#ifdef USE_MODEL
  if (prefs.prof_flag)
    {
    profit_end(theprofit);
    if (prefs.dprof_flag)
      profit_end(thedprofit);
    if (FLAG(obj2.prof_concentration)|FLAG(obj2.prof_concentration))
      {
      profit_end(thepprofit);
      profit_end(theqprofit);
      }
    fft_end();
    }
#endif

  if (prefs.psf_flag)
    psf_end(thepsf, thepsfit);

  if (prefs.dpsf_flag)
    psf_end(thedpsf, thedpsfit);

  if (FLAG(obj2.sprob))
    neurclose();

/* Processing end date and time */
  thetimet2 = time(NULL);
  tm = localtime(&thetimet2);
  sprintf(prefs.sdate_end,"%04d-%02d-%02d",
	tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
  sprintf(prefs.stime_end,"%02d:%02d:%02d",
	tm->tm_hour, tm->tm_min, tm->tm_sec);
  prefs.time_diff = counter_seconds() - dtime;

/* Write XML */
  if (prefs.xml_flag)
    write_xml(prefs.xml_name);

  endcat((char *)NULL);

  if (prefs.xml_flag || prefs.cat_type==ASCII_VO)
    end_xml();

/* Free FITS headers (now catalogues are closed). */
  if (field->fitsheadsize > 0) {
      free(field->fitshead);
  }

  return;
  }