Beispiel #1
0
sint32 treadn(int fd, uint8 *buf, uint32 nbytes, unsigned int timout)
{
    uint32      nleft;
    sint32     nread;
    nleft = nbytes;
    
    while (nleft > 0)
    {
        if ((nread = tread(fd, buf, nleft, timout)) < 0)
        {
            if (nleft == nbytes)
            {
                return(-1); /* error, return -1 */
            }
            else
            {
                break;      /* error, return amount read so far */
            }
        }
        else if (nread == 0)
        {
            break;          /* EOF */
        }
        
        nleft -= nread;
        buf += nread;
    }
    
    return (nbytes - nleft);      /* return >= 0 */
}
rt_public char *app_tread(size_t *size)
          		/* Filled in with size of read string */
{
	/* Read bytes from the "pipe" and put them into a new allocated buffer.
	 * Returns the address of that buffer or a null pointer in case of errors.
	 */
	return tread(app_sp, size);
}
Beispiel #3
0
// 经测试如果是[02 FF FE 91 0A 02 06 05 04 FF FD],可以解析;
// 如果是[02 FF FF FE 91 0A 02 06 05 04 FF FD],则不能解析。所以不能连续出现两个及以上的FF
// 从串口读数据
void BTM_Recv_BtmA(void)
{
    uint32 i = 0;
    sint32 num = 0;  // recv data number
    uint8 btmHead_1 = 0;
    uint8 btmHead_2 = 0;
    sint32 rst = 0;
    int j;
    // init req frame
    BTM_ReqFrameInit();
    // 从串口读取1字节数据
    num = tread(btmAFd, &btmHead_1, 1, BTM_UART_RECV_TIMEOUT);
    // DBG_INFO("[BTM] receive btmhead_1 = %02x\n", btmHead_1 );

    // if btmhead_1 correct, then continue recv head_2
    if ((num == 1) && (btmHead_1 == SINO_FRAME_HEAD_1))
    {
        num = tread(btmAFd, &btmHead_2, 1, BTM_UART_RECV_TIMEOUT);

        // receive sino btm correct header
        if ((num == 1) && (btmHead_2 == SINO_FRAME_HEAD_2))
        {
            for (i = 0; i < BTM_RECV_BUF_SIZE; i++)
            {
                tread(btmAFd, &btmARecvBuf[i], 1, BTM_UART_RECV_TIMEOUT);

                // receive sino btm correct footer
                if ((btmARecvBuf[i - 1] == SINO_FRAME_FOOT_1) && (btmARecvBuf[i] == SINO_FRAME_FOOT_2))
                {
                    //DBG_INFO("[BTM] btm receive req frame footer\n");
                    // parse vobc req, i-2 means not include packet header
                    BTM_ParseSinoReqPacket_BtmA(btmARecvBuf, btmAReqframeBuf, (i - 2));
                    //DBG_INFO("[BTM] btm req frame buf size %d\n", rst);
                    // unpack vobc req frame
                    BTM_UnpackRecvPacket_BtmA();
                    break;
                }
            }
        }
    }
    else
    {
        // if not receive req or timeout, then init req packet
        BTM_ReqFrameInit();
    }
}
task main()
{
	while(true){
		checkMode();
		drive();
		tread();
		wheel();
	}
}
Beispiel #5
0
BOOL CRarArchive::IsArchive()
//---------------------------
{
	struct MarkHeader MarkHead;
	int SFXLen,ArcType;
  
	SFXLen=ArcType=SolidType=LockedType=0;
	ArcFormat=0;

	if (tread(MarkHead.Mark,SIZEOF_MARKHEAD)!=SIZEOF_MARKHEAD) return FALSE;
	if (MarkHead.Mark[0]==0x52 && MarkHead.Mark[1]==0x45 &&
		MarkHead.Mark[2]==0x7e && MarkHead.Mark[3]==0x5e)
	{
		ArcFormat=OLD;
		tseek(0,SEEK_SET);
		ReadHeader(MAIN_HEAD);
		ArcType=(OldMhd.Flags & MHD_MULT_VOL) ? VOL : ARC;
	} else
	if (MarkHead.Mark[0]==0x52 && MarkHead.Mark[1]==0x61 &&
		MarkHead.Mark[2]==0x72 && MarkHead.Mark[3]==0x21 &&
		MarkHead.Mark[4]==0x1a && MarkHead.Mark[5]==0x07 &&
		MarkHead.Mark[6]==0x00)
	{
		ArcFormat=NEW;
		if (ReadHeader(MAIN_HEAD)!=SIZEOF_NEWMHD) return FALSE;
		ArcType = (NewMhd.Flags & MHD_MULT_VOL) ? VOL : ARC;
	}
	if (ArcFormat==OLD)
	{
		MainHeadSize=SIZEOF_OLDMHD;
		NewMhd.Flags=OldMhd.Flags & 0x3f;
		NewMhd.HeadSize=OldMhd.HeadSize;
	} else
	{
		MainHeadSize=SIZEOF_NEWMHD;
		if ((UWORD)~HeaderCRC!=NewMhd.HeadCRC)
		{
			// Warning
			return FALSE; //?
		}
	}
	if (NewMhd.Flags & MHD_SOLID) SolidType=1;
	if (NewMhd.Flags & MHD_LOCK) LockedType=1;
	return (ArcType) ? TRUE : FALSE;
}
Beispiel #6
0
/*
 * Read data from the printer, possibly increasing the buffer.
 * Returns offset of end of data in buffer or -1 on failure.
 *
 * LOCKING: none.
 */
ssize_t readmore(int sockfd, char **bpp, int off, int *bszp)
{
    ssize_t nr;
    char *bp = *bpp;
    int bsz = *bszp;

    if (off >= bsz) {
        bsz += IOBUFSZ;
        if ((bp = realloc(*bpp, bsz)) == NULL)
            log_sys("readmore: can't allocate bigger read buffer");
        *bszp = bsz;
        *bpp = bp;
    }
    if ((nr = tread(sockfd, &bp[off], bsz-off, 1)) < 0)
        return(off+nr);
    else
        return(-1);
}
Beispiel #7
0
int readreq()
{
    int r;
    if (skipsp()) goto readend;
    c = suck();
    if (c == EOF) goto readend;
    if (c == '\n') goto readend;
    if (c == '.') {
        while (1) {
            c = suck();
            if (c == EOF) break;
            if (c == '\n') break;
        }
        goto readend;
    }
    r = c << 9;
    c = suck();
    if (c != EOF) {
        if (c != '\n') {
            r = r | c;
        }
    }

    if (r==0157150) c = tread(ohead);	/* oh */
    if (r==0163160) {			/* sp */
        o_sp=nread();
        writebreak();
    }
    if (r==0164141) do_ta();		/* ta */
    if (r==0165154) o_ul=nread();		/* ul */

    while (1) {
        if (c == EOF) break;
        if (c == '\n') break;
        c= suck();
    }
readend:
    if (c != EOF)
        return(1);
    else
        return(0);
}
Beispiel #8
0
static void 
to_data_new(struct tor_conn *tc)
{
	int from, to, amnt;
	char *buf;

	from = tc->from;
	to   = tc->to;
	while (1) {
		int ret;
		cbuf_t cb;

		if (!(buf = cbuf_alloc(BUFF_SZ, &cb))) BUG();
		amnt = tread(cos_spd_id(), to, cb, BUFF_SZ-1);
		if (0 == amnt) break;
		else if (-EPIPE == amnt) {
			goto close;
		} else if (amnt < 0) {
			printc("read from fd %d produced %d.\n", from, amnt);
			BUG();
		}
		assert(amnt <= BUFF_SZ);
		if (amnt != (ret = from_twrite(cos_spd_id(), from, cb, amnt))) {
			printc("conn_mgr: write failed w/ %d of %d on fd %d\n", 
			       ret, amnt, to);
			goto close;
		}
		cbuf_free(buf);
	}
done:
	cbuf_free(buf);
	return;
close:
	mapping_remove(from, to, tc->feid, tc->teid);
	from_trelease(cos_spd_id(), from);
	trelease(cos_spd_id(), to);
	assert(tc->feid && tc->teid);
	evt_put(tc->feid);
	evt_put(tc->teid);
	goto done;
}
Beispiel #9
0
/*
 * "Timed" read - timout specifies the number of seconds to wait
 * per read call before giving up, but read exactly nbytes bytes.
 * Returns number of bytes read or -1 on error.
 *
 * LOCKING: none.
 */
ssize_t
treadn(int fd, void *buf, size_t nbytes, unsigned int timout)
{
	size_t	nleft;
	ssize_t	nread;

	nleft = nbytes;
	while (nleft > 0) {
		if ((nread = tread(fd, buf, nleft, timout)) < 0) {
			if (nleft == nbytes)
				return(-1); /* error, return -1 */
			else
				break;      /* error, return amount read so far */
		} else if (nread == 0) {
			break;          /* EOF */
		}
		nleft -= nread;
		buf += nread;
	}
	return(nbytes - nleft);      /* return >= 0 */
}
Beispiel #10
0
/*
 * The TTY might be turning \n into \r.  For now, just
 * pretend it's working.  The 8-bit test will fail with a 
 * good error message.
 */
static char*
rdln(Fd *fd)
{
	int i=0;
	static char buf[BUFSZ+1];

	do{
		if(tread(fd, &buf[i], 1) <= 0)
			break;
		if(buf[i] == '\r')
			buf[i] = '\n';
		if(buf[i++] == '\n')
			break;
	}while(i < BUFSZ);

	if(i == 0)
		return nil;

	buf[i] = '\0';
	return buf;
}
Beispiel #11
0
/*
 * Read and parse the response from the printer.  Return 1
 * if the request was successful, and 0 otherwise.
 *
 * LOCKING: none.
 */
int
printer_status(int sfd, struct job *jp)
{
	int				i, success, code, len, found, bufsz, datsz;
	int32_t			jobid;
	ssize_t			nr;
	char			*bp, *cp, *statcode, *reason, *contentlen;
	struct ipp_hdr	*hp;

	/*
	 * Read the HTTP header followed by the IPP response header.
	 * They can be returned in multiple read attempts.  Use the
	 * Content-Length specifier to determine how much to read.
	 */
	success = 0;
	bufsz = IOBUFSZ;
	if ((bp = malloc(IOBUFSZ)) == NULL)
		log_sys("printer_status: can't allocate read buffer");

	while ((nr = tread(sfd, bp, bufsz, 5)) > 0) {
		/*
		 * Find the status.  Response starts with "HTTP/x.y"
		 * so we can skip the first 8 characters.
		 */
		cp = bp + 8;
		datsz = nr;
		while (isspace((int)*cp))
			cp++;
		statcode = cp;
		while (isdigit((int)*cp))
			cp++;
		if (cp == statcode) { /* Bad format; log it and move on */
			log_msg(bp);
		} else {
			*cp++ = '\0';
			reason = cp;
			while (*cp != '\r' && *cp != '\n')
				cp++;
			*cp = '\0';
			code = atoi(statcode);
			if (HTTP_INFO(code))
				continue;
			if (!HTTP_SUCCESS(code)) { /* probable error: log it */
				bp[datsz] = '\0';
				log_msg("error: %s", reason);
				break;
			}

			/*
			 * HTTP request was okay, but still need to check
			 * IPP status.  Search for the Content-Length.
			 */
			i = cp - bp;
			for (;;) {
				while (*cp != 'C' && *cp != 'c' && i < datsz) {
					cp++;
					i++;
				}
				if (i >= datsz) {	/* get more header */
					if ((nr = readmore(sfd, &bp, i, &bufsz)) < 0) {
						goto out;
					} else {
						cp = &bp[i];
						datsz += nr;
					}
				}

				if (strncasecmp(cp, "Content-Length:", 15) == 0) {
					cp += 15;
					while (isspace((int)*cp))
						cp++;
					contentlen = cp;
					while (isdigit((int)*cp))
						cp++;
					*cp++ = '\0';
					i = cp - bp;
					len = atoi(contentlen);
					break;
				} else {
					cp++;
					i++;
				}
			}
			if (i >= datsz) {	/* get more header */
				if ((nr = readmore(sfd, &bp, i, &bufsz)) < 0) {
					goto out;
				} else {
					cp = &bp[i];
					datsz += nr;
				}
			}

			found = 0;
			while (!found) {  /* look for end of HTTP header */
				while (i < datsz - 2) {
					if (*cp == '\n' && *(cp + 1) == '\r' &&
					  *(cp + 2) == '\n') {
						found = 1;
						cp += 3;
						i += 3;
						break;
					}
					cp++;
					i++;
				}
				if (i >= datsz) {	/* get more header */
					if ((nr = readmore(sfd, &bp, i, &bufsz)) < 0) {
						goto out;
					} else {
						cp = &bp[i];
						datsz += nr;
					}
				}
			}

			if (datsz - i < len) {	/* get more header */
				if ((nr = readmore(sfd, &bp, i, &bufsz)) < 0) {
					goto out;
				} else {
					cp = &bp[i];
					datsz += nr;
				}
			}

			hp = (struct ipp_hdr *)cp;
			i = ntohs(hp->status);
			jobid = ntohl(hp->request_id);

			if (jobid != jp->jobid) {
				/*
				 * Different jobs.  Ignore it.
				 */
				log_msg("jobid %d status code %d", jobid, i);
				break;
			}

			if (STATCLASS_OK(i))
				success = 1;
			break;
		}
	}

out:
	free(bp);
	if (nr < 0) {
		log_msg("jobid %d: error reading printer response: %s",
		  jobid, strerror(errno));
	}
	return(success);
}
Beispiel #12
0
/*
 * Accept a print job from a client.
 *
 * LOCKING: none.
 */
void *
client_thread(void *arg)
{
	int					n, fd, sockfd, nr, nw, first;
	int32_t				jobid;
	pthread_t			tid;
	struct printreq		req;
	struct printresp	res;
	char				name[FILENMSZ];
	char				buf[IOBUFSZ];

	tid = pthread_self();
	pthread_cleanup_push(client_cleanup, (void *)((long)tid));
	sockfd = (long)arg;
	add_worker(tid, sockfd);

	/*
	 * Read the request header.
	 */
	if ((n = treadn(sockfd, &req, sizeof(struct printreq), 10)) !=
	  sizeof(struct printreq)) {
		res.jobid = 0;
		if (n < 0)
			res.retcode = htonl(errno);
		else
			res.retcode = htonl(EIO);
		strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
		writen(sockfd, &res, sizeof(struct printresp));
		pthread_exit((void *)1);
	}
	req.size = ntohl(req.size);
	req.flags = ntohl(req.flags);

	/*
	 * Create the data file.
	 */
	jobid = get_newjobno();
	sprintf(name, "%s/%s/%d", SPOOLDIR, DATADIR, jobid);
	fd = creat(name, FILEPERM);
	if (fd < 0) {
		res.jobid = 0;
		res.retcode = htonl(errno);
		log_msg("client_thread: can't create %s: %s", name,
		  strerror(res.retcode));
		strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
		writen(sockfd, &res, sizeof(struct printresp));
		pthread_exit((void *)1);
	}

	/*
	 * Read the file and store it in the spool directory.
	 * Try to figure out if the file is a PostScript file
	 * or a plain text file.
	 */
	first = 1;
	while ((nr = tread(sockfd, buf, IOBUFSZ, 20)) > 0) {
		if (first) {
			first = 0;
			if (strncmp(buf, "%!PS", 4) != 0)
				req.flags |= PR_TEXT;
		}
		nw = write(fd, buf, nr);
		if (nw != nr) {
			res.jobid = 0;
			if (nw < 0)
				res.retcode = htonl(errno);
			else
				res.retcode = htonl(EIO);
			log_msg("client_thread: can't write %s: %s", name,
			  strerror(res.retcode));
			close(fd);
			strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
			writen(sockfd, &res, sizeof(struct printresp));
			unlink(name);
			pthread_exit((void *)1);
		}
	}
	close(fd);

	/*
	 * Create the control file.  Then write the
	 * print request information to the control
	 * file.
	 */
	sprintf(name, "%s/%s/%d", SPOOLDIR, REQDIR, jobid);
	fd = creat(name, FILEPERM);
	if (fd < 0) {
		res.jobid = 0;
		res.retcode = htonl(errno);
		log_msg("client_thread: can't create %s: %s", name,
		  strerror(res.retcode));
		strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
		writen(sockfd, &res, sizeof(struct printresp));
		sprintf(name, "%s/%s/%d", SPOOLDIR, DATADIR, jobid);
		unlink(name);
		pthread_exit((void *)1);
	}
	nw = write(fd, &req, sizeof(struct printreq));
	if (nw != sizeof(struct printreq)) {
		res.jobid = 0;
		if (nw < 0)
			res.retcode = htonl(errno);
		else
			res.retcode = htonl(EIO);
		log_msg("client_thread: can't write %s: %s", name,
		  strerror(res.retcode));
		close(fd);
		strncpy(res.msg, strerror(res.retcode), MSGLEN_MAX);
		writen(sockfd, &res, sizeof(struct printresp));
		unlink(name);
		sprintf(name, "%s/%s/%d", SPOOLDIR, DATADIR, jobid);
		unlink(name);
		pthread_exit((void *)1);
	}
	close(fd);

	/*
	 * Send response to client.
	 */
	res.retcode = 0;
	res.jobid = htonl(jobid);
	sprintf(res.msg, "request ID %d", jobid);
	writen(sockfd, &res, sizeof(struct printresp));

	/*
	 * Notify the printer thread, clean up, and exit.
	 */
	log_msg("adding job %d to queue", jobid);
	add_job(&req, jobid);
	pthread_cleanup_pop(1);
	return((void *)0);
}
Beispiel #13
0
static void
service(int cfd, int sfd, int dfd)
{
	Fcall	f;
	int	r;
	Fid*	fp;

	fidpool = allocfidpool(nop);
	for(;;){
		fp = nil;
		r = getfcall(cfd, &f);
		if (r <= 0){
			fprint(dfd, "trfs: getfcall %r\n");
			break;
		}
		if(verbose)
			fprint(dfd , "c→s %F\n", &f);
		switch(f.type){
		case Tclunk:
		case Tremove:
			// BUG in lib9p? removefid leaks fid.
			// is that what it should do?
			fp = lookupfid(fidpool, f.fid);
			if (fp != nil){
				removefid(fidpool, f.fid);
				closefid(fp);
				closefid(fp);
				fp = nil;
			}
			break;
		case Tcreate:
			tcreate(&f);
			// and also...
		case Topen:
			fp = allocfid(fidpool, f.fid);
			fp->aux = 0;
			break;
		case Tread:
			tread(&f);
			break;
		case Twalk:
			twalk(&f);
			break;
		case Twstat:
			twstat(&f);
			break;
		}
		if(verbose && debug)
			fprint(dfd , "c→s %F\n", &f);
		if (putfcall(sfd, &f) < 0)
			fprint(dfd , "can't putfcall: %r\n");
		

		r = getfcall(sfd, &f);
		if (r <= 0){
			fprint(dfd, "trfs: 2nd getfcall %r\n");
			break;
		}
		if (verbose)
			fprint(dfd, "c←s %F\n", &f);
		switch(f.type){
		case Ropen:
		case Rcreate:
			fp->qid = f.qid;
			break;
		case Rread:
			rread(&f);
			break;
		case Rstat:
			rstat(&f);
			break;
		}
		if(verbose && debug)
			fprint(dfd , "c←s %F\n", &f);
		if (putfcall(cfd, &f) < 0)
			fprint(dfd , "can't 2n dputfcall: %r\n");
		if (fp != nil)
			closefid(fp);
	}
}
Beispiel #14
0
struct mFitExecReturn *mFitExec(char *tblfile, char *fitfile, char *diffdir, int levelOnly, int debugin)
{
   int    stat, ncols, count, failed;
   int    warning, missing;

   int    icntr1;
   int    icntr2;
   int    idiffname;

   int    cntr1;
   int    cntr2;

   char   diffname[MAXSTR];

   double a;
   double b;
   double c;
   double crpix1;
   double crpix2;
   int    xmin;
   int    xmax;
   int    ymin;
   int    ymax;
   double xcenter;
   double ycenter;
   double npixel;
   double rms;
   double boxx;
   double boxy;
   double boxwidth;
   double boxheight;
   double boxangle;

   FILE   *fout;


   struct mFitExecReturn  *returnStruct;
   struct mFitplaneReturn *fitplane;
   
   returnStruct = (struct mFitExecReturn *)malloc(sizeof(struct mFitExecReturn));
   
   memset((void *)returnStruct, 0, sizeof(returnStruct));

   returnStruct->status = 1;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   mFitExec_debug = debugin;

   fout = fopen(fitfile, "w+");

   if(fout == (FILE *)NULL)
   {
      strcpy(returnStruct->msg, "Can't open output file.");
      return returnStruct;
   }


   /***************************************/ 
   /* Open the difference list table file */
   /***************************************/ 

   ncols = topen(tblfile);

   if(ncols <= 0)
   {
      sprintf(returnStruct->msg, "Invalid diffs metadata file: %s", tblfile);
      fclose(fout);
      return returnStruct;
   }

   icntr1    = tcol( "cntr1");
   icntr2    = tcol( "cntr2");
   idiffname = tcol( "diff");

   if(icntr1    < 0
   || icntr2    < 0
   || idiffname < 0)
   {
      strcpy(returnStruct->msg, "Need columns: cntr1 cntr2 diff");
      fclose(fout);
      return returnStruct;
   }


   /***************************************/ 
   /* Read the records and call mFitplane */
   /***************************************/ 

   count   = 0;
   failed  = 0;
   warning = 0;
   missing = 0;

   fprintf(fout, "|%9s|%9s|%16s|%16s|%16s|%14s|%14s|%10s|%10s|%10s|%10s|%13s|%13s|%13s|%16s|%16s|%16s|%16s|%16s|%16s|\n",
      "plus", "minus", "a", "b", "c", "crpix1", "crpix2", "xmin", "xmax", "ymin", "ymax", "xcenter", "ycenter", "npixel", "rms", "boxx", "boxy", "boxwidth", "boxheight", "boxang");
   fflush(fout);

   while(1)
   {
      stat = tread();

      if(stat < 0)
         break;

      cntr1 = atoi(tval(icntr1));
      cntr2 = atoi(tval(icntr2));

      strcpy(diffname, montage_filePath(diffdir, tval(idiffname)));

      if(montage_checkFile(diffname))
      {
         ++count;
         ++missing;
         continue;
      }

      fitplane = mFitplane(diffname, levelOnly, 0., 0);

      if(mFitExec_debug)
      {
         printf("mFitplane(%s) -> [%s]\n", diffname, fitplane->msg);
         fflush(stdout);
      }

      if(fitplane->status)
         ++failed;
      else
      {
         a         = fitplane->a;
         b         = fitplane->b;
         c         = fitplane->c;
         crpix1    = fitplane->crpix1;
         crpix2    = fitplane->crpix2;
         xmin      = fitplane->xmin;
         xmax      = fitplane->xmax;
         ymin      = fitplane->ymin;
         ymax      = fitplane->ymax;
         xcenter   = fitplane->xcenter;
         ycenter   = fitplane->ycenter;
         npixel    = fitplane->npixel;
         rms       = fitplane->rms;
         boxx      = fitplane->boxx;
         boxy      = fitplane->boxy;
         boxwidth  = fitplane->boxwidth;
         boxheight = fitplane->boxheight;
         boxangle  = fitplane->boxang;

         fprintf(fout, " %9d %9d %16.5e %16.5e %16.5e %14.2f %14.2f %10d %10d %10d %10d %13.2f %13.2f %13.0f %16.5e %16.1f %16.1f %16.1f %16.1f %16.1f \n",
               cntr1, cntr2, a, b, c, crpix1, crpix2, xmin, xmax, ymin, ymax,
               xcenter, ycenter, npixel, rms, boxx, boxy, boxwidth, boxheight, boxangle);
         fflush(fout);
      }

      free(fitplane);

      ++count;
   }


   /* Finish up */

   returnStruct->status = 0;

   sprintf(returnStruct->msg,  "count=%d, failed=%d, warning=%d, missing=%d",
      count, failed, warning, missing);

   sprintf(returnStruct->json, "{\"count\":%d, \"failed\":%d, \"warning\":%d, \"missing\":%d}",
      count, failed, warning, missing);

   returnStruct->count   = count;
   returnStruct->failed  = failed;
   returnStruct->warning = warning;
   returnStruct->missing = missing;

   return returnStruct;
}
Beispiel #15
0
int main(int argc, char **argv)
{
   int       i, j, l, m, c, count, ismag, ncol;
   int       dl, dm, width, haveFlux, isImg, csys;
   int       side, ibegin, iend, nstep, useCenter;
   int       racol, deccol, fluxcol;
   int       ra1col, dec1col;
   int       ra2col, dec2col;
   int       ra3col, dec3col;
   int       ra4col, dec4col;
   long      fpixel, nelements;
   double    rac, decc;
   double    ra[4], dec[4];
   double    x,  y,  z;
   double    x0, y0, z0;
   double    x1, y1, z1;
   double    oxpix, oypix, equinox;
   int       offscl;
   double    ilon;
   double    ilat;
   double    pixscale, len, sideLength, dtr;
   double    offset;

   double    xn, yn, zn;
   double    ran, decn;
   double    sina, cosa;
   double    sind, cosd;

   double    a11, a12, a13;
   double    a21, a22, a23;
   double    a31, a32, a33;

   double    x0p, y0p, z0p;
   double    x1p, y1p, z1p;

   double    lon0, lon1;
   double    xp, yp;
   double    lon;

   double    pixel_value;

   double    weights[5][5];

   double    weights3[5][5] = {{0.0, 0.0, 0.0, 0.0, 0.0},
                               {0.0, 0.1, 0.2, 0.1, 0.0},
                               {0.0, 0.2, 1.0, 0.2, 0.0},
                               {0.0, 0.1, 0.2, 0.1, 0.0},
                               {0.0, 0.0, 0.0, 0.0, 0.0}};

   double    weights5[5][5] = {{0.0, 0.1, 0.2, 0.1, 0.0},
                               {0.1, 0.3, 0.5, 0.3, 0.1},
                               {0.2, 0.5, 1.0, 0.5, 0.2},
                               {0.1, 0.3, 0.5, 0.3, 0.1},
                               {0.0, 0.1, 0.2, 0.1, 0.0}};

   double  **data;

   int       status = 0;

   char      input_file   [MAXSTR];
   char      colname      [MAXSTR];
   char      output_file  [MAXSTR];
   char      template_file[MAXSTR];

   int       bitpix = DOUBLE_IMG; 
   long      naxis  = 2;  

   double    sumweights;
   double    refmag;

   dtr = atan(1.0)/45.;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   ismag  = 0;
   opterr = 0;

   useCenter = 0;

   strcpy(colname, "");

   while ((c = getopt(argc, argv, "pm:d:w:c:")) != EOF) 
   {
      switch (c) 
      {
         case 'm':
	    ismag = 1;
	    refmag = atof(optarg);
            break;

         case 'd':
            debug = debugCheck(optarg);
            break;

         case 'w':
	    width  = atoi(optarg);
            break;

         case 'c':
            strcpy(colname, optarg);
            break;

         case 'p':
            useCenter = 1;
            break;

         default:
	    printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-c column][-m refmag][-d level][-w size] in.tbl out.fits hdr.template\"]\n", argv[0]);
            exit(1);
            break;
      }
   }

   if (argc - optind < 3) 
   {
      printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-c column][-m refmag][-d level][-w size] in.tbl out.fits hdr.template\"]\n", argv[0]);
      exit(1);
   }

   strcpy(input_file,    argv[optind]);
   strcpy(output_file,   argv[optind+1]);
   strcpy(template_file, argv[optind+2]);

   if(debug >= 1)
   {
      printf("input_file    = [%s]\n", input_file);
      printf("colname       = [%s]\n", colname);
      printf("output_file   = [%s]\n", output_file);
      printf("template_file = [%s]\n", template_file);
      printf("width         = %d\n",   width);
      printf("ismag         = %d\n",   ismag);
      fflush(stdout);
   }


   /********************************************/
   /* Set the weights for spreading the points */
   /********************************************/

   sumweights = 0.;

   for(i=0; i<5; ++i)
   {
      for(j=0; j<5; ++j)
      {
	 if(width == 3)
	    sumweights += weights3[i][j];

	 else if(width == 5)
	    sumweights += weights5[i][j];
      }
   }

   for(i=0; i<5; ++i)
   {
      for(j=0; j<5; ++j)
      {
	 if(width == 3)
	    weights[i][j] = weights3[i][j]/sumweights;

	 else if(width == 5)
	    weights[i][j] = weights5[i][j]/sumweights;

	 else 
	    weights[i][j] = 0.;
      }
   }

   if(width != 3 && width != 5)
      weights[2][2] = 1.;




   /************************************************/ 
   /* Open the table file and find the data column */ 
   /************************************************/ 

   ncol = topen(input_file);

   if(ncol <= 0)
   {
      printf("[struct stat=\"ERROR\", msg=\"Can't open input table %s\"]\n", input_file);
      exit(0);
   }

   racol   = tcol( "ra");
   deccol  = tcol("dec");

    ra1col = tcol( "ra1");
   dec1col = tcol("dec1");
    ra2col = tcol( "ra2");
   dec2col = tcol("dec2");
    ra3col = tcol( "ra3");
   dec3col = tcol("dec3");
    ra4col = tcol( "ra4");
   dec4col = tcol("dec4");

   haveFlux = 1;
   if(strlen(colname) == 0)
      haveFlux = 0;
   else
      fluxcol = tcol(colname);

   isImg = 1;

   if(ra1col < 0 || dec1col < 0
   || ra2col < 0 || dec2col < 0
   || ra3col < 0 || dec3col < 0
   || ra4col < 0 || dec4col < 0)
      isImg = 0;

   if(useCenter)
      isImg = 0;

   if(!isImg)
   {
      if(racol <  0)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Can't find column 'ra'\"]\n");
	 exit(0);
      }

      if(deccol <  0)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Can't find column 'dec'\"]\n");
	 exit(0);
      }
   }

   if(haveFlux && fluxcol <  0)
   {
      printf("[struct stat=\"ERROR\", msg=\"Can't find column '%s'\"]\n", colname);
      exit(0);
   }


   /*************************************************/ 
   /* Process the output header template to get the */ 
   /* image size, coordinate system and projection  */ 
   /*************************************************/ 

   readTemplate(template_file);

   pixscale = fabs(output.wcs->xinc);

   if(fabs(output.wcs->yinc) > pixscale)
      pixscale = fabs(output.wcs->yinc);

   csys = EQUJ;

   if(strncmp(output.wcs->c1type, "RA",   2) == 0)
      csys = EQUJ;
   if(strncmp(output.wcs->c1type, "GLON", 4) == 0)
      csys = GAL;
   if(strncmp(output.wcs->c1type, "ELON", 4) == 0)
      csys = ECLJ;

   equinox = output.wcs->equinox;

   if(debug >= 1)
   {
      printf("output.naxes[0] =  %ld\n", output.naxes[0]);
      printf("output.naxes[1] =  %ld\n", output.naxes[1]);
      printf("output.sys      =  %d\n",  output.sys);
      printf("output.epoch    =  %-g\n", output.epoch);
      printf("output proj     =  %s\n",  output.wcs->ptype);
      printf("output crval[0] =  %-g\n", output.wcs->crval[0]);
      printf("output crval[1] =  %-g\n", output.wcs->crval[1]);
      printf("output crpix[0] =  %-g\n", output.wcs->crpix[0]);
      printf("output crpix[1] =  %-g\n", output.wcs->crpix[1]);
      printf("output cdelt[0] =  %-g\n", output.wcs->cdelt[0]);
      printf("output cdelt[1] =  %-g\n", output.wcs->cdelt[1]);

      fflush(stdout);
   }


   /***********************************************/ 
   /* Allocate memory for the output image pixels */ 
   /***********************************************/ 

   data = (double **)malloc(output.naxes[1] * sizeof(double *));

   data[0] = (double *)malloc(output.naxes[0] * output.naxes[1] * sizeof(double));

   if(debug >= 1)
   {
      printf("%ld bytes allocated for image pixels\n", 
	 output.naxes[0] * output.naxes[1] * sizeof(double));
      fflush(stdout);
   }


   /**********************************************************/
   /* Initialize pointers to the start of each row of pixels */
   /**********************************************************/

   for(i=1; i<output.naxes[1]; i++)
      data[i] = data[i-1] + output.naxes[0];

   if(debug >= 1)
   {
      printf("pixel line pointers populated\n"); 
      fflush(stdout);
   }

   for (j=0; j<output.naxes[1]; ++j)
   {
      for (i=0; i<output.naxes[0]; ++i)
      {
	 data[j][i] = 0.;
      }
   }


   /************************/
   /* Create the FITS file */
   /************************/

   remove(output_file);               

   if(fits_create_file(&output.fptr, output_file, &status)) 
      printFitsError(status);           


   /*********************************************************/
   /* Create the FITS image.  All the required keywords are */
   /* handled automatically.                                */
   /*********************************************************/

   if (fits_create_img(output.fptr, bitpix, naxis, output.naxes, &status))
      printFitsError(status);          

   if(debug >= 1)
   {
      printf("FITS image created (not yet populated)\n"); 
      fflush(stdout);
   }


   /*****************************/
   /* Loop over the input files */
   /*****************************/

   time(&currtime);
   start = currtime;


   /*******************/
   /* For each source */
   /*******************/

   count = 0;

   while(tread() >= 0)
   {
      ++count;

      if(isImg)
      {
	 if(debug && count/1000*1000 == count)
	 {
	    printf("%9d image outlines processed\n", count);
	    fflush(stdout);
	 }

	 ra [0] = atof(tval( ra1col));
	 dec[0] = atof(tval(dec1col));
	 ra [1] = atof(tval( ra2col));
	 dec[1] = atof(tval(dec2col));
	 ra [2] = atof(tval( ra3col));
	 dec[2] = atof(tval(dec3col));
	 ra [3] = atof(tval( ra4col));
	 dec[3] = atof(tval(dec4col));

	 for(side=0; side<4; ++side)
	 {
	    ibegin = side;
	    iend   = (side+1)%4;

	    x0 = cos(ra[ibegin]*dtr) * cos(dec[ibegin]*dtr);
	    y0 = sin(ra[ibegin]*dtr) * cos(dec[ibegin]*dtr);
	    z0 = sin(dec[ibegin]*dtr);

	    x1 = cos(ra[iend]*dtr) * cos(dec[iend]*dtr);
	    y1 = sin(ra[iend]*dtr) * cos(dec[iend]*dtr);
	    z1 = sin(dec[iend]*dtr);

	    xn = y0*z1 - z0*y1;
	    yn = z0*x1 - x0*z1;
	    zn = x0*y1 - y0*x1;

	    len = sqrt(xn*xn + yn*yn + zn*zn);

	    xn = xn / len;
	    yn = yn / len;
	    zn = zn / len;

	    ran  = atan2(yn, xn);
	    decn = asin(zn);

	    sina = sin(ran);
	    cosa = cos(ran);

	    sind = sin(decn);
	    cosd = cos(decn);

	    a11 =  cosa*sind;
	    a12 =  sina*sind;
	    a13 = -cosd;
	    a21 = -sina;
	    a22 =  cosa;
	    a23 =  0.;
	    a31 =  cosa*cosd;
	    a32 =  sina*cosd;
	    a33 =  sind;

	    x0p =  a11*x0 + a12*y0 + a13*z0;
	    y0p =  a21*x0 + a22*y0 + a23*z0;
	    z0p =  a31*x0 + a32*y0 + a33*z0;

	    x1p =  a11*x1 + a12*y1 + a13*z1;
	    y1p =  a21*x1 + a22*y1 + a23*z1;
	    z1p =  a31*x1 + a32*y1 + a33*z1;

	    lon0 = atan2(y0p, x0p);
	    lon1 = atan2(y1p, x1p);

	    if(fabs(lon1-lon0)/dtr > 180.)
	    {
	       if(lon0 < 0.) lon0 += 360.*dtr;
	       if(lon1 < 0.) lon1 += 360.*dtr;
	    }

	    sideLength = acos(x0*x1 + y0*y1 + z0*z1) / dtr;

            offset = pixscale/2.*dtr;
	    if(lon0 > lon1)
	       offset = -offset;

	    nstep = (lon1 - lon0)/offset;

	    lon = lon0;
	    for(i=0; i<nstep; ++i)
	    {
	       lon += offset;

	       xp = cos(lon);
	       yp = sin(lon);

	       x = a11*xp + a21*yp;
	       y = a12*xp + a22*yp;
	       z = a13*xp + a23*yp;

	       rac  = atan2(y,x)/dtr;
	       decc = asin(z)/dtr;

	       convertCoordinates (EQUJ,   2000.,    rac,   decc,
				   csys, equinox, &ilon, &ilat, 0.);

               offscl = 0;

	       wcs2pix(output.wcs, ilon, ilat, &oxpix, &oypix, &offscl);

               fixxy(&oxpix, &oypix, &offscl);

	       if(haveFlux)
		  pixel_value = atof(tval(fluxcol));
	       else
		  pixel_value = 1;

	       l = (int)(oxpix + 0.5) - 1;
	       m = (int)(oypix + 0.5) - 1;

	       if(!offscl)
		  data[m][l] = pixel_value;
	    }
	 }
      }
      else
      {
	 if(debug && count/1000*1000 == count)
	 {
	    printf("%9d sources processed\n", count);
	    fflush(stdout);
	 }

	 rac  = atof(tval(racol));
	 decc = atof(tval(deccol));

	 convertCoordinates (EQUJ,   2000.,    rac,   decc,
			     csys, equinox, &ilon, &ilat, 0.);

	 if(haveFlux)
	    pixel_value = atof(tval(fluxcol));
	 else
	    pixel_value = 1;

	 if(ismag)
	    pixel_value = pow(10., 0.4 * (refmag - pixel_value));

	 wcs2pix(output.wcs, ilon, ilat, &oxpix, &oypix, &offscl);

	 if(pixel_value < 1.e10)
	 {
	    if(debug >= 3)
	    {
	       printf(" value = %11.3e at coord = (%12.8f,%12.8f)", pixel_value, ilon, ilat);

	       if(offscl)
	       {
		  printf(" -> opix = (%7.1f,%7.1f) OFF SCALE\n",
		     oxpix, oypix);
		  fflush(stdout);
	       }
	       else
	       {
		  printf(" -> opix = (%7.1f,%7.1f)\n",
		     oxpix, oypix);
		  fflush(stdout);
	       }
	    }
	    else if(pixel_value > 1000000.)
	    {
	       printf(" value = %11.3e at coord = (%12.8f,%12.8f)", pixel_value, ilon, ilat);

	       if(offscl)
	       {
		  printf(" -> opix = (%7.1f,%7.1f) OFF SCALE\n",
		     oxpix, oypix);
		  fflush(stdout);
	       }
	       else
	       {
		  printf(" -> opix = (%7.1f,%7.1f)\n",
		     oxpix, oypix);
		  fflush(stdout);
	       }
	    }

	    if(!offscl)
	    {
	       l = (int)(oxpix + 0.5) - 1;
	       m = (int)(oypix + 0.5) - 1;

	       if(l < 0 || m < 0 || l >= output.naxes[0] || m >= output.naxes[1])
	       {
		  /*
		  printf("ERROR: l=%d, m=%d\n", l, m);
		  fflush(stdout);
		  */
	       }

	       else
	       {
		  for(dl=-2; dl<=2; ++dl)
		  {
		     if(l+dl < 0 || l+dl>= output.naxes[0])
			continue;

		     for(dm=-2; dm<=2; ++dm)
		     {
			if(m+dm < 0 || m+dm>= output.naxes[1])
			   continue;

			data[m+dm][l+dl] += weights[dm+2][dl+2] * pixel_value;
		     }
		  }
	       }
	    }
	 }
      }
   }


   /************************/
   /* Write the image data */
   /************************/

   fpixel    = 1;
   nelements = output.naxes[0] * output.naxes[1];

   if (fits_write_img(output.fptr, TDOUBLE, fpixel, nelements, data[0], &status))
      printFitsError(status);

   if(debug >= 1)
   {
      printf("Data array written to FITS image\n"); 
      fflush(stdout);
   }


   /*************************************/
   /* Add keywords from a template file */
   /*************************************/

   if(fits_write_key_template(output.fptr, template_file, &status))
      printFitsError(status);           

   if(debug >= 1)
   {
      printf("Template keywords written to FITS image\n"); 
      fflush(stdout);
   }


   /***********************/
   /* Close the FITS file */
   /***********************/

   if(fits_close_file(output.fptr, &status))
   printFitsError(status);           

   if(debug >= 1)
   {
      printf("FITS image finalized\n"); 
      fflush(stdout);
   }


   time(&currtime);

   printf("[struct stat=\"OK\", time=%d]\n", 
      (int)(currtime - start));
   fflush(stdout);

   exit(0);
}
Beispiel #16
0
int main(int argc, char **argv)
{
   int    ch, stat, ncols, count, failed, missing, warning;

   int    icntr1;
   int    icntr2;
   int    istatfile;

   int    cntr1;
   int    cntr2;

   char   statfile[MAXSTR];

   char   tblfile [MAXSTR];
   char   fitfile [MAXSTR];
   char   statdir [MAXSTR];

   char   line    [MAXSTR];
   char   msg     [MAXSTR];
   char   val     [MAXSTR];
   char   status  [32];

   double a;
   double b;
   double c;
   double crpix1;
   double crpix2;
   int    xmin;
   int    xmax;
   int    ymin;
   int    ymax;
   double xcenter;
   double ycenter;
   double npixel;
   double rms;
   double boxx;
   double boxy;
   double boxwidth;
   double boxheight;
   double boxangle;

   FILE   *fstat;
   FILE   *fout;

   SVC *svc=NULL;



   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   debug = 0;

   opterr = 0;

   fstatus = stdout;

   while ((ch = getopt(argc, argv, "ds:")) != EOF) 
   {
      switch (ch) 
      {
         case 'd':
            debug = 1;
            break;

         case 's':
            if((fstatus = fopen(optarg, "w+")) == (FILE *)NULL)
            {
               printf("[struct stat=\"ERROR\", msg=\"Cannot open status file: %s\"]\n",
                  optarg);
               exit(1);
            }
            break;

         default:
            printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d] [-s statusfile] statfiles.tbl fits.tbl statdir\"]\n", argv[0]);
            exit(1);
            break;
      }
   }

   if (argc - optind < 3) 
   {
      printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d] [-s statusfile] statfiles.tbl fits.tbl statdir\"]\n", argv[0]);
      exit(1);
   }

   strcpy(tblfile, argv[optind]);
   strcpy(fitfile, argv[optind + 1]);
   strcpy(statdir, argv[optind + 2]);

   fout = fopen(fitfile, "w+");

   if(fout == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Can't open output file.\"]\n");
      fflush(stdout);
      exit(1);
   }


   /**************************************************/ 
   /* Open the difference fit status file list table */
   /**************************************************/ 

   ncols = topen(tblfile);

   if(ncols <= 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid statfiles metadata file: %s\"]\n",
         tblfile);
      exit(1);
   }

   icntr1    = tcol( "cntr1");
   icntr2    = tcol( "cntr2");
   istatfile = tcol( "stat");

   if(icntr1    < 0
   || icntr2    < 0
   || istatfile < 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Need columns: cntr1 cntr2 plus minus diff\"]\n");
      exit(1);
   }


   /***************************************/ 
   /* Read the records and call mFitPlane */
   /***************************************/ 

   count   = 0;
   failed  = 0;
   missing = 0;
   warning = 0;

   fprintf(fout, "| plus|minus|       a    |      b     |      c     | crpix1  | crpix2  | xmin | xmax | ymin | ymax | xcenter | ycenter |  npixel |    rms     |    boxx    |    boxy    |  boxwidth  | boxheight  |   boxang   |\n");
   fflush(fout);

   while(1)
   {
      stat = tread();

      if(stat < 0)
         break;

      cntr1 = atoi(tval(icntr1));
      cntr2 = atoi(tval(icntr2));

      strcpy(statfile, statdir);
      strcat(statfile, "/");
      strcat(statfile, tval(istatfile));

      if(checkFile(statfile))
      {
         ++count;
         ++missing;
         continue;
      }

      fstat = fopen(statfile, "r");

      if(fstat == (FILE *)NULL)
      {
         ++count;
         ++missing;
         continue;
      }


      if(fgets(line, MAXSTR, fstat) == (char *)NULL)
      {
         ++count;
         ++missing;
         continue;
      }

      svc=svc_struct(line); 

      strcpy( status, svc_val(line, "stat", val));

      if(strcmp( status, "ABORT") == 0)
      {
         strcpy( msg, svc_val(line, "msg", val ));

         fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"%s\"]\n", msg);
         fflush(stdout);

         exit(1);
      }

      ++count;
      if(strcmp( status, "ERROR") == 0)
         ++failed;
      else if(strcmp( status, "WARNING") == 0)
         ++warning;
      else
      {
         a         = atof(svc_val(line, "a", val));
         b         = atof(svc_val(line, "b", val));
         c         = atof(svc_val(line, "c", val));
         crpix1    = atof(svc_val(line, "crpix1", val));
         crpix2    = atof(svc_val(line, "crpix2", val));
         xmin      = atoi(svc_val(line, "xmin", val));
         xmax      = atoi(svc_val(line, "xmax", val));
         ymin      = atoi(svc_val(line, "ymin", val));
         ymax      = atoi(svc_val(line, "ymax", val));
         xcenter   = atof(svc_val(line, "xcenter", val));
         ycenter   = atof(svc_val(line, "ycenter", val));
         npixel    = atof(svc_val(line, "npixel", val));
         rms       = atof(svc_val(line, "rms", val));
         boxx      = atof(svc_val(line, "boxx", val));
         boxy      = atof(svc_val(line, "boxy", val));
         boxwidth  = atof(svc_val(line, "boxwidth", val));
         boxheight = atof(svc_val(line, "boxheight", val));
         boxangle  = atof(svc_val(line, "boxang", val));


         fprintf(fout, " %5d %5d %12.5e %12.5e %12.5e %9.2f %9.2f %6d %6d %6d %6d %9.2f %9.2f %9.0f %12.5e %12.1f %12.1f %12.1f %12.1f %12.1f\n",
            cntr1, cntr2, a, b, c, crpix1, crpix2, xmin, xmax, ymin, ymax,
            xcenter, ycenter, npixel, rms, boxx, boxy, boxwidth, boxheight, boxangle);
         fflush(fout);
      }

      svc_free(svc);

      fclose(fstat);
   }

   fprintf(fstatus, "[struct stat=\"OK\", count=%d, failed=%d, missing=%d, warning=%d]\n", count, failed, missing, warning);
   fflush(stdout);

   exit(0);
}
int main(int argc, char **argv)
{
   int     i, j, k, ncol, nimages;
   int     haveHdr, itmp, istat, mAddCntr;
   int     nparents, parent, parent_prev;
   int     naxis1s, naxis2s;
  
   char    line          [MAXSTR];
   char    mproj         [MAXSTR];
   char    survey        [MAXSTR];
   char    band          [MAXSTR];
   char    hdrFile       [MAXSTR];
   char    mosaicCentLon [MAXSTR];
   char    mosaicCentLat [MAXSTR];
   char    mosaicWidth   [MAXSTR];
   char    mosaicHeight  [MAXSTR];
   char    mosaicCdelt   [MAXSTR];
   char    workdir       [MAXSTR];
   char    urlbase       [MAXSTR];
   char    workurlbase   [MAXSTR];
   char    timestr       [MAXSTR];
   char    cmd           [MAXSTR];
   char    status        [MAXSTR];
   char    msg           [MAXSTR];
   char    fname         [MAXSTR];
   char    fitname       [MAXSTR];
   char    plusname      [MAXSTR];
   char    minusname     [MAXSTR];
   char    jobid         [MAXSTR];
   char    fileList      [MAXSTR];
   char    parentList    [MAXSTR];
   char    sortedParent  [MAXSTR];

   char   *fileid;
   char   *parentid;

   clock_t timeval;

   double  width;
   double  height;
   double  cdelt;
   double  crval1, crval2;
   double  crpix1, crpix2;

   int     ifname, iurl, icntr1, icntr2, iplusname, iminusname, iscale;
   int     cntr, cntr1, cntr2, id, level;

   int     shrinkFactor, shrinkFactorX, shrinkFactorY;

   double  x, y, z;
   double  xc, yc, zc;
   double  xpos, ypos, dtr;
   double  dist, maxRadius;
   double  lonc, latc;

   FILE   *fp;
   FILE   *fdag;
   FILE   *ffit;
   FILE   *fcache;
   FILE   *furl;
   FILE   *ffile;
   FILE   *fparent;

   char   dv_version  [MAXSTR];
   
   int    maxtbl = 1000;

   char   key[MAXSTR];
   char   val[MAXSTR];

   struct stat type;

   HT_table_t *depends;

   char *path = getenv("MONTAGE_HOME");


   /* Various time value variables */

   char       buffer[256];

   int        yr, mo, day, hr, min, sec, pid;

   time_t     curtime;
   struct tm *loctime;

   char       idstr[256];


   dtr = atan(1.0)/45.;

   strcpy(dv_version, "1.0");

   HT_set_debug(0); 


   /* Generate a unique ID based on data/time/pid */

   curtime = time (NULL);
   loctime = localtime (&curtime);

   strftime(buffer, 256, "%Y", loctime);
   yr = atoi(buffer);

   strftime(buffer, 256, "%m", loctime);
   mo = atoi(buffer);

   strftime(buffer, 256, "%d", loctime);
   day = atoi(buffer);

   strftime(buffer, 256, "%H", loctime);
   hr = atoi(buffer);

   strftime(buffer, 256, "%M", loctime);
   min = atoi(buffer);

   strftime(buffer, 256, "%S", loctime);
   sec = atoi(buffer);

   pid = (int)getpid();

   sprintf(idstr, "%04d%02d%02d_%02d%02d%02d_%d",
      yr, mo, day, hr, min, sec, pid);



   /* Set up the dependency hash table */

   depends = HT_create_table(maxtbl);

   timeval = time(0);

   strcpy(timestr, ctime((const time_t *)(&timeval)));

   for(i=0; i<strlen(timestr); ++i)
      if(timestr[i] == '\n')
	 timestr[i]  = '\0';

   if(debug)
   {
      fdebug = fopen("debug.txt", "w+");

      if(fdebug == (FILE *)NULL)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Error opening debug file\"]\n");
	 exit(0);
      }

      fprintf(fdebug, "DEBUGGING mDAG:\n\n");
      fflush(fdebug);

      if(debug > 1)
	 svc_debug(fdebug);
   }



   /* Get the location/size information */

   haveHdr = 0;

   if(argc < 11)
   {
      printf("[struct stat=\"ERROR\", msg=\"Usage: %s survey band centerlon centerlat width height cdelt workdir workurlbase urlbase | %s -h survey band hdrfile workdir workurlbase urlbase (object/location string must be a single argument)\"]\n", argv[0], argv[0]);
      exit(0);
   }


   strcpy(survey,        argv[1]);
   strcpy(band,          argv[2]);
   strcpy(mosaicCentLon, argv[3]);
   strcpy(mosaicCentLat, argv[4]);
   strcpy(mosaicWidth,   argv[5]);
   strcpy(mosaicHeight,  argv[6]);
   strcpy(mosaicCdelt,   argv[7]);
   strcpy(workdir,       argv[8]);
   strcpy(workurlbase,   argv[9]);
   strcpy(urlbase,       argv[10]);

   crval1 = atof(mosaicCentLon);
   crval2 = atof(mosaicCentLat);
   width  = fabs(atof(mosaicWidth));
   height = fabs(atof(mosaicHeight));
   cdelt  = fabs(atof(mosaicCdelt));

   naxis1 = (int)(width  / cdelt) + 0.5;
   naxis2 = (int)(height / cdelt) + 0.5;

   crpix1 = (naxis1+1.)/2.;
   crpix2 = (naxis2+1.)/2.;

   istat = stat(workdir, &type);
   if(istat < 0)
      printError("work directory doesn't exist");

   strcpy(mproj, "mProject");


   /********************************************************/
   /* we have the size/center, we need to build the header */
   /********************************************************/

   /*******************************/
   /* Create header template file */
   /*******************************/

   sprintf(hdrFile, "%s/region.hdr", workdir);

   fp = fopen(hdrFile, "w+");

   if(fp == (FILE *)NULL)
   {
      printf("[struct stat=\"ERROR\", msg=\"Error opening header template file\"]\n");
	   exit(0);
   }

   fprintf(fp, "SIMPLE  = T\n"                  );
   fprintf(fp, "BITPIX  = -64\n"                );
   fprintf(fp, "NAXIS   = 2\n"                  );
   fprintf(fp, "NAXIS1  = %d\n",      naxis1    );
   fprintf(fp, "NAXIS2  = %d\n",      naxis2    );
   fprintf(fp, "CTYPE1  = '%s'\n",   "GLON-CAR" );
   fprintf(fp, "CTYPE2  = '%s'\n",   "GLAT-CAR" );
   fprintf(fp, "CRVAL1  = %11.6f\n",  crval1    );
   fprintf(fp, "CRVAL2  = %11.6f\n",  crval2    );
   fprintf(fp, "CRPIX1  = %11.6f\n",  crpix1    );
   fprintf(fp, "CRPIX2  = %11.6f\n",  crpix2    );
   fprintf(fp, "CDELT1  = %.9f\n",   -cdelt     );
   fprintf(fp, "CDELT2  = %.9f\n",    cdelt     );
   fprintf(fp, "CROTA2  = %11.6f\n",  0.0       );
   fprintf(fp, "EQUINOX = %d\n",      2000      );


   if(strcasecmp(survey, "2MASS") == 0)
   {
      if(strcasecmp(band, "J") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 20.9044);
      else if(strcasecmp(band, "H") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 20.4871);
      else if(strcasecmp(band, "K") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 19.9757);
   }

   fprintf(fp, "END\n"                          );

   fclose(fp);


   /***********************************/
   /* Create big header template file */
   /***********************************/

   sprintf(hdrFile, "%s/big_region.hdr", workdir);

   fp = fopen(hdrFile, "w+");

   if(fp == (FILE *)NULL)
   {
      printf("[struct stat=\"ERROR\", msg=\"Error opening big header template file\"]\n");
      exit(0);
   }
   
   fprintf(fp, "SIMPLE  = T\n"                      );
   fprintf(fp, "BITPIX  = -64\n"                    );
   fprintf(fp, "NAXIS   = 2\n"                      );
   fprintf(fp, "NAXIS1  = %d\n",      naxis1+3000   );
   fprintf(fp, "NAXIS2  = %d\n",      naxis2+3000   );
   fprintf(fp, "CTYPE1  = '%s'\n",   "GLON-CAR"     );
   fprintf(fp, "CTYPE2  = '%s'\n",   "GLAT-CAR"     );
   fprintf(fp, "CRVAL1  = %11.6f\n",  crval1        );
   fprintf(fp, "CRVAL2  = %11.6f\n",  crval2        );
   fprintf(fp, "CRPIX1  = %11.6f\n",  crpix1+1500   );
   fprintf(fp, "CRPIX2  = %11.6f\n",  crpix2+1500   );
   fprintf(fp, "CDELT1  = %.9f\n",   -cdelt         );
   fprintf(fp, "CDELT2  = %.9f\n",    cdelt         );
   fprintf(fp, "CROTA2  = %11.6f\n",  0.0           );
   fprintf(fp, "EQUINOX = %d\n",      2000          );

   if(strcasecmp(survey, "2MASS") == 0)
   {
      if(strcasecmp(band, "J") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 20.9044);

      else if(strcasecmp(band, "H") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 20.4871);

      else if(strcasecmp(band, "K") == 0)
         fprintf(fp, "MAGZP   = %11.6f\n", 19.9757);
   }

   fprintf(fp, "END\n"                          );
   fclose(fp);


   /************************************************/
   /* Get list of raw input images for this region */
   /************************************************/

   /* this is how mExec is implemented */
   double scaleWidth = width * 1.42;
   double scaleHeight = height * 1.42;

   if(path)
      sprintf(cmd, "%s/bin/mArchiveList %s %s \"%s %s gal\" %.2f %.2f %s/images.tbl",
            path, survey, band, mosaicCentLon, mosaicCentLat, scaleWidth,
            scaleHeight, workdir);
   else 
      sprintf(cmd, "mArchiveList %s %s \"%s %s gal\" %.2f %.2f %s/images.tbl",
            survey, band, mosaicCentLon, mosaicCentLat, scaleWidth,
            scaleHeight, workdir);

   if(debug)
   {
      fprintf(fdebug, "[%s]\n", cmd);
      fflush(fdebug);
   }

   svc_run(cmd);

   strcpy( status, svc_value( "stat" ));

   if (strcmp( status, "ERROR") == 0)
   {
      strcpy( msg, svc_value( "msg" ));

      printError(msg);
   }

   if (strcmp(status, "ABORT") == 0)
   {
      strcpy( msg, svc_value( "msg" ));

      printError(msg);
   }

   nimages = atof(svc_value("count"));

   if (nimages == 0)
   {
      sprintf( msg, "%s has no data covering this area", survey);

      printError(msg);
   }



   /*****************************************/
   /* Get the image lists the DAG will need */
   /*****************************************/

   if(path)
      sprintf(cmd, "%s/bin/mDAGTbls %s/images.tbl %s/big_region.hdr %s/rimages.tbl %s/pimages.tbl %s/cimages.tbl",
         path, workdir, workdir, workdir, workdir, workdir);
      else 
         sprintf(cmd, "mDAGTbls %s/images.tbl %s/big_region.hdr %s/rimages.tbl %s/pimages.tbl %s/cimages.tbl",
            workdir, workdir, workdir, workdir, workdir);
 

   if(debug)
   {
      fprintf(fdebug, "[%s]\n", cmd);
      fflush(fdebug);
   }

   svc_run(cmd);

   strcpy( status, svc_value( "stat" ));

   if (strcmp( status, "ERROR") == 0)
   {
      strcpy( msg, svc_value( "msg" ));

      printError(msg);
   }



   /******************************************/
   /* Get the overlap list the DAG will need */
   /******************************************/

   if(path)
      sprintf(cmd, "%s/bin/mOverlaps %s/rimages.tbl %s/diffs.tbl",
         path, workdir, workdir);
      else 
         sprintf(cmd, " mOverlaps %s/rimages.tbl %s/diffs.tbl",
            workdir, workdir);

   if(debug)
   {
      fprintf(fdebug, "[%s]\n", cmd);
      fflush(fdebug);
   }

   svc_run(cmd);

   strcpy( status, svc_value( "stat" ));

   if (strcmp( status, "ERROR") == 0)
   {
      strcpy( msg, svc_value( "msg" ));

      printError(msg);
   }


   

   /****************************************************/
   /*  Determine shrink factor for presentation image. */
   /****************************************************/

   shrinkFactorX = (int)(naxis1 / 1024. + 1.);
   shrinkFactorY = (int)(naxis2 / 1024. + 1.);

   shrinkFactor = shrinkFactorX;
   if(shrinkFactor < shrinkFactorY)
      shrinkFactor = shrinkFactorY;

   if(debug)
   {
      fprintf(fdebug, "\n");
      fprintf(fdebug, "shrinkFactorX = %d\n", shrinkFactorX);
      fprintf(fdebug, "shrinkFactorY = %d\n", shrinkFactorY);
      fprintf(fdebug, "shrinkFactor  = %d\n", shrinkFactor);
      fprintf(fdebug, "\n");
      fflush(fdebug);
   }


   /***********************************************/
   /* Now we can generate the DAG XML file itself */
   /* First the XML header                        */
   /***********************************************/

   if(debug)
   {
      fprintf(fdebug, "Generating DAG file header ...\n");
      fflush(fdebug);
   }

   sprintf(cmd, "%s/dag.xml", workdir);
   fdag = fopen(cmd, "w+");

   sprintf(cmd, "%s/cache.list", workdir);
   fcache = fopen(cmd, "w+");

   sprintf(cmd, "%s/url.list", workdir);
   furl = fopen(cmd, "w+");

   fprintf(fdag, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
   fprintf(fdag, "<!-- Generated:    %s -->\n", timestr);
   fprintf(fdag, "<!-- Generated by: Montage DAG service      -->\n\n");
   fprintf(fdag, "<adag xmlns=\"http://pegasus.isi.edu/schema/DAX\"\n");
   fprintf(fdag, "      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
   fprintf(fdag, "      xsi:schemaLocation=\"http://pegasus.isi.edu/schema/DAX http://pegasus.isi.edu/schema/dax-2.1.xsd\"\n");
   fprintf(fdag, "      version=\"2.1\" count=\"1\" index=\"0\" name=\"montage\">\n\n");

   fflush(fdag);

   fprintf(fdag, "  <!-- Survey:            %-30s -->\n", survey);
   fprintf(fdag, "  <!-- Band:              %-30s -->\n", band);
   fprintf(fdag, "  <!-- Center Longitude:  %-30s -->\n", mosaicCentLon);
   fprintf(fdag, "  <!-- Center Latitude:   %-30s -->\n", mosaicCentLat);
   
   if(haveHdr)
      fprintf(fdag, "  <!-- (WCS is in input header file)           -->\n");
   else
   {
      fprintf(fdag, "  <!-- Width:   %-30s -->\n", mosaicWidth);
      fprintf(fdag, "  <!-- Height:  %-30s -->\n", mosaicHeight);
   }

   fprintf(fdag, "\n\n");
   fflush(fdag);

   /******************************************/
   /* compose the url lfn cache list         */
   /******************************************/

   sprintf(cmd, "%s/images.tbl", workdir);

   ncol = topen(cmd);

   ifname = tcol("file");
   iurl = tcol("URL");

   if(ifname < 0)
      printError("'Raw' image list does not have column 'file'");

   if(iurl < 0)
      printError("'Raw' image list does not have column 'url'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      fprintf(furl, "%s %s pool=\"ipac_cluster\"\n", tval(ifname), tval(iurl));
   }

   tclose();
   fclose(furl);


   /******************************************/
   /* DAG: "filename" lines for input images */
   /******************************************/

   if(debug)
   {
      fprintf(fdebug, "Generating DAG file filename list ...\n");
      fflush(fdebug);
   }

   fprintf(fdag, "  <!-- Part 1:  Files Used -->\n\n");

   sprintf(cmd, "%s/rimages.tbl", workdir);

   ncol = topen(cmd);

   ifname = tcol("file");

   if(ifname < 0)
      printError("'Raw' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      fprintf(fdag, "  <filename file=\"%s\" link=\"input\"/>\n", tval(ifname));
   }

   fprintf(fdag, "\n");
   fflush(fdag);
   tclose();



   /**********************************************/
   /* DAG: "filename" lines for projected images */
   /* including area files                       */
   /**********************************************/

   sprintf(cmd, "%s/pimages.tbl", workdir);

   ncol = topen(cmd);

   ifname = tcol("file");

   if(ifname < 0)
      printError("'Projected' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      fprintf(fdag, "  <filename file=\"%s\" link=\"inout\"/>\n", tval(ifname));

      strcpy(fname, tval(ifname));

      fname[strlen(fname)-5] = '\0';

      strcat(fname, "_area.fits");

      fprintf(fdag, "  <filename file=\"%s\" link=\"inout\"/>\n", fname);
   }

   fprintf(fdag, "\n");
   fflush(fdag);
   tclose();



   /***********************************************/
   /* DAG: "filename" lines for difference images */
   /* and fit output files (plus one more file    */
   /* with a list of these fits)                  */
   /***********************************************/

   sprintf(cmd, "%s/diffs.tbl", workdir);

   ncol   = topen(cmd);
   ifname = tcol("diff");
   icntr1 = tcol("cntr1");
   icntr2 = tcol("cntr2");

   if(ifname < 0)
      printError("'Diff' image list does not have column 'diff'");

   sprintf(cmd, "%s/statfile.tbl", workdir);

   ffit = fopen(cmd, "w+");

   sprintf(fmt, "|%%7s|%%7s|%%22s|\n");
   sprintf(dfmt, " %%7d %%7d %%22s \n");

   fprintf(ffit, fmt, "cntr1", "cntr2", "stat");
   fprintf(ffit, fmt, "int", "int", "char");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      cntr1 = atoi(tval(icntr1));
      cntr2 = atoi(tval(icntr2));

      fprintf(fdag, "  <filename file=\"%s\" link=\"output\"/>\n", tval(ifname));

      strcpy(fname, tval(ifname));

      fname[strlen(fname)-5] = '\0';

      sprintf(fitname, "fit%s.txt", fname+4);

      fprintf(fdag, "  <filename file=\"%s\" link=\"inout\"/>\n\n", fitname);

      fprintf(ffit, dfmt, cntr1, cntr2, fitname);
   }

   fflush(fdag);
   tclose();

   fclose(ffit);

   fprintf(fdag, "  <filename file=\"statfile_%s.tbl\" link=\"input\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"fits.tbl\" link=\"inout\"/>\n");
   fprintf(fdag, "\n");
   fflush(fdag);

   fprintf(fcache, "statfile_%s.tbl %s/%s/statfile.tbl pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);


   /***********************************************/
   /* DAG: "filename" lines for corrections table */
   /* and the corrected image files (including    */
   /* area files)                                 */
   /***********************************************/

   fprintf(fdag, "  <filename file=\"corrections.tbl\" link=\"inout\"/>\n");
   fprintf(fdag, "\n");
   fflush(fdag);

   sprintf(cmd, "%s/cimages.tbl", workdir);

   ncol = topen(cmd);
   ifname = tcol("file");

   if(ifname < 0)
      printError("'Corrected' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      fprintf(fdag, "  <filename file=\"%s\" link=\"inout\"/>\n", tval(ifname));

      strcpy(fname, tval(ifname));

      fname[strlen(fname)-5] = '\0';

      strcat(fname, "_area.fits");

      fprintf(fdag, "  <filename file=\"%s\" link=\"inout\"/>\n", fname);
   }

   fprintf(fdag, "\n");
   fflush(fdag);
   tclose();
   

   /***********************************************/
   /* DAG: "filename" lines for template files,   */
   /* subset image files, output files, and       */
   /* shrunken output files.                      */
   /***********************************************/

   fprintf(fdag, "  <filename file=\"newcimages.tbl\" link=\"inout\"/>\n");
   fprintf(fdag, "\n");
   fflush(fdag);

   fprintf(fdag, "  <filename file=\"big_region_%s.hdr\" link=\"input\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"region_%s.hdr\" link=\"input\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"pimages_%s.tbl\" link=\"input\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"cimages_%s.tbl\" link=\"input\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"dag_%s.xml\" link=\"inout\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"images_%s.tbl\" link=\"inout\"/>\n", idstr);
   fprintf(fdag, "\n");

   fprintf(fdag, "  <filename file=\"shrunken_%s.hdr\" link=\"inout\"/>\n", idstr);

   fprintf(fdag, "  <filename file=\"shrunken_%s.fits\" link=\"inout\"/>\n", idstr);
   fprintf(fdag, "  <filename file=\"shrunken_%s.jpg\" link=\"output\"/>\n", idstr);
   fprintf(fdag, "\n\n");
   fflush(fdag);

   fprintf(fcache, "big_region_%s.hdr %s/%s/big_region.hdr pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);
   fprintf(fcache, "region_%s.hdr %s/%s/region.hdr pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);

   fprintf(fcache, "pimages_%s.tbl %s/%s/pimages.tbl pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);
   fprintf(fcache, "cimages_%s.tbl %s/%s/cimages.tbl pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);
   fflush(fcache);

   /* to be saved in user's storage space */
   fprintf(fcache, "dag_%s.xml %s/%s/dag.xml pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);
   fprintf(fcache, "images_%s.tbl %s/%s/images.tbl pool=\"ipac_cluster\"\n", idstr, workurlbase, workdir);

   /**************************************************/
   /* DAG: "job" lines for mProject/mProjectPP jobs. */
   /**************************************************/

   if(debug)
   {
      fprintf(fdebug, "Generating DAG file job list ...\n");
      fflush(fdebug);
   }

   id    = 0;
   level = 9;

   fprintf(fdag, "  <!-- Part 2:  Definition of Jobs -->\n\n");

   cntr = 0;

   sprintf(cmd, "%s/rimages.tbl", workdir);

   ncol   = topen(cmd);

   ifname = tcol("file");
   iscale = tcol("scale");

   if(ifname < 0)
      printError("'Raw' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      ++id;
      ++cntr;

      strcpy(fname, tval(ifname));

      fname[strlen(fname) - 5] = '\0';

      fprintf(fdag,"  <job id=\"ID%06d\" name=\"%s\" version=\"3.0\" level=\"%d\" dv-name=\"mProject%d\" dv-version=\"1.0\">\n", id, mproj, level, cntr);

      if(iscale >= 0)
	 fprintf(fdag,"    <argument>\n      -X\n      -x %s\n      <filename file=\"%s.fits\"/>\n      <filename file=\"p%s.fits\"/>\n      <filename file=\"big_region_%s.hdr\"/>\n    </argument>\n\n", tval(iscale), fname, fname, idstr);
      else
	 fprintf(fdag,"    <argument>\n      -X\n      <filename file=\"%s.fits\"/>\n      <filename file=\"p%s.fits\"/>\n      <filename file=\"big_region_%s.hdr\"/>\n    </argument>\n\n", fname, fname, idstr);

      fprintf(fdag,"    <uses file=\"%s.fits\" link=\"input\" transfer=\"true\"/>\n", fname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "%s.fits",  fname);
      HT_add_entry(depends, key, val);

      fprintf(fcache,"%s.fits %s/%s.fits pool=\"ipac_cluster\"\n",fname,urlbase,fname);

      fprintf(fdag,"    <uses file=\"p%s.fits\" link=\"output\" register=\"false\" transfer=\"false\"/>\n", fname);

      sprintf(key, "p%s.fits", fname);
      sprintf(val, "ID%06d", id);
      HT_add_entry(depends, key, val);

      fprintf(fdag,"    <uses file=\"p%s_area.fits\" link=\"output\" register=\"false\" transfer=\"false\"/>\n", fname);

      fprintf(fdag,"    <uses file=\"big_region_%s.hdr\" link=\"input\" transfer=\"true\"/>\n", idstr);

      sprintf(key, "ID%06d", id);
      sprintf(val, "big_region.hdr");
      HT_add_entry(depends, key, val);

      fprintf(fdag,"  </job>\n\n\n");
   }

   tclose();
   fflush(fcache);
   fclose(fcache);



   /***************************************/
   /* DAG: "job" lines for mDiffFit jobs. */
   /***************************************/

   cntr = 0;

   sprintf(cmd, "%s/diffs.tbl", workdir);

   ncol      = topen(cmd);

   icntr1     = tcol("cntr1");
   icntr2     = tcol("cntr2");
   iplusname  = tcol("plus");
   iminusname = tcol("minus");

   --level;

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      ++id;
      ++cntr;

      cntr1 = atoi(tval(icntr1));
      cntr2 = atoi(tval(icntr2));

      strcpy(plusname,  tval(iplusname));
      strcpy(minusname, tval(iminusname));

      plusname [strlen(plusname)  - 5] = '\0';
      minusname[strlen(minusname) - 5] = '\0';

      fname[strlen(fname) - 5] = '\0';

      fprintf(fdag, "  <job id=\"ID%06d\" name=\"mDiffFit\" version=\"3.0\" level=\"%d\" dv-name=\"mDiffFit%d\" dv-version=\"1.0\">\n", id, level, cntr);

      fprintf(fdag, "    <argument>\n      -s <filename file=\"fit.%06d.%06d.txt\"/>\n      <filename file=\"p%s.fits\"/>\n      <filename file=\"p%s.fits\"/>\n      <filename file=\"diff.%06d.%06d.fits\"/>\n      <filename file=\"big_region_%s.hdr\"/>\n    </argument>\n\n", 
         cntr1, cntr2, plusname, minusname, cntr1, cntr2, idstr);

      fprintf(fdag, "    <uses file=\"mDiff\" link=\"input\" transfer=\"true\" type=\"executable\"/>\n");
      fprintf(fdag, "    <uses file=\"mFitplane\" link=\"input\" transfer=\"true\" type=\"executable\"/>\n");

      fprintf(fdag, "    <uses file=\"fit.%06d.%06d.txt\" link=\"output\" register=\"false\" transfer=\"false\"/>\n",
         cntr1, cntr2);

      sprintf(key, "fit.%06d.%06d.txt",  cntr1, cntr2);
      sprintf(val, "ID%06d", id);
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"p%s.fits\" link=\"input\" transfer=\"true\"/>\n",
         plusname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "p%s.fits",  plusname);
      HT_add_entry(depends, key, val);


      fprintf(fdag, "    <uses file=\"p%s_area.fits\" link=\"input\" transfer=\"true\"/>\n", 
         plusname);

      fprintf(fdag, "    <uses file=\"p%s.fits\" link=\"input\" transfer=\"true\"/>\n",
         minusname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "p%s.fits",  minusname);
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"p%s_area.fits\" link=\"input\" transfer=\"true\"/>\n", 
         minusname);

      fprintf(fdag, "    <uses file=\"diff.%06d.%06d.fits\" link=\"output\" register=\"false\" transfer=\"false\" optional=\"true\"/>\n", cntr1, cntr2);

      sprintf(key, "diff.%06d.%06d.fits",  cntr1, cntr2);
      sprintf(val, "ID%06d", id);
      HT_add_entry(depends, key, val);


      fprintf(fdag, "    <uses file=\"big_region_%s.hdr\" link=\"input\" transfer=\"true\"/>\n", idstr);

      sprintf(key, "ID%06d", id);
      sprintf(val, "big_region.hdr");
      HT_add_entry(depends, key, val);

      fprintf(fdag, "  </job>\n\n\n");
   }

   tclose();



   /****************************************/
   /* DAG: "job" line for mConcatFit jobs. */
   /****************************************/

   ++id;

   --level;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mConcatFit\" version=\"3.0\" level=\"%d\" dv-name=\"mConcatFit1\" dv-version=\"1.0\">\n", id, level);

   fprintf(fdag, "    <argument>\n      <filename file=\"statfile_%s.tbl\"/>\n      <filename file=\"fits.tbl\"/>\n      .\n    </argument>\n\n", idstr);

   fprintf(fdag, "    <uses file=\"statfile_%s.tbl\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "statfile.tbl");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"fits.tbl\" link=\"output\" register=\"false\" transfer=\"false\"/>\n");

   sprintf(key, "fits.tbl");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   sprintf(cmd, "%s/diffs.tbl", workdir);

   ncol   = topen(cmd);
   icntr1 = tcol("cntr1");
   icntr2 = tcol("cntr2");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      cntr1 = atoi(tval(icntr1));
      cntr2 = atoi(tval(icntr2));

      fprintf(fdag, "    <uses file=\"fit.%06d.%06d.txt\" link=\"input\" transfer=\"true\"/>\n", 
         cntr1, cntr2);

      sprintf(key, "ID%06d", id);
      sprintf(val, "fit.%06d.%06d.txt", cntr1, cntr2);
      HT_add_entry(depends, key, val);
   }

   tclose();
      
   fprintf(fdag, "  </job>\n\n\n");



   /*************************************/
   /* DAG: "job" line for mBgModel job. */
   /*************************************/

   ++id;

   --level;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mBgModel\" version=\"3.0\" level=\"%d\" dv-name=\"mBgModel1\" dv-version=\"1.0\">\n", id, level);

   fprintf(fdag, "    <argument>\n      -l\n      -i 100000\n      <filename file=\"pimages_%s.tbl\"/>\n      <filename file=\"fits.tbl\"/>\n      <filename file=\"corrections.tbl\"/>\n    </argument>\n\n", idstr);

   fprintf(fdag, "    <uses file=\"pimages_%s.tbl\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "pimages.tbl");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"fits.tbl\" link=\"input\" transfer=\"true\"/>\n");

   sprintf(key, "ID%06d", id);
   sprintf(val, "fits.tbl");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"corrections.tbl\" link=\"output\" register=\"false\" transfer=\"false\"/>\n");

   sprintf(key, "corrections.tbl");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "  </job>\n\n\n");



   /*****************************************/
   /* DAG: "job" line for mBackground jobs. */
   /*****************************************/

   --level;

   cntr = 0;

   sprintf(cmd, "%s/rimages.tbl", workdir);

   ncol   = topen(cmd);
   ifname = tcol("file");

   if(ifname < 0)
      printError("'Raw' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      strcpy(fname, tval(ifname));

      fname[strlen(fname) - 5] = '\0';

      ++id;
      ++cntr;

      fprintf(fdag, "  <job id=\"ID%06d\" name=\"mBackground\" version=\"3.0\" level=\"%d\" dv-name=\"mBackground%d\" dv-version=\"1.0\">\n", id, level, cntr);

      fprintf(fdag, "    <argument>\n      -t\n      <filename file=\"p%s.fits\"/>\n      <filename file=\"c%s.fits\"/>\n      <filename file=\"pimages_%s.tbl\"/>\n      <filename file=\"corrections.tbl\"/>\n    </argument>\n\n", 
         fname, fname, idstr);

      fprintf(fdag, "    <uses file=\"p%s.fits\" link=\"input\" transfer=\"true\"/>\n",
         fname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "p%s.fits", fname);
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"p%s_area.fits\" link=\"input\" transfer=\"true\"/>\n", 
         fname);

      fprintf(fdag, "    <uses file=\"pimages_%s.tbl\" link=\"input\" transfer=\"true\"/>\n", idstr);

      sprintf(key, "ID%06d", id);
      sprintf(val, "pimages.tbl");
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"corrections.tbl\" link=\"input\" transfer=\"true\"/>\n");

      sprintf(key, "ID%06d", id);
      sprintf(val, "corrections.tbl");
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"c%s.fits\" link=\"output\" register=\"false\" transfer=\"false\"/>\n", 
         fname);

      sprintf(key, "c%s.fits", fname);
      sprintf(val, "ID%06d", id);
      HT_add_entry(depends, key, val);

      fprintf(fdag, "    <uses file=\"c%s_area.fits\" link=\"output\" register=\"false\" transfer=\"false\"/>\n", 
         fname);

      fprintf(fdag, "  </job>\n\n\n");
   }

   fflush(fdag);



   /**********************************************/
   /* DAG: "job" lines for tile mImgtbl jobs.    */
   /* We have to regenerate the cimages table(s) */
   /* because the pixel offsets and sizes need   */
   /* to be exactly right and the original is    */
   /* only an approximation.                     */
   /**********************************************/

   --level;

   cntr = 0;

   ++id;
   ++cntr;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mImgtbl\" version=\"3.0\" level=\"%d\" dv-name=\"mImgtbl%d\" dv-version=\"1.0\">\n", 
         id, level, cntr);

   fprintf(fdag, "    <argument>\n      .\n      -t <filename file=\"cimages_%s.tbl\"/>\n      <filename file=\"newcimages.tbl\"/>\n    </argument>\n\n", idstr);

   fprintf(fdag, "    <uses file=\"cimages_%s.tbl\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "cimages.tbl");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"newcimages.tbl\" link=\"output\" register=\"false\" transfer=\"false\"/>\n");

   sprintf(key, "newcimages.tbl");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   sprintf(cmd, "%s/cimages.tbl", workdir);

   ncol = topen(cmd);
   ifname = tcol("file");

   if(ifname < 0)
      printError("'Corrected' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      strcpy(fname, tval(ifname));

      fname[strlen(fname) - 5] = '\0';

      fprintf(fdag, "    <uses file=\"%s.fits\" link=\"input\" transfer=\"true\"/>\n", 
            fname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "%s.fits", fname);
      HT_add_entry(depends, key, val);
   }

   tclose();

   fprintf(fdag, "  </job>\n\n\n");
   fflush(fdag);


   /*******************************************/
   /* DAG: "job" lines for tile mAdd jobs.    */
   /*******************************************/

   --level;

   cntr = 0;

   ++id;
   ++cntr;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mAdd\" version=\"3.0\" level=\"%d\" dv-name=\"mAdd%d\" dv-version=\"1.0\">\n", 
         id, level, cntr);

   fprintf(fdag, "    <argument>\n      -e\n      <filename file=\"newcimages.tbl\"/>\n      <filename file=\"region_%s.hdr\"/>\n      <filename file=\"mosaic_%s.fits\"/>\n    </argument>\n\n", idstr, idstr);

   fprintf(fdag, "    <uses file=\"newcimages.tbl\" link=\"input\" transfer=\"true\"/>\n");

   sprintf(key, "ID%06d", id);
   sprintf(val, "newcimages.tbl");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"region_%s.hdr\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "region.hdr");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"mosaic_%s.fits\" link=\"output\" register=\"true\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "mosaic.fits");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"mosaic_%s_area.fits\" link=\"output\" register=\"true\" transfer=\"true\"/>\n", idstr);

   sprintf(cmd, "%s/cimages.tbl", workdir);

   ncol = topen(cmd);
   ifname = tcol("file");

   if(ifname < 0)
      printError("'Corrected' image list does not have column 'file'");

   while(1)
   {
      istat = tread();

      if(istat < 0)
         break;

      strcpy(fname, tval(ifname));

      fname[strlen(fname) - 5] = '\0';

      fprintf(fdag, "    <uses file=\"%s.fits\" link=\"input\" transfer=\"true\"/>\n", 
            fname);

      fprintf(fdag, "    <uses file=\"%s_area.fits\" link=\"input\" transfer=\"true\"/>\n", 
            fname);

      sprintf(key, "ID%06d", id);
      sprintf(val, "%s.fits",  fname);
      HT_add_entry(depends, key, val);

   }

   fprintf(fdag, "  </job>\n\n\n");
   fflush(fdag);

   mAddCntr = cntr;



   /*******************************************/
   /* DAG: "job" lines for tile mShrink jobs. */
   /*******************************************/

   --level;

   cntr = 0;

   ++id;
   ++cntr;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mShrink\" version=\"3.0\" level=\"%d\" dv-name=\"mShrink%d\" dv-version=\"1.0\">\n", id, level, cntr);

   fprintf(fdag, "    <argument>\n      <filename file=\"mosaic_%s.fits\"/>\n      <filename file=\"shrunken_%s.fits\"/>\n      %d\n    </argument>\n\n", idstr, idstr, shrinkFactor);

   fprintf(fdag, "    <uses file=\"mosaic_%s.fits\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "mosaic.fits");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"shrunken_%s.fits\" link=\"output\" register=\"true\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "shrunken.fits");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "  </job>\n\n\n");

   fflush(fdag);


   /****************************/
   /* DAG: Make the final JPEG */
   /****************************/

   ++id;

   --level;

   fprintf(fdag, "  <job id=\"ID%06d\" name=\"mJPEG\" version=\"3.0\" level=\"%d\" dv-name=\"mJPEG1\" dv-version=\"1.0\">\n", id, level);

   fprintf(fdag, "    <argument>\n      -ct 1\n      -gray <filename file=\"shrunken_%s.fits\"/>\n      min max gaussianlog\n      -out <filename file=\"shrunken_%s.jpg\"/>\n    </argument>\n\n", idstr, idstr);

   fprintf(fdag, "    <uses file=\"shrunken_%s.fits\" link=\"input\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "ID%06d", id);
   sprintf(val, "shrunken.fits");
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"shrunken_%s.jpg\" link=\"output\" register=\"true\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "shrunken.jpg");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"dag_%s.xml\" link=\"input\" transfer=\"true\"/>\n", idstr);
   fprintf(fdag, "    <uses file=\"dag_%s.xml\" link=\"output\" register=\"false\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "dag.xml");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "    <uses file=\"images_%s.tbl\" link=\"input\" transfer=\"true\"/>\n", idstr);
   fprintf(fdag, "    <uses file=\"images_%s.tbl\" link=\"output\" register=\"false\" transfer=\"true\"/>\n", idstr);

   sprintf(key, "images.tbl");
   sprintf(val, "ID%06d", id);
   HT_add_entry(depends, key, val);

   fprintf(fdag, "  </job>\n\n\n\n");

   fflush(fdag);



   /*******************************************/
   /* DAG: Flow control dependencies.         */
   /* First, mDiffs depend on mProjects       */
   /*******************************************/

   if(debug)
   {
      fprintf(fdebug, "Generating DAG file parent/child info ...\n");
      fflush(fdebug);
   }

   fprintf(fdag, "  <!-- Part 3:  Control-Flow Dependencies -->\n\n");

   sprintf(fileList,     "%s/files.lis",   workdir);
   sprintf(parentList,   "%s/parents.lis", workdir);
   sprintf(sortedParent, "%s/sortedParents.lis", workdir);

   for(i=1; i<=id; ++i)
   {
      sprintf(jobid, "ID%06d", i);

      fileid = HT_lookup_key(depends, jobid);

      ffile = fopen(fileList, "w+");

      if(ffile == (FILE *)NULL)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Error opening working file list for write\"]\n");
	 exit(0);
      }

      while(fileid != (char *)NULL)
      {
	 fprintf(ffile, "%s\n", fileid);
	 fflush(ffile);

	 fileid = HT_next_entry(depends);
      }

      fclose(ffile);

      ffile = fopen(fileList, "r");

      if(ffile == (FILE *)NULL)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Error opening working file list for read\"]\n");
	 exit(0);
      }

      fparent = fopen(parentList, "w+");

      if(fparent == (FILE *)NULL)
      {
	 printf("[struct stat=\"ERROR\", msg=\"Error opening parent list\"]\n");
	 exit(0);
      }

      nparents = 0;

      fprintf(fparent, "|   parent   |\n");

      while(1)
      {
	 if(fgets(line, MAXSTR, ffile) == (char *)NULL)
	    break;

	 if(line[strlen(line)-1] == '\n')
	    line[strlen(line)-1]  = '\0';

	 parentid = HT_lookup_key(depends, line);

	 while(parentid != (char *)NULL)
	 {
	    parent = atoi(parentid+2);

	    fprintf(fparent, " %12d\n", parent);
	    fflush(fparent);

	    ++nparents;

	    parentid = HT_next_entry(depends);
	 }
      }

      fclose(ffile);
      fclose(fparent);

      unlink(fileList);

      if(nparents > 0)
      {

      if(path)
	 sprintf(cmd, "%s/bin/mTblSort %s parent %s", path, parentList, sortedParent);
         else 
	    sprintf(cmd, "mTblSort %s parent %s", parentList, sortedParent);
	 
	 svc_run(cmd);

	 strcpy( status, svc_value( "stat" ));

	 if (strcmp( status, "ERROR") == 0)
	 {
	    strcpy( msg, svc_value( "msg" ));

	    printError(msg);
	 }

         unlink(parentList);

	 fparent = fopen(sortedParent, "r");

	 if(fparent == (FILE *)NULL)
	 {
	    printf("[struct stat=\"ERROR\", msg=\"Error opening sorted parent list\"]\n");
	    exit(0);
	 }

	 fgets(line, MAXSTR, fparent);

	 fprintf(fdag, "  <child ref=\"%s\">\n", jobid);

	 for(j=0; j<nparents; ++j)
	 {
            if(fgets(line, MAXSTR, fparent) == (char *)NULL)
	       break;
	    
	    parent_prev = parent;
	    parent = atoi(line);

	    if(j > 0 && parent == parent_prev)
	       continue;

	    fprintf(fdag, "    <parent ref=\"ID%06d\"/>\n", parent);
	 }

	 fprintf(fdag, "  </child>\n\n");
	 fflush(fdag);

         fclose(fparent);
      }
      unlink(sortedParent);
   }

   fprintf(fdag, "</adag>\n");
   fflush(fdag);
   fclose(fdag);

   if(debug)
   {
      fprintf(fdebug, "done.\n");
      fflush(fdebug);
   }

   printf("[struct stat=\"OK\", id=\"%s\"]\n", idstr);
   exit(0);
}
Beispiel #18
0
bool GlobalGrid::read( std::ifstream &ifs ){ // reads the grid
        clear();
        std::string T;
        ifs >> T;
        if ( !(T.compare( "num_dimensions:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 1" << endl; ifs.close(); clear(); return false; }
        ifs >> num_dimensions;
        ifs >> T; if ( !(T.compare( "num_outputs:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 2" << endl; ifs.close(); clear(); return false; }
        ifs >> num_outputs;
        ifs >> T; if ( !(T.compare( "alpha:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 3" << endl; ifs.close(); clear(); return false; }
        tread( 1, &alpha, ifs );
        ifs >> T; if ( !(T.compare( "beta:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 4" << endl; ifs.close(); clear(); return false; }
        tread( 1, &beta, ifs );
        ifs >> T; if ( !(T.compare( "ruleType:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 6" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare("lagrange-chebyshev") == 0 ){       ruleType = rule_chebyshev; }else
        if ( T.compare("lagrange-clenshaw-curtis") == 0 ){ ruleType = rule_clenshawcurtis; }else
        if ( T.compare("lagrange-chebyshev-nested-twopoint") == 0 ){ ruleType = rule_chebyshevN2P; }else
        if ( T.compare("lagrange-gauss-legendre") == 0 ){  ruleType = rule_gausslegendre; }else
        if ( T.compare("lagrange-gauss-chebyshev1") == 0 ){  ruleType = rule_gausschebyshev1; }else
        if ( T.compare("lagrange-gauss-chebyshev2") == 0 ){  ruleType = rule_gausschebyshev2; }else
        if ( T.compare("lagrange-fejer2") == 0 ){  ruleType = rule_fejer2; }else
        if ( T.compare("lagrange-gauss-gegenbauer") == 0 ){  ruleType = rule_gaussgegenbauer; }else
        if ( T.compare("lagrange-gauss-jacobi") == 0 ){  ruleType = rule_gaussjacobi; }else
        if ( T.compare("lagrange-gauss-laguerre") == 0 ){  ruleType = rule_gausslaguerre; }else
        if ( T.compare("lagrange-gauss-hermite") == 0 ){  ruleType = rule_gausshermite; }else{
                cerr << "ERROR: Wrong File Format! code GG 7" << endl; ifs.close(); clear(); return false;
        }
        ifs >> T; if ( !(T.compare( "Anisotropic:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 8" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare("yes") == 0 ){
                anisotropic = new int[num_dimensions+1];
                tread( num_dimensions+1, anisotropic, ifs );
                //tensorList = new IndexSet( num_dimensions, 0, num_outputs ); tensorList->read( ifs );
        }
        ifs >> T; if ( !(T.compare( "Tensors:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 9" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare("yes") == 0 ){
                tensorList = new IndexSet( num_dimensions, 0, num_outputs ); tensorList->read( ifs );
        }
        ifs >> T; if ( !(T.compare( "TensorWeights:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 10" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare("yes") == 0 ){
                tensor_weights = new int[tensorList->getNumIndexes()]; tread( tensorList->getNumIndexes(), tensor_weights, ifs );
        }
        ifs >> T; if ( !(T.compare( "Points:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 11" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare("yes") == 0 ){
                points = new IndexSet( num_dimensions, 0, num_outputs ); points->read( ifs );
        }
        ifs >> T; if ( !(T.compare( "NeededPoints:" ) == 0) ){ cerr << "ERROR: Wrong File Format! code GG 12" << endl; ifs.close(); clear(); return false; }
        ifs >> T;
        if ( T.compare( "yes" ) == 0 ){
                needed_points = new IndexSet( num_dimensions, 0, num_outputs );
                needed_points->read( ifs );
        }else{
                needed_points = 0;
        }

        makeOnedRule( computeMaxLevel() + 1 );
        makeTensorsArray();
        if ( num_outputs > 0 ){
                for( int t=0; t<tensorList->getNumIndexes(); t++ ){
                        if ( tensor_weights[t] != 0 ){
                                tensorRules[t].referenceValues( points );
                        }
                }
        }

        return true;
}
Beispiel #19
0
int main(int argc, char **argv)
{
   int       debug, noAreas, i;
   int       tableDriven, haveStatus;
   int       icntr, ifname, cntr;
   int       ncols, index, istat;
   int       ia, ib, ic, id;

   double    A, B, C;

   char      input_file [MAXSTR];
   char      output_file[MAXSTR];
   char      tblfile    [MAXSTR];
   char      corrfile   [MAXSTR];
   char      file       [MAXSTR];

   char     *end;

   struct mBackgroundReturn *returnStruct;

   FILE *montage_status;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   debug       = 0;
   tableDriven = 0;
   noAreas     = 0;
   haveStatus  = 0;

   montage_status = stdout;

   for(i=0; i<argc; ++i)
   {
      if(strcmp(argv[i], "-s") == 0)
      {
         haveStatus = 1;

         if(i+1 >= argc)
         {
            printf("[struct stat=\"ERROR\", msg=\"No status file name given\"]\n");
            exit(1);
         }

         if((montage_status = fopen(argv[i+1], "w+")) == (FILE *)NULL)
         {
            printf ("[struct stat=\"ERROR\", msg=\"Cannot open status file: %s\"]\n",
               argv[i+1]);
            exit(1);
         }

         ++i;
      }

      else if(strcmp(argv[i], "-n") == 0)
         noAreas = 1;

      else if(strcmp(argv[i], "-t") == 0)
         tableDriven = 1;

      else if(strcmp(argv[i], "-d") == 0)
      {
         if(i+1 >= argc)
         {
            printf("[struct stat=\"ERROR\", msg=\"No debug level given\"]\n");
            exit(1);
         }

         debug = strtol(argv[i+1], &end, 0);

         if(end - argv[i+1] < strlen(argv[i+1]))
         {
            printf("[struct stat=\"ERROR\", msg=\"Debug level string is invalid: '%s'\"]\n", argv[i+1]);
            exit(1);
         }

         if(debug < 0)
         {
            printf("[struct stat=\"ERROR\", msg=\"Debug level value cannot be negative\"]\n");
            exit(1);
         }

         ++i;
      }
   }

   if(haveStatus)
   {
      argv += 2;
      argc -= 2;;
   }
   
   if(debug)
   {
      argv += 2;
      argc -= 2;;
   }
   
   if(noAreas)
   {
      ++argv;
      --argc;
   }
   
   if(tableDriven)
   {
      ++argv;
      --argc;
   }
   
   if (argc < 5) 
   {
      printf ("[struct stat=\"ERROR\", msg=\"Usage: mBackground [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits A B C | mBackground [-t(able-mode)] [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits images.tbl corrfile.tbl\"]\n");
      exit(1);
   }

   strcpy(input_file,  argv[1]);

   if(input_file[0] == '-')
   {
      printf ("[struct stat=\"ERROR\", msg=\"Invalid input file '%s'\"]\n", input_file);
      exit(1);
   }

   strcpy(output_file, argv[2]);

   if(output_file[0] == '-')
   {
      printf ("[struct stat=\"ERROR\", msg=\"Invalid output file '%s'\"]\n", output_file);
      exit(1);
   }

   A = 0.;
   B = 0.;
   C = 0.;

   if(!tableDriven)
   {
      if (argc != 6) 
      {
         printf ("[struct stat=\"ERROR\", msg=\"Usage: mBackground [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits A B C | mBackground [-t](able-mode) [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits images.tbl corrfile.tbl\"]\n");
         exit(1);
      }

      A = strtod(argv[3], &end);

      if(end < argv[3] + strlen(argv[3]))
      {
         printf ("[struct stat=\"ERROR\", msg=\"A coefficient string is not a number\"]\n");
         exit(1);
      }

      B = strtod(argv[4], &end);

      if(end < argv[4] + strlen(argv[4]))
      {
         printf ("[struct stat=\"ERROR\", msg=\"B coefficient string is not a number\"]\n");
         exit(1);
      }

      C = strtod(argv[5], &end);

      if(end < argv[5] + strlen(argv[5]))
      {
         printf ("[struct stat=\"ERROR\", msg=\"C coefficient string is not a number\"]\n");
         exit(1);
      }
   }
   else
   {
      /* Look up the file cntr in the images.tbl file */
      /* and then the correction coefficients in the  */
      /* corrections table generated by mBgModel      */

      if (argc != 5) 
      {
         printf ("[struct stat=\"ERROR\", msg=\"Usage: mBackground [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits A B C | mBackground [-t](able-mode) [-d level] [-n(o-areas)] [-s statusfile] in.fits out.fits images.tbl corrfile.tbl\"]\n");
         exit(1);
      }

      strcpy(tblfile,  argv[3]);
      strcpy(corrfile, argv[4]);


      /* Open the image list table file */

      ncols = topen(tblfile);

      if(ncols <= 0)
      {
         fprintf(montage_status, "[struct stat=\"ERROR\", msg=\"Invalid image metadata file: %s\"]\n",
            tblfile);
         exit(1);
      }

      icntr  = tcol( "cntr");
      ifname = tcol( "fname");

      if(ifname < 0)
         ifname = tcol( "file");

      if(icntr  < 0
      || ifname < 0)
      {
         fprintf(montage_status, "[struct stat=\"ERROR\", msg=\"Image table needs columns cntr and fname\"]\n");
         exit(1);
      }


      /* Read the records and find the cntr for our file name */

      index = 0;

      while(1)
      {
         istat = tread();

         if(istat < 0)
         {
            fprintf(montage_status, "[struct stat=\"ERROR\", msg=\"Hit end of image table without finding file name\"]\n");
            exit(1);
         }

         cntr = atoi(tval(icntr));

         strcpy(file, tval(ifname));

         if(strcmp(file, input_file) == 0)
            break;
      }

      tclose();


      ncols = topen(corrfile);

      icntr    = tcol( "id");
      ia       = tcol( "a");
      ib       = tcol( "b");
      ic       = tcol( "c");

      if(icntr    < 0
      || ia       < 0
      || ib       < 0
      || ic       < 0)
      {
         fprintf(montage_status, "[struct stat=\"ERROR\", msg=\"Need columns: id,a,b,c in corrections file\"]\n");
         exit(1);
      }


      /* Read the records and find the correction coefficients */

      while(1)
      {
         istat = tread();

         if(istat < 0)
         {
            A = 0.;
            B = 0.;
            C = 0.;

            break;
         }

         id = atoi(tval(icntr));

         if(id != cntr)
            continue;

         A = atof(tval(ia));
         B = atof(tval(ib));
         C = atof(tval(ic));

         break;
      }

      tclose();
   }

   returnStruct = mBackground(input_file, output_file, A, B, C, noAreas, debug);

   if(returnStruct->status == 1)
   {
       fprintf(montage_status, "[struct stat=\"ERROR\", msg=\"%s\"]\n", returnStruct->msg);
       exit(1);
   }
   else
   {
       fprintf(montage_status, "[struct stat=\"OK\", %s]\n", returnStruct->msg);
       exit(0);
   }
}
Beispiel #20
0
int main(int argc, char **argv)
{
   int    c;
   char   header[32768];
   char   temp  [MAXSTR];
   char   fmt   [MAXSTR];
   char   rfmt  [MAXSTR];
   char   pfmt  [MAXSTR];
   char   cfmt  [MAXSTR];
   char   ofile [MAXSTR];
   char   scale [MAXSTR];
   int    i, j;
   int    namelen, nimages, ntotal, stat;
   double xpos, ypos;
   double lon, lat;
   double oxpix, oypix;
   int    oxpixMin, oypixMin;
   int    oxpixMax, oypixMax;
   int    offscl, mode;
   int    ncols;
   FILE  *fraw;
   FILE  *fproj;
   FILE  *fcorr;


   /***************************************/
   /* Process the command-line parameters */
   /***************************************/

   debug   = 0;
   opterr  = 0;

   fstatus = stdout;

   while ((c = getopt(argc, argv, "ds:")) != EOF) 
   {
      switch (c) 
      {
         case 'd':
            debug = 1;
            break;

         case 's':
            if((fstatus = fopen(optarg, "w+")) == (FILE *)NULL)
            {
               printf("[struct stat=\"ERROR\", msg=\"Cannot open status file: %s\"]\n",
                  optarg);
               exit(1);
            }
            break;

         default:
	    printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d][-s statusfile] images.tbl hdr.template raw.tbl projected.tbl corrected.tbl\"]\n", argv[0]);
            exit(1);
            break;
      }
   }

   if (argc - optind < 5) 
   {
      printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-d][-s statusfile] images.tbl hdr.template raw.tbl projected.tbl corrected.tbl\"]\n", argv[0]);
      exit(1);
   }

   strcpy(origimg_file,  argv[optind]);
   strcpy(template_file, argv[optind + 1]);
   strcpy(rawimg_file,   argv[optind + 2]);
   strcpy(projimg_file,  argv[optind + 3]);
   strcpy(corrimg_file,  argv[optind + 4]);

   checkHdr(template_file, 1, 0);

   if(debug)
   {
      printf("\norigimg_file   = [%s]\n", origimg_file);
      printf("template_file  = [%s]\n\n", template_file);
      printf("rawimg_file    = [%s]\n", rawimg_file);
      printf("projimg_file   = [%s]\n", projimg_file);
      printf("corrimg_file   = [%s]\n", corrimg_file);
      fflush(stdout);
   }


   /*************************************************/ 
   /* Process the output header template to get the */ 
   /* image size, coordinate system and projection  */ 
   /*************************************************/ 

   readTemplate(template_file);

   if(debug)
   {
      printf("\noutput.sys       =  %d\n",  output.sys);
      printf("output.epoch     =  %-g\n", output.epoch);
      printf("output proj      =  %s\n",  output.wcs->ptype);

      fflush(stdout);
   }


   /*********************************************/ 
   /* Open the image header metadata table file */
   /*********************************************/ 

   ncols = topen(origimg_file);

   if(ncols <= 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid image metadata file: %s\"]\n",
         origimg_file);
      exit(1);
   }


   icntr    = tcol("cntr");
   ictype1  = tcol("ctype1");
   ictype2  = tcol("ctype2");
   iequinox = tcol("equinox");
   inl      = tcol("nl");
   ins      = tcol("ns");
   icrval1  = tcol("crval1");
   icrval2  = tcol("crval2");
   icrpix1  = tcol("crpix1");
   icrpix2  = tcol("crpix2");
   icdelt1  = tcol("cdelt1");
   icdelt2  = tcol("cdelt2");
   icrota2  = tcol("crota2");
   iepoch   = tcol("epoch");
   ifname   = tcol("fname");
   iscale   = tcol("scale");

   icd11    = tcol("cd1_1");
   icd12    = tcol("cd1_2");
   icd21    = tcol("cd2_1");
   icd22    = tcol("cd2_2");

   if(ins < 0)
      ins = tcol("naxis1");

   if(inl < 0)
      inl = tcol("naxis2");

   if(ifname < 0)
      ifname = tcol("file");

   if(icd11 >= 0 && icd12 >= 0  && icd21 >= 0  && icd12 >= 0)
      mode = CD;

   else if(icdelt1 >= 0 && icdelt2 >= 0  && icrota2 >= 0)
      mode = CDELT;

   else
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Not enough information to determine coverages (CDELTs or CD matrix)\"]\n");
      exit(1);
   }


   if(icntr   < 0
   || ictype1 < 0
   || ictype2 < 0
   || inl     < 0
   || ins     < 0
   || icrval1 < 0
   || icrval2 < 0
   || icrpix1 < 0
   || icrpix2 < 0
   || ifname  < 0)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Need columns: cntr ctype1 ctype2 nl ns crval1 crval2 crpix1 crpix2 cdelt1 cdelt2 crota2 fname (equinox optional)\"]\n");
      exit(1);
   }


   /******************************************************/
   /* Scan the table to get the true 'file' column width */
   /******************************************************/

   namelen = 0;

   while(1)
   {
      stat = tread();

      if(stat < 0)
	 break;

      strcpy(input.fname, fileName(tval(ifname)));

      if(strlen(input.fname) > namelen)
	 namelen = strlen(input.fname);
   }

   tseek(0);


   /*************************************/
   /* Write headers to the output files */
   /*************************************/

   if((fraw = (FILE *)fopen(rawimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         rawimg_file);
      exit(1);
   }

   fprintf(fraw, "\\datatype=fitshdr\n");

   if(iscale >= 0)
   {
      sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%10s|%%%ds|\n", namelen+2);

      fprintf(fraw, fmt,
	 "cntr",
	 "ctype1",
	 "ctype2",
	 "naxis1",
	 "naxis2",
	 "crval1",
	 "crval2",
	 "crpix1",
	 "crpix2",
	 "cdelt1",
	 "cdelt2",
	 "crota2",
	 "equinox",
	 "scale",
	 "file");

      fprintf(fraw, fmt,
	 "int",
	 "char",
	 "char",
	 "int",
	 "int",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "int",
	 "double",
	 "char");
   }
   else
   {
      sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%%ds|\n", namelen+2);


      fprintf(fraw, fmt,
	 "cntr",
	 "ctype1",
	 "ctype2",
	 "naxis1",
	 "naxis2",
	 "crval1",
	 "crval2",
	 "crpix1",
	 "crpix2",
	 "cdelt1",
	 "cdelt2",
	 "crota2",
	 "equinox",
	 "file");

      fprintf(fraw, fmt,
	 "int",
	 "char",
	 "char",
	 "int",
	 "int",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "double",
	 "int",
	 "char");
   }

   if((fproj = (FILE *)fopen(projimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         projimg_file);
      exit(1);
   }

   fprintf(fproj, "\\datatype=fitshdr\n");

   sprintf(fmt, "|%%5s|%%8s|%%8s|%%6s|%%6s|%%10s|%%10s|%%10s|%%10s|%%11s|%%11s|%%8s|%%7s|%%%ds|\n", namelen+2);

   fprintf(fproj, fmt,
      "cntr",
      "ctype1",
      "ctype2",
      "naxis1",
      "naxis2",
      "crval1",
      "crval2",
      "crpix1",
      "crpix2",
      "cdelt1",
      "cdelt2",
      "crota2",
      "equinox",
      "file");

   fprintf(fproj, fmt,
      "int",
      "char",
      "char",
      "int",
      "int",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "int",
      "char");


   if((fcorr = (FILE *)fopen(corrimg_file, "w+")) == (FILE *)NULL)
   {
      fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Invalid output metadata file: %s\"]\n",
         corrimg_file);
      exit(1);
   }

   fprintf(fcorr, "\\datatype=fitshdr\n");

   fprintf(fcorr, fmt,
      "cntr",
      "ctype1",
      "ctype2",
      "naxis1",
      "naxis2",
      "crval1",
      "crval2",
      "crpix1",
      "crpix2",
      "cdelt1",
      "cdelt2",
      "crota2",
      "equinox",
      "file");

   fprintf(fcorr, fmt,
      "int",
      "char",
      "char",
      "int",
      "int",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "double",
      "int",
      "char");


   /************************************************/
   /* Read the metadata and process each image WCS */
   /************************************************/

   namelen = 0;
   nimages = 0;
   ntotal  = 0;

   if(iscale >= 0)
      sprintf(rfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f %%10s %%%ds\n", namelen+2);
   else
      sprintf(rfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f %%%ds\n", namelen+2);

   sprintf(pfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f p%%%ds\n", namelen+2);

   sprintf(cfmt, " %%5d %%8s %%8s %%6d %%6d %%10.6f %%10.6f %%10.2f %%10.2f %%11.8f %%11.8f %%8.5f %%7.0f c%%%ds\n", namelen+2);

   while(1)
   {
      stat = tread();

      if(stat < 0)
	 break;
      
      ++ntotal;

      strcpy(input.ctype1, tval(ictype1));
      strcpy(input.ctype2, tval(ictype2));

      input.cntr      = atoi(tval(icntr));
      input.naxis1    = atoi(tval(ins));
      input.naxis2    = atoi(tval(inl));
      input.crpix1    = atof(tval(icrpix1));
      input.crpix2    = atof(tval(icrpix2));
      input.crval1    = atof(tval(icrval1));
      input.crval2    = atof(tval(icrval2));

      if(mode == CDELT)
      {
	 input.cdelt1    = atof(tval(icdelt1));
	 input.cdelt2    = atof(tval(icdelt2));
	 input.crota2    = atof(tval(icrota2));
      }
      else
      {
	 input.cd11      = atof(tval(icd11));
	 input.cd12      = atof(tval(icd12));
	 input.cd21      = atof(tval(icd21));
	 input.cd22      = atof(tval(icd22));
      }

      input.epoch     = 2000;

      strcpy(header, "");
      sprintf(temp, "SIMPLE  = T"                    ); stradd(header, temp);
      sprintf(temp, "BITPIX  = -64"                  ); stradd(header, temp);
      sprintf(temp, "NAXIS   = 2"                    ); stradd(header, temp);
      sprintf(temp, "NAXIS1  = %d",     input.naxis1 ); stradd(header, temp);
      sprintf(temp, "NAXIS2  = %d",     input.naxis2 ); stradd(header, temp);
      sprintf(temp, "CTYPE1  = '%s'",   input.ctype1 ); stradd(header, temp);
      sprintf(temp, "CTYPE2  = '%s'",   input.ctype2 ); stradd(header, temp);
      sprintf(temp, "CRVAL1  = %11.6f", input.crval1 ); stradd(header, temp);
      sprintf(temp, "CRVAL2  = %11.6f", input.crval2 ); stradd(header, temp);
      sprintf(temp, "CRPIX1  = %11.6f", input.crpix1 ); stradd(header, temp);
      sprintf(temp, "CRPIX2  = %11.6f", input.crpix2 ); stradd(header, temp);

      if(mode == CDELT)
      {
      sprintf(temp, "CDELT1  = %11.6f", input.cdelt1 ); stradd(header, temp);
      sprintf(temp, "CDELT2  = %11.6f", input.cdelt2 ); stradd(header, temp);
      sprintf(temp, "CROTA2  = %11.6f", input.crota2 ); stradd(header, temp);
      }
      else
      {
      sprintf(temp, "CD1_1   = %11.6f", input.cd11   ); stradd(header, temp);
      sprintf(temp, "CD1_2   = %11.6f", input.cd12   ); stradd(header, temp);
      sprintf(temp, "CD2_1   = %11.6f", input.cd21   ); stradd(header, temp);
      sprintf(temp, "CD2_2   = %11.6f", input.cd22   ); stradd(header, temp);
      }

      sprintf(temp, "EQUINOX = %d",     input.equinox); stradd(header, temp);
      sprintf(temp, "END"                            ); stradd(header, temp);
      
      if(iequinox >= 0)
	 input.equinox = atoi(tval(iequinox));

      strcpy(input.fname, fileName(tval(ifname)));

      if(iscale >= 0)
	 strcpy(scale, tval(iscale));

      if(strlen(input.fname) > namelen)
	 namelen = strlen(input.fname);

      if(debug)
      {
	 printf("Image header to wcsinit():\n%s\n", header);
	 fflush(stdout);
      }

      input.wcs = wcsinit(header);

      checkWCS(input.wcs, 0);
			     
      if(input.wcs == (struct WorldCoor *)NULL)
      {
	 fprintf(fstatus, "[struct stat=\"ERROR\", msg=\"Bad WCS for image %d\"]\n", 
	    nimages);
	 exit(1);
      }


      /***************************************************/
      /* Check the boundaries of the input image against */
      /* the output region of interest                   */
      /***************************************************/

      oxpixMin =  100000000;
      oxpixMax = -100000000;
      oypixMin =  100000000;
      oypixMax = -100000000;

      /* Check input left and right */

      for (j=0; j<input.naxis2+1; ++j)
      {
	 pix2wcs(input.wcs, 0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }

	 pix2wcs(input.wcs, input.naxis1+0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }
      }


      /* Check input top and bottom */

      for (i=0; i<input.naxis1+1; ++i)
      {
	 pix2wcs(input.wcs, i+0.5, 0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }

	 pix2wcs(input.wcs, i+0.5, input.naxis2+0.5, &xpos, &ypos);

	 convertCoordinates(input.sys, input.epoch, xpos, ypos,
			    output.sys, output.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(output.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(oxpix < oxpixMin) oxpixMin = oxpix;
	    if(oxpix > oxpixMax) oxpixMax = oxpix;
	    if(oypix < oypixMin) oypixMin = oypix;
	    if(oypix > oypixMax) oypixMax = oypix;
	 }
      }


      /***************************************************/
      /* Check the boundaries of the region of interest  */
      /* against the input image                         */
      /***************************************************/

      /* Check ouput left and right */

      for (j=0; j<output.wcs->nypix+1; ++j)
      {
	 pix2wcs(output.wcs, 0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(0.5   < oxpixMin) oxpixMin = 0.5;
	    if(0.5   > oxpixMax) oxpixMax = 0.5;

	    if(j+0.5 < oypixMin) oypixMin = j+0.5;
	    if(j+0.5 > oypixMax) oypixMax = j+0.5;
	 }

	 pix2wcs(output.wcs, output.wcs->nxpix+0.5, j+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(output.wcs->nxpix+0.5 < oxpixMin) oxpixMin = output.wcs->nxpix+0.5;
	    if(output.wcs->nxpix+0.5 > oxpixMax) oxpixMax = output.wcs->nxpix+0.5;

	    if(j+0.5 < oypixMin) oypixMin = j+0.5;
	    if(j+0.5 > oypixMax) oypixMax = j+0.5;
	 }
      }


      /* Check input top and bottom */

      for (i=0; i<output.wcs->nxpix+1; ++i)
      {
	 pix2wcs(output.wcs, i+0.5, 0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(i+0.5 < oxpixMin) oxpixMin = i+0.5;
	    if(i+0.5 > oxpixMax) oxpixMax = i+0.5;

	    if(0.5   < oypixMin) oypixMin = 0.5  ;
	    if(0.5   > oypixMax) oypixMax = 0.5  ;
	 }

	 pix2wcs(output.wcs, i+0.5, output.wcs->nypix+0.5, &xpos, &ypos);

	 convertCoordinates(output.sys, output.epoch, xpos, ypos,
			     input.sys,  input.epoch, &lon, &lat, 0.0);
	 
	 wcs2pix(input.wcs, lon, lat, &oxpix, &oypix, &offscl);

	 if(!offscl)
	 {
	    if(i+0.5 < oxpixMin) oxpixMin = i+0.5;
	    if(i+0.5 > oxpixMax) oxpixMax = i+0.5;

	    if(output.wcs->nypix+0.5 < oypixMin) oypixMin = output.wcs->nypix+0.5;
	    if(output.wcs->nypix+0.5 > oypixMax) oypixMax = output.wcs->nypix+0.5;
	 }
      }

      if(oxpixMax < oxpixMin) continue;
      if(oypixMax < oypixMin) continue;


      /* Remove any possible compression extension */

      strcpy(ofile, input.fname);

      if(strlen(ofile) > 3 && strcmp(ofile+strlen(ofile)-3, ".gz") == 0)
	 ofile[strlen(ofile)-3] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, ".Z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, ".z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".zip") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 2 && strcmp(ofile+strlen(ofile)-2, "-z") == 0)
	 ofile[strlen(ofile)-2] = '\0';

      else if(strlen(ofile) > 3 && strcmp(ofile+strlen(ofile)-3, "-gz") == 0)
	 ofile[strlen(ofile)-3] = '\0';


      /* Make sure the extension is ".fits" */

      if(strlen(ofile) > 5 && strcmp(ofile+strlen(ofile)-5, ".fits") == 0)
	 ofile[strlen(ofile)-5] = '\0';

      else if(strlen(ofile) > 5 && strcmp(ofile+strlen(ofile)-5, ".FITS") == 0)
	 ofile[strlen(ofile)-5] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".fit") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".FIT") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".fts") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      else if(strlen(ofile) > 4 && strcmp(ofile+strlen(ofile)-4, ".FTS") == 0)
	 ofile[strlen(ofile)-4] = '\0';

      strcat(ofile, ".fits");

      if(iscale >= 0)
      {
	 fprintf(fraw, rfmt,
	   nimages+1,
	   output.wcs->ctype[0],
	   output.wcs->ctype[1],
	   oxpixMax - oxpixMin + 1,
	   oypixMax - oypixMin + 1,
	   output.wcs->crval[0],
	   output.wcs->crval[1],
	   output.wcs->crpix[0] - oxpixMin,
	   output.wcs->crpix[1] - oypixMin,
	   output.wcs->cdelt[0],
	   output.wcs->cdelt[1],
	   output.wcs->rot,
	   output.epoch,
	   scale,
	   ofile);
      }
      else
      {
	 fprintf(fraw, rfmt,
	   nimages+1,
	   output.wcs->ctype[0],
	   output.wcs->ctype[1],
	   oxpixMax - oxpixMin + 1,
	   oypixMax - oypixMin + 1,
	   output.wcs->crval[0],
	   output.wcs->crval[1],
	   output.wcs->crpix[0] - oxpixMin,
	   output.wcs->crpix[1] - oypixMin,
	   output.wcs->cdelt[0],
	   output.wcs->cdelt[1],
	   output.wcs->rot,
	   output.epoch,
	   ofile);
      }

      fprintf(fproj, pfmt,
	nimages+1,
	output.wcs->ctype[0],
	output.wcs->ctype[1],
	oxpixMax - oxpixMin + 1,
	oypixMax - oypixMin + 1,
	output.wcs->crval[0],
	output.wcs->crval[1],
	output.wcs->crpix[0] - oxpixMin,
	output.wcs->crpix[1] - oypixMin,
	output.wcs->cdelt[0],
	output.wcs->cdelt[1],
	output.wcs->rot,
	output.epoch,
	ofile);

      fprintf(fcorr, cfmt,
	nimages+1,
	output.wcs->ctype[0],
	output.wcs->ctype[1],
	oxpixMax - oxpixMin + 1,
	oypixMax - oypixMin + 1,
	output.wcs->crval[0],
	output.wcs->crval[1],
	output.wcs->crpix[0] - oxpixMin,
	output.wcs->crpix[1] - oypixMin,
	output.wcs->cdelt[0],
	output.wcs->cdelt[1],
	output.wcs->rot,
	output.epoch,
	ofile);

      ++nimages;
   }


   fclose(fraw);
   fclose(fproj);
   fclose(fcorr);

   fprintf(fstatus, "[struct stat=\"OK\", count=\"%d\", total=\"%d\"]\n", 
      nimages, ntotal);
   fflush(stdout);

   exit(0);
}
Beispiel #21
0
/*
 * Assumes pipe is buffered at least 257 characters,
 * so both sides can send and then receive.
 */
int
banner(Replica *r, char *name)
{
	int i;
	char c, *p;
	char buf[257];

	dbg(DbgRpc, "sending tracmd\n");
	qlock(&r->rlock);
	qlock(&r->wlock);
	/* both sides send tracmd */
	if(twrite(r->wfd, tracmd, sizeof tracmd-1) < 0
	|| twflush(r->wfd) == -1){
		werrstr("writing banner: %r");
	err:
		qunlock(&r->wlock);
		qunlock(&r->rlock);
		return -1;
	}
	dbg(DbgRpc, "waiting for tracmd\n");
	while((p = rdln(r->rfd)) != nil){
		if(strcmp(tracmd, p) == 0)
			break;
		if(name)
			fprint(2, "%s# %s", name, p);
	}
	if(p == nil){
		werrstr("did not receive initial banner");
		goto err;
	}

	dbg(DbgRpc, "sending antissh\n");
	/* both sides send \n~?\n~.\n */
	if(twrite(r->wfd, antissh, sizeof antissh-1) < 0
	|| twflush(r->wfd) == -1){
		werrstr("writing antissh: %r");
		goto err;
	}
	dbg(DbgRpc, "waiting for antissh\n");
	if(readln(r->rfd, "\n")<0 || readln(r->rfd, "~?\n")<0 || readln(r->rfd, "~.\n") < 0){
		werrstr("corrupt anti-ssh banner");
		goto err;
	}

	dbg(DbgRpc, "sending byte map\n");
	/* both sides send 0x00, 0x01, ..., 0xFF, 0x00 */
	/* the second 0x00 gives us a way to notice 0xFF being dropped */
	for(i=0; i<257; i++)
		buf[i] = i;
	if(twrite(r->wfd, buf, sizeof buf) < 0 || twflush(r->wfd) == -1){
		werrstr("short channel test write: %r");
		goto err;
	}
	
	dbg(DbgRpc, "receiving byte map\n");
	/* could be more efficient but doesn't matter */
	for(i=0; i < sizeof buf; i++){
		if(tread(r->rfd, &c, 1) != 1){
			werrstr("8-bit test: expected 0x%x, got eof", buf[i]);
			goto err;
		}
		if(c != buf[i]){
			werrstr("8-bit test: expected 0x%x, got 0x%x", buf[i], c);
			goto err;
		}
	}
//fprint(2, "%s: pass\n", argv0);
	qunlock(&r->wlock);
	qunlock(&r->rlock);
	return 0;
}