示例#1
0
文件: parse.c 项目: bbidulock/adwm
static Bool
parsekey(const char *s, const char *e, Key *k)
{
	const char *p, *q;

	XPRINTF("Parsing key from: '%s'\n", s);
	for (p = s; p < e && (isalnum(*p) || isblank(*p) || *p == '_'); p++) ;
	if (p < e && *p == '+') {
		k->mod = parsemod(s, p);
		p++;
	} else
		p = s;
	for (q = p; q < e && (isalnum(*q) || isblank(*q) || *q == '_'); q++) ;
	if (q < e && *q != '=')
		q = e;
	if ((k->keysym = parsesym(p, q)) == NoSymbol) {
		EPRINTF("Failed to parse symbol from '%s' to '%s'\n", p, q);
		return False;
	}
	if (q < e)
		k->arg = parsearg(q + 1, e);
	else if (k->arg)
		k->arg = strdup(k->arg);
	return True;
}
示例#2
0
int set_cell(char *cell_id, char *cell_str, size_t size)
{
    if (cell_str == NULL || cgc_strlen(cell_str) == 0 || cgc_strlen(cell_str) >= size)
        return -1;

    cell_t *cell = get_cell(cell_id);
    if (cell == NULL)
        return -1;

    if (cell->cell_type != UNUSED) {
        free(cell->str);
        cell->str = NULL;
        cell->cell_type = UNUSED;
        cell->formula = NULL;
    }

    cell->str = malloc(cgc_strlen(cell_str) + 1);
    if(cell->str == NULL)
        return -1;

    strcpy(cell->str, cell_str);
    if (cgc_strlen(cell_str) >= 2 && cell_str[0] == '=') {
        cell->formula = &cell->str[1];
        cell->cell_type = FORMULA;
    } else {
        // Non functions can only be a double or a string
        cell->cell_type = parsearg(cell->str);
        if (cell->cell_type != DOUBLE)
            cell->cell_type = STRING;
    }

    return 0;
}
示例#3
0
文件: main.c 项目: darksoul42/bitrig
int
main(int argc, char *argv[])
{
	f = -1;

	if (pledge("stdio rpath wpath cpath dns inet", NULL) == -1)
		err(1, "pledge");

	/* set default transfer mode */
	strlcpy(mode, "netascii", sizeof(mode));

	/* set peer if given */
	if (argc > 1)
		parsearg(argc, argv);

	/* catch SIGINT */
	signal(SIGINT, intr);

	/* allocate memory for packets */
	if ((ackbuf = malloc(SEGSIZE_MAX + 4)) == NULL)
		err(1, "malloc");

	/* command prompt */
	command();

	return (0);
}
示例#4
0
static int eval_function(operator_t *op, stack_t **values, char *val_str, size_t size)
{
    if (op == NULL || val_str == NULL || size <= 2)
        return -1;

    double val = 0.0;
    char *arg;
    char *op_name = (char *) op->name;
    size_t i, num_args = 0;
    int is_bad_formula = 0;
    operator_t *nested_op;

    stack_t *args = NULL;
    if (is_arg_arithmetic(op_name)) {
        num_args = 2;
    } else {
        char *arg_count = pop_copy(values);
        if (arg_count == NULL)
            goto error;

        num_args = strtol(arg_count, NULL, 10);
        free(arg_count);
    }

    for (i = 0; i < num_args; i++) {
        arg = pop_copy(values);
        //printf("arg[%d]==%s\n", i, arg);
        if (parsearg(arg) == FUNCTION) {
            nested_op = get_op(arg);
            free(arg);
            if (eval_function(nested_op, values, val_str, size) == 0)
                push_copy(&args, val_str, size);
            else
                goto error;

        } else if (push(&args, arg) != 0) {
            goto error;
        }
    }

    val = op->function(&args, &is_bad_formula);
    if (is_bad_formula)
        goto error;

    if (ftoa(val, val_str, size) == NULL)
        goto error;

    return 0;

error:
    clear_stack(&args);
    return -1;
}
示例#5
0
int
main(int argc, char **argv)
{
  int i;
  cpu_set_t cpuset;
  mem_bench_info_t mbinfo;

  if (numa_available() == -1){
    fprintf(stderr, "numa functions aren't available\n");
    exit(EXIT_FAILURE);
  }

  parsearg(argc, argv);
  mbinfo.working_size = option.access_size;

  // set affinity
  CPU_ZERO(&cpuset);
  CPU_SET(option.usecore, &cpuset);
  sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpuset);

  // read benchmark
  printf("===========================================\n"
         "memory benchmark\n"
         "===========================================\n");
  for (i = 0; i <= numa_max_node(); i++) {
    mbinfo.destnode = i;
    mbinfo.pc.ops = 0;
    mbinfo.pc.clk = 0;
    numa_membench(&mbinfo);
    printf("memory_alloc_node\t%d\n"
           "access_size\t%ld\n"
           "total_ops\t%ld\n"
           "total_clk\t%ld\n"
           "exec_time_sec\t%.9f\n"
           "ops_per_sec\t%e\n"
           "clk_per_op\t%e\n"
           "usec_per_op\t%f\n",
           i,
           mbinfo.working_size,
           mbinfo.pc.ops,
           mbinfo.pc.clk,
           mbinfo.pc.wallclocktime,
           mbinfo.pc.ops / mbinfo.pc.wallclocktime,
           ((double)mbinfo.pc.clk) / mbinfo.pc.ops,
           mbinfo.pc.wallclocktime * 1000000 / mbinfo.pc.ops
           );
  }

  return 0;
}
示例#6
0
static queue_t *infixtorpn(char *infix, size_t size)
{
    /* Use RPN */
    int is_mismatched = 0;
    int func_size = 16;
    int func_idx = -1;
    char *formula = malloc(size);
    int *func_args = malloc(func_size * sizeof(int));

    char *delims = "():,+-*/";
    char *arg, *iter;
    char delim;
    char arith_op[2] = {'\0', '\0'};
    char *value;
    cell_type_e arg_type;
    stack_t *operators = NULL;
    queue_t *output_q = NULL;

    cgc_memcpy(formula, infix, size);
    if (sanitize_formula(formula, size) != 0)
        goto cleanup;

    arg = iter = formula;
    size_t i = 0;
    char prev_char = 0;
    while ( i++ < size) {
        if (strchr(delims, *iter) == NULL && *iter != '\0') {
            prev_char = *iter;
            iter++;
            continue;
        } else if (strchr(delims, *iter) != NULL) {
            if (*iter == '-') {
                if(i <= 1 || (prev_char != ')' && (prev_char < '0' || prev_char > '9'))) {
                    prev_char = *iter;
                    iter++;
                    continue;
                }
            }
        }

        prev_char = *iter;
        delim = *iter;
        *iter = '\0';
        arg_type = parsearg(arg);
        switch (arg_type) {
            case DOUBLE:
            case CELL_ID:
                enqueue_copy(&output_q, arg, cgc_strlen(arg) + 1);
                break;
            case FUNCTION:
#ifdef PATCHED
                if(func_idx == func_size-1) {
#else
                if(func_idx == func_size) {
#endif
                    func_size *= 2;
                    int *temp = realloc(func_args, func_size * sizeof(int));
                    if (temp == NULL)
                        goto error;
                    func_args = temp;
                }

                func_args[++func_idx] = 0;
                push_copy(&operators, arg, cgc_strlen(arg) + 1);
                break;
            case BAD_CELL:
                break;
            default:
                goto error;
        }

        is_mismatched = 0;
        switch(delim) {
            case '(':
                push_copy(&operators, "(", cgc_strlen("(") + 1);
                break;
            case ')':
                is_mismatched = 1;
                while (operators != NULL) {
                    if (strcmp(peek_top(operators), "(") == 0) {
                        value = pop_copy(&operators);
                        free(value);
                        is_mismatched = 0;
                        break;
                    } else {
                        enqueue(&output_q, pop_copy(&operators));
                    }
                }

                // handle parens without any operator
                if (peek_top(operators) == NULL || func_idx < 0)
                    break;

                char num_args_str[16];
                if(strchr(delims, peek_top(operators)[0]) != NULL) {
                    break;
                } else if (parsearg(peek_top(operators)) == FUNCTION) {
                    enqueue_copy(&output_q, itoa(func_args[func_idx--] + 1, num_args_str,
                                    sizeof(num_args_str)), sizeof(num_args_str));
                    enqueue(&output_q, pop_copy(&operators));
                }

                break;
            case ',':
                is_mismatched = 1;
                while (operators != NULL) {
                    if (strcmp(peek_top(operators), "(") == 0) {
                        if (func_idx >= 0)
                            func_args[func_idx]++;
                        is_mismatched = 0;
                        break;
                    } else {
                        enqueue(&output_q, pop_copy(&operators));
                    }
                }
                break;
            case '+':
            case '-':
                //TODO - FIXME - precedence is broken
                //TODO - FIXME - negative is still broken
                // 4/5-5
                arith_op[0] = delim;
                while (operators != NULL) {
                    if (strcmp(peek_top(operators), "-") == 0 || strcmp(peek_top(operators), "+") == 0 ||
                        strcmp(peek_top(operators), "+") == 0 || strcmp(peek_top(operators), "/") == 0)
                        enqueue(&output_q, pop_copy(&operators));
                    else
                        break;
                }

                push_copy(&operators, arith_op, cgc_strlen(arith_op)+1);
                break;
            case '*':
            case '/':
                //TODO - FIXME - precedence is broken
                arith_op[0] = delim;
                while (operators != NULL) {
                    if (strcmp(peek_top(operators), "/") == 0 || strcmp(peek_top(operators), "*") == 0)
                        enqueue(&output_q, pop_copy(&operators));
                    else
                        break;

                }

                push_copy(&operators, arith_op, cgc_strlen(arith_op)+1);
                break;

            case '\0':
                goto finish;
            default:
                goto error;
        }

        if (is_mismatched)
            goto error;

        arg = ++iter;
    }
finish:

    while (operators != NULL) {
        if (strcmp(peek_top(operators), "(") == 0 || strcmp(peek_top(operators), ")") == 0)
            goto error;

        enqueue(&output_q, pop_copy(&operators));
    }

    goto cleanup;

error:
    clear_queue(&output_q);
    clear_stack(&operators);

cleanup:
    free(formula);
    free(func_args);
    return output_q;
}
示例#7
0
static double eval_formula(char *formula, int *is_bad_formula, stack_t **cir_ref, int id)
{
    char val_str[TMP_STR_SIZE];
    char tmp_id_str[TMP_STR_SIZE];
    size_t size = TMP_STR_SIZE;
    double val = 0.0;
    double result = 0.0;
    *is_bad_formula = 0;
    cell_type_e cell_type;
    char *arg;

    if(itoa(id, tmp_id_str, size) == NULL)
        goto error;

    push_copy(cir_ref, tmp_id_str, cgc_strlen(tmp_id_str) + 1);
    queue_t *rpn = infixtorpn(formula, cgc_strlen(formula) + 1);

    queue_t *args = NULL;
    stack_t *values = NULL;

    stack_t *tmp = NULL;
    operator_t *op = NULL;

    while (rpn != NULL) {
        arg = dequeue_copy(&rpn);
        cell_type = parsearg(arg);
        switch(cell_type) {
            case DOUBLE:
                push(&values, arg);
                break;
            case FUNCTION:
                op = get_op(arg);
                if (eval_function(op, &values, val_str, size) == -1) {
                    goto error;
                }

                push_copy(&values, val_str, size);
                break;
            case CELL_ID:
                tmp = *cir_ref;
                cell_t *cell = get_cell(arg);
                if(cell == NULL)
                    goto error;

                while (tmp != NULL) {
                    if(itoa(cell->id, tmp_id_str, size) == NULL)
                        goto error;

                    if (memcmp(tmp->data, tmp_id_str, cgc_strlen(tmp->data) + 1) == 0)
                        goto error; //Circular reference
                    tmp = tmp->next;
                }

                if (cell->cell_type == UNUSED) {
                    push_copy(&values, "0", sizeof("0"));
                } else if (cell->cell_type == DOUBLE) {
                    push_copy(&values, cell->str, cgc_strlen(cell->str) + 1);
                } else if(cell->cell_type == FORMULA) {
                    val = eval_formula(cell->formula, is_bad_formula, cir_ref, cell->id);
                    if(*is_bad_formula)
                        goto error;

                    ftoa(val, val_str, size);
                    push_copy(&values, val_str, size);
                } else {
                    goto error;
                }

                break;
            default:
                goto error;
        }
    }

    char *result_str = pop_copy(&values);
    if (values != NULL)
        goto error;

    result = atof(result_str, size, is_bad_formula);
    if (*is_bad_formula)
        goto error;

    goto cleanup;

error:
    *is_bad_formula = 1;
    val = 0.0;
    clear_queue(&rpn);
    clear_queue(&args);
    clear_stack(&values);
cleanup:
    free(pop_copy(cir_ref));

    return result;
}
示例#8
0
int dstrvsprintf(dstring_t str, const char *format, va_list args) {

   /* flags containing information about a single conversion specifier */
   struct specifier conversion;

   /* keeps track of our position in format */
   char *curpos;
   char *end;

   /* keeps track of the return value of append* functions */
   int r;

   curpos = (char *)format;

   /* make sure the string is empty */
   if (dstrlen(str) != 0) {
      dstrtrunc(str, 0);
      if (dstrerrno != DSTR_SUCCESS) {
         return -1;
      }
   }

   while (*curpos != '\0') {

      /* possible conversion specifier */
      if ('%' == *curpos) {

         end = parsearg(curpos, &conversion);
         if (dstrerrno != DSTR_SUCCESS) {
            return -1;
         }

         /* it wasn't a valid specifier */
         if (end == curpos) {
            dstrinsertc(str, dstrlen(str), *curpos);
            if (dstrerrno != DSTR_SUCCESS) {
               return -1;
            }
            curpos++;
            continue;
         }

         /* it was a valid specifier */
         else {
            /* make sure we update curpos */
            curpos = end;
            switch(CONVERSIONBITS & conversion.format) {
               case PERCENT:
                  dstrinsertc(str, dstrlen(str) - 1, '%');
                  if (DSTR_SUCCESS != dstrerrno) {
                     return -1;
                  }
                  break;

               case SIGNED_INT:

                  if (conversion.format & LONG) {
                     r = appendsignedint(str, conversion,
                            va_arg(args, long int), 10);
                  } else if (conversion.format & SHORT) {
                     r = appendsignedint(str, conversion,
                            (long int)va_arg(args, int), 10);
                  } else {
示例#9
0
int main(int argc, const char * const *argv)
{
  int help = 0, version = 0, hang = 0, prefix = -1, repeat = 0, suffix = -1,
      Tab = 1, width = 72, body = 0, cap = 0, div = 0, Err = 0, expel = 0,
      fit = 0, guess = 0, invis = 0, just = 0, last = 0, quote = 0, Report = 0,
      touch = -1;
  int prefixbak, suffixbak, c, sawnonblank, oweblank, n, i, afp, fs;
  charset *bodychars = NULL, *protectchars = NULL, *quotechars = NULL;
  char *parinit = NULL, *arg, **inlines = NULL, **endline, **firstline, *end,
       **nextline, **outlines = NULL, **line;
  const char *env, * const whitechars = " \f\n\r\t\v";
  errmsg_t errmsg = { '\0' };
  lineprop *props = NULL, *firstprop, *nextprop;
  FILE *errout;

/* Process environment variables: */

  env = getenv("PARBODY");
  if (!env) env = "";
  bodychars = parsecharset(env,errmsg);
  if (*errmsg) {
    help = 1;
    goto parcleanup;
  }

  env = getenv("PARPROTECT");
  if (!env) env = "";
  protectchars = parsecharset(env,errmsg);
  if (*errmsg) {
    help = 1;
    goto parcleanup;
  }

  env = getenv("PARQUOTE");
  if (!env) env = "> ";
  quotechars = parsecharset(env,errmsg);
  if (*errmsg) {
    help = 1;
    goto parcleanup;
  }

  env = getenv("PARINIT");
  if (env) {
    parinit = malloc((strlen(env) + 1) * sizeof (char));
    if (!parinit) {
      strcpy(errmsg,outofmem);
      goto parcleanup;
    }
    strcpy(parinit,env);
    arg = strtok(parinit,whitechars);
    while (arg) {
      parsearg(arg, &help, &version, bodychars, protectchars,
               quotechars, &hang, &prefix, &repeat, &suffix, &Tab,
               &width, &body, &cap, &div, &Err, &expel, &fit, &guess,
               &invis, &just, &last, &quote, &Report, &touch, errmsg );
      if (*errmsg || help || version) goto parcleanup;
      arg = strtok(NULL,whitechars);
    }
    free(parinit);
    parinit = NULL;
  }

/* Process command line arguments: */

  while (*++argv) {
    parsearg(*argv, &help, &version, bodychars, protectchars,
             quotechars, &hang, &prefix, &repeat, &suffix, &Tab,
             &width, &body, &cap, &div, &Err, &expel, &fit, &guess,
             &invis, &just, &last, &quote, &Report, &touch, errmsg );
    if (*errmsg || help || version) goto parcleanup;
  }

  if (Tab == 0) {
    strcpy(errmsg, "<Tab> must not be 0.\n");
    goto parcleanup;
  }

  if (touch < 0) touch = fit || last;
  prefixbak = prefix;
  suffixbak = suffix;

/* Main loop: */

  for (sawnonblank = oweblank = 0;  ;  ) {
    for (;;) {
      c = getchar();
      if (expel && c == '\n') {
        oweblank = sawnonblank;
        continue;
      }
      if (csmember((char) c, protectchars)) {
        sawnonblank = 1;
        if (oweblank) {
          putchar('\n');
          oweblank = 0;
        }
        while (c != '\n' && c != EOF) {
          putchar(c);
          c = getchar();
        }
      }
      if (c != '\n') break;
      putchar(c);
    }
    if (c == EOF) break;
    ungetc(c,stdin);

    inlines =
      readlines(&props, protectchars, quotechars, Tab, invis, quote, errmsg);
    if (*errmsg) goto parcleanup;

    for (endline = inlines;  *endline;  ++endline);
    if (endline == inlines) {
      free(inlines);
      inlines = NULL;
      continue;
    }

    sawnonblank = 1;
    if (oweblank) {
      putchar('\n');
      oweblank = 0;
    }

    delimit((const char * const *) inlines,
            (const char * const *) endline,
            bodychars, repeat, body, div, 0, 0, props);

    if (expel)
      marksuperf((const char * const *) inlines,
                 (const char * const *) endline, props);

    firstline = inlines, firstprop = props;
    do {
      if (isbodiless(firstprop)) {
        if (!isinvis(firstprop) && !(expel && issuperf(firstprop))) {
          for (end = *firstline;  *end;  ++end);
          if (!repeat  ||  firstprop->rc == ' ' && !firstprop->s) {
            while (end > *firstline && end[-1] == ' ') --end;
            *end = '\0';
            puts(*firstline);
          }
          else {
            n = width - firstprop->p - firstprop->s;
            if (n < 0) {
              sprintf(errmsg,impossibility,5);
              goto parcleanup;
            }
            printf("%.*s", firstprop->p, *firstline);
            for (i = n;  i;  --i)
              putchar(firstprop->rc);
            puts(end - firstprop->s);
          }
        }
        ++firstline, ++firstprop;
        continue;
      }

      for (nextline = firstline + 1, nextprop = firstprop + 1;
           nextline < endline && !isbodiless(nextprop) && !isfirst(nextprop);
           ++nextline, ++nextprop);

      prefix = prefixbak, suffix = suffixbak;
      setaffixes((const char * const *) firstline,
                 (const char * const *) nextline, firstprop, bodychars,
                 quotechars, hang, body, quote, &afp, &fs, &prefix, &suffix);
      if (width <= prefix + suffix) {
        sprintf(errmsg,
                "<width> (%d) <= <prefix> (%d) + <suffix> (%d)\n",
                width, prefix, suffix);
        goto parcleanup;
      }

      outlines =
        reformat((const char * const *) firstline,
                 (const char * const *) nextline,
                 afp, fs, hang, prefix, suffix, width, cap,
                 fit, guess, just, last, Report, touch, errmsg);
      if (*errmsg) goto parcleanup;

      for (line = outlines;  *line;  ++line)
        puts(*line);

      freelines(outlines);
      outlines = NULL;

      firstline = nextline, firstprop = nextprop;
    } while (firstline < endline);

    freelines(inlines);
    inlines = NULL;

    free(props);
    props = NULL;
  }

parcleanup:

  if (bodychars) freecharset(bodychars);
  if (protectchars) freecharset(protectchars);
  if (quotechars) freecharset(quotechars);
  if (parinit) free(parinit);
  if (inlines) freelines(inlines);
  if (props) free(props);
  if (outlines) freelines(outlines);

  errout = Err ? stderr : stdout;
  if (*errmsg) fprintf(errout, "par error:\n%.*s", errmsg_size, errmsg);
  if (version) fputs("par 1.50\n",errout);
  if (help)    fputs(usagemsg,errout);

  return *errmsg ? EXIT_FAILURE : EXIT_SUCCESS;
}
示例#10
0
文件: imcio2a.c 项目: eterps/pwrake
int main(int argc,char *argv[])
{
#define NOT_REPLACE -999999.0
  struct  imh	imhin={""}, imhout={""};
  struct  icom	icomin={0}, icomout={0};
  char	fnamin[BUFSIZ]="", fnamout[BUFSIZ]="";
  char temp[BUFSIZ];
  FILE	*fp=NULL, *fp2=NULL;

  float *dp, *dpout;
  float *dpybin,*dpxbin;
  int *ndp;
  int	ix,iy;

  int pixignr=INT_MIN;
  float   rplc_ignor=NOT_REPLACE;
  int maxadd=-1;
  float bzero=0.,bscale=1.;

/*  int pixoff; */
  int  u2off;
  int iouty, ioutx, i, NBINX=1, NBINY=1, NBIN=1;
  int  ymin=0, ymax=INT_MAX;
  int  xmin=0, xmax=INT_MAX;
  char dtype[80]="\0";
  int fitsdtype;
  float fitsmax;

  char modename[20]="";

  int pixoff;

  int n0;
  int nline=-1;

  int xshift=0,yshift=0;
  float vxref=FLT_MAX,vyref=FLT_MAX;

  MOSMODE mosmode=NODIST_NOADD;
  /*
    int dist_clip=0,dist_flux=0,dist_peak=0,dist_add=0,
    dist_med=0, nodist_noadd=0, const_add=0;
  */
  int addorghead=0;
  float vxoff,vyoff;
  int nfrm;

  float sigmaf=0.16,nsigma=3.0;
  int meanmin=0,clipmin=3;

  getargopt opts[30];
  char *files[3]={NULL};
  int n=0;
  int helpflag;



  /*
   * ... Open Input
   */

  files[0]=fnamin;
  files[1]=fnamout;


  setopts(&opts[n++],"-maxadd=", OPTTYP_INT , &maxadd,"(mos)max number of coadd");
  setopts(&opts[n++],"-nline=", OPTTYP_INT , &nline,"(mos)y-width of buffering");

  setopts(&opts[n++],"-nodist_noadd", OPTTYP_FLAG , &mosmode,"(mos)quick mode (default)",NODIST_NOADD);

  setopts(&opts[n++],"-dist_add", OPTTYP_FLAG , &mosmode,"(mos)bilinear weighted mean",DIST_ADD);
  setopts(&opts[n++],"-dist_med", OPTTYP_FLAG , &mosmode,"(mos)bilinear weighted median",DIST_MED);
  setopts(&opts[n++],"-const_add", OPTTYP_FLAG , &mosmode,"(mos)mean of at least maxadd images or blank",CONST_ADD);
  setopts(&opts[n++],"-dist_clip", OPTTYP_FLAG , &mosmode,"(mos)clip mean mode(tesing)",DIST_CLIP_ADD);
  setopts(&opts[n++],"-dist_flux", OPTTYP_FLAG , &mosmode,"(mos)flux map mode(testing)",DIST_FLUX);
  setopts(&opts[n++],"-dist_peak", OPTTYP_FLAG , &mosmode,"(mos)outlyer mode(testing)",DIST_PEAK);


  setopts(&opts[n++],"-vxref=", OPTTYP_FLOAT , &vxref,"(mos) reference pixel x(default: not used (automatic))");
  setopts(&opts[n++],"-vyref=", OPTTYP_FLOAT , &vyref,"(mos) reference pixel y(default: not used(automacic))");
  setopts(&opts[n++],"-addorghead", OPTTYP_FLAG , &addorghead,"(mos) Add original header of reference (default:no)",1);

  setopts(&opts[n++],"-sigmaf=", OPTTYP_FLOAT , &sigmaf,"(mos/clip)sigma estimate fraction (default:0.160)");
  setopts(&opts[n++],"-nsigma=", OPTTYP_FLOAT , &nsigma,"(mos/clip)clipping sigma factor(default:3.0)");
  setopts(&opts[n++],"-clipmin=", OPTTYP_INT , &clipmin,"(mos/clip)minimum # of images for clipping (default:3)");
  setopts(&opts[n++],"-meanmin=", OPTTYP_INT , &meanmin,"(mos/clip)minimum # of images for taking clipped mean(default:not set)");


  setopts(&opts[n++],"-ymin=", OPTTYP_INT , &ymin,"ymin (default:0)");
  setopts(&opts[n++],"-ymax=", OPTTYP_INT , &ymax,"ymax (default:npy-1)");
  setopts(&opts[n++],"-xmin=", OPTTYP_INT , &xmin,"xmin (default:0)");
  setopts(&opts[n++],"-xmax=", OPTTYP_INT , &xmax,"xmax (default:npx-1");

  setopts(&opts[n++],"-bin=", OPTTYP_INT , &NBIN,"binning size(default:1)");
  setopts(&opts[n++],"-binx=", OPTTYP_INT , &NBINX,"binning size(default:1)");
  setopts(&opts[n++],"-biny=", OPTTYP_INT , &NBINY,"binning size(default:1)");

  setopts(&opts[n++],"-bzero=", OPTTYP_FLOAT , &bzero,
	  "bzero");
  setopts(&opts[n++],"-bscale=", OPTTYP_FLOAT , &bscale,
	  "bscale");
  setopts(&opts[n++],"-dtype=", OPTTYP_STRING , dtype,
	  "datatyp(FITSFLOAT,FITSSHORT...)");
  setopts(&opts[n++],"-pixignr=", OPTTYP_FLOAT , &rplc_ignor,
	  "pixignr value");
  setopts(&opts[n++],"-ignor=", OPTTYP_FLOAT , &rplc_ignor,
	  "pixignr value");

  setopts(&opts[n++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);

  if(fnamout[0]=='\0')
   {
      fprintf(stderr,"Error: No input file specified!!\n");
      helpflag=1;
    }
  if(helpflag==1)
    {
      print_help("Usage: imcio2 <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  switch(mosmode)
    {
    case DIST_CLIP_ADD:
      sprintf(modename,"dist_clip");
      imc_mos_set_clip_param(nsigma,sigmaf,clipmin,meanmin);
      break;
    case CONST_ADD:
      if (maxadd<=0) maxadd=1;
      sprintf(modename,"const_add %d",maxadd);
      break;
    case DIST_FLUX:
      sprintf(modename,"dist_flux");
      break;
    case DIST_PEAK:
      sprintf(modename,"dist_peak");
      break;
    case DIST_ADD:
      sprintf(modename,"dist_add");
      break;
    case DIST_MED:
      sprintf(modename,"dist_med");
      break;
    case NODIST_NOADD:
      sprintf(modename,"dist_noadd");
      break;
    default:
      mosmode=NODIST_NOADD;
      sprintf(modename,"nodist_noadd");
      break;
    }
  imc_mos_set_default_add( mosmode );
  if (maxadd>0)
    {
      imc_mos_set_default_maxadd( maxadd );
      printf(" Max # of frames is %d\n", maxadd);
    }

  if(nline<0)
    nline=200;
  
  imc_mos_set_nline(nline);
  imc_mos_set_nline_l(nline);
  
  if( fnamin[0]=='\0' ) 
    {
      (void) printf("\n input IRAF/FITS/MOS file name = " );
      (void) fgets( temp,BUFSIZ,stdin );
      sscanf(temp,"%s",fnamin);
    }
  else
    (void)printf("\n Input = %s\n",fnamin );
  

  if( (fp = imropen ( fnamin, &imhin, &icomin )) == NULL ) 
    {
      exit(-1);
    }

  /* testing */
  if (imhin.dtype==DTYPEMOS)
    {
      if (vxref!=FLT_MAX && vyref!=FLT_MAX)
	{
	  printf("vxref:%f vyref:%f\n",vxref,vyref);
	  imc_mos_set_shift(&imhin, -vxref, -vyref);
	}
    }

  u2off=imget_u2off( &imhin );
  (void) printf("Offset = %d\n",u2off);
  pixignr=imget_pixignr( &imhin );
  (void) printf("Pixignr= %d\n",pixignr);

  if(xmin<0) xshift=-xmin;
  if(ymin<0) yshift=-ymin;

  if( ymax == INT_MAX ) 
    {
      /* ymax is not given */
      ymax = imhin.npy;
    }
  else
    ymax++;

  if( xmax == INT_MAX ) 
    {
      /* ymax is not given */
      xmax = imhin.npx;
    }
  else
    xmax++;

  printf("Output Y range: %d to %d in original frame\n",ymin,(ymax-1));
  printf("Output X range: %d to %d in original frame\n",xmin,(xmax-1));

  if( ymin > (ymax-1) ) 
    {
      printf("Error: Ymin > Ymax\n");
      imclose( fp,&imhin,&icomin );
      exit(-1);
    }
  if( xmin > (xmax-1) ) 
    {
      printf("Error: Xmin > Xmax\n");
      imclose( fp,&imhin,&icomin );
      exit(-1);
    }

  /* 2003/12/23 */
  /* check */
  if (imhin.dtype==DTYPEMOS)
    {
      if (0!=imc_mos_check_fill_buffer(&imhin,xmin,xmax,
				       ymin,ymax,nline))
	{
	  printf("Error: nline is not appropriate\n");
	  exit(-1);
	}
    }
  /*
   * ... Open output
   */
  
  if(fnamout[0]=='\0' ) 
    {
      (void) printf(" output IRAF/FITS file name = " );
      (void) fgets( temp,BUFSIZ,stdin );
      sscanf(temp,"%s",fnamout);
    }
  else
    (void)printf(  " Output= %s\n\n", fnamout );
  
  imh_inherit(&imhin,&icomin,&imhout,&icomout,fnamout);

  if (NBIN!=1) 
    {
      NBINX=NBIN;
      NBINY=NBIN;
    }
  NBIN=NBINX*NBINY;

  imhout.npx   = (xmax - xmin)/ NBINX;
  imhout.npy   = (ymax - ymin)/ NBINY;
  imhout.ndatx = imhout.npx;
  imhout.ndaty = imhout.npy;

  if (imhout.dtype==DTYPFITS)
    {
      if(dtype[0]!='\0')
	{
	  if (strstr(dtype,"SHORT"))
	    {
	      fitsdtype=FITSSHORT;
	      fitsmax=(float)SHRT_MAX-1.; /* defined in <limits.h> */
	    }
	  else if (strstr(dtype,"INT"))
	    {
	      fitsdtype=FITSINT;
	      fitsmax=(float)INT_MAX-1.; /* defined in <limits.h> */
	    }
	  else if (strstr(dtype,"CHAR"))
	    {
	      fitsdtype=FITSCHAR;
	      fitsmax=(float)CHAR_MAX-1.; /* defined in <limits.h> */
	    }
	  else if (strstr(dtype,"FLOAT"))
	    {
	      fitsdtype=FITSFLOAT;
	    }
	  else
	    {
	      fitsdtype=FITSSHORT;
	      fitsmax=SHRT_MAX-2.; /* defined in <limits.h> */
	    }
	}
      else
	{
	  (void)imc_fits_get_dtype( &imhout, &fitsdtype, NULL, NULL, NULL);
	}
      (void)imc_fits_set_dtype( &imhout, fitsdtype, bzero, bscale );
    }
  else
    {	  
      if (strstr(dtype,"I2"))
	{
	  imhout.dtype=DTYPI2;
	}
      else if (strstr(dtype,"INT"))
	{
	  imhout.dtype=DTYPINT;
	}
      else if (strstr(dtype,"I4"))
	{
	  imhout.dtype=DTYPI4;
	}
      else if (strstr(dtype,"R4"))
	{
	  imhout.dtype=DTYPR4;
	}
      else if (strstr(dtype,"R8"))
	{
	  imhout.dtype=DTYPR8;
	}
      else
	{
	  imhout.dtype=DTYPU2;
	}
      imset_u2off(&imhout,&icomout,u2off);  
    }


  /*  Make comments */

  imaddhistf(&icomout,"made by imcio2 from %-48.48s",fnamin);
  
  if(imhout.npx != imhin.npx ||  imhout.npy != imhin.npy || NBIN>1)
    {
      imaddhistf(&icomout,
		 "  x[%d:%d] y[%d:%d] %dx%d bining",
		 xmin,xmax,ymin,ymax,NBINX,NBINY);
    }   

  (void)imc_fits_get_dtype( &imhout, NULL, NULL, NULL, &pixoff);

  if(rplc_ignor!=NOT_REPLACE)
    {
      imset_pixignr(&imhout, &icomout, (int)rplc_ignor);
    }
  else
    {
      imset_pixignr(&imhout, &icomout, (int)pixignr);
      rplc_ignor=pixignr;
    }

  /* 2002/05/07 WCS change is added */
  imc_shift_WCS(&icomout, (float)xmin, (float)ymin);
  if (NBIN>1)
    {
      /*
	imc_scale_WCS(&icomout, 1.0/((float)NBIN));
      */
      imc_scale_WCS2(&icomout, 1.0/((float)NBINX),1.0/((float)NBINY));
    }


  /** 2004/03/03 *.mos */
  if (imhin.dtype==DTYPEMOS)
    {
      imc_mos_get_params(&imhin,&vxoff,&vyoff,
			 NULL,NULL,NULL,NULL,
			 NULL,&nfrm,NULL);
      imaddhistf(&icomout,"shift by %f %f from original mos",
		 vxoff,vyoff);
      imaddhistf(&icomout,"%d frames are used, %s",
		 nfrm, modename);

      if (addorghead==1)
	imc_mos_merge_org_header(&icomout,&imhin);
    }


  if( (fp2 = imwopen( fnamout, &imhout, &icomout )) == NULL ) 
    {
      imclose( fp,&imhin,&icomin );
      exit(-1);
    }

/*
 * ... Copy line to line
 */
  dp=(float*)malloc(sizeof(float)*imhin.npx);
  if(dp==NULL)
    {
      printf("Image too large. Cannot allocale memory for dp.\n"); 
      imclose( fp,&imhin,&icomin );
      imclose( fp2,&imhout,&icomout );
      exit(-1);
    }



/* Bin */
    if( NBIN > 1 ) 
      {
	/* 1999/02/19 changed */
	printf("\nBinning by %d x %d ...\n", NBINX, NBINY );	

	dpybin=(float*)malloc(sizeof(float)*imhin.npx);  
	dpxbin=(float*)malloc(sizeof(float)*imhout.npx);
	ndp=(int*)malloc(sizeof(int)*imhin.npx);

	if(dpybin==NULL||dpxbin==NULL||ndp==NULL)
	  {
	    printf("Image too large. Cannot allocale memory for ndp.\n"); 
	    imclose( fp,&imhin,&icomin );
	    imclose( fp2,&imhout,&icomout );
	    exit(-1);
	  }

	for( iy=ymin, iouty=0; iouty<imhout.npy; iouty++ ) 
	  {
	    
	    /* clear y buffer */
	    memset(ndp,0,imhin.npx*sizeof(int));	    
	    memset(dpybin,0,imhin.npx*sizeof(float));	    
	    
	    /* bin in y */
	    for(i=0; i<NBINY && iy<ymax; i++ ) 
	      {		
		/* Read a line */
		if(iy>=0)
		  {
		    (void) imrl_tor( &imhin, fp, dp, iy );
		    for( ix=xmin; ix<xmax; ix++) 
		      {
			if((ix>=0) && (dp[ix]!=(float)pixignr))
			  {
			    dpybin[ix+xshift] += dp[ix];
			    ndp[ix+xshift]++;
			  }
		      }
		  }
		iy++;
	      }

	    /* clear x buffer */
	    memset(dpxbin,0,imhout.npx*sizeof(float));

	    /* bin in x */
	    for(ix=xmin, ioutx=0 ; ioutx<imhout.npx; ioutx++ ) 
	      {
		n0=0;
		for(i=0; i<NBINX && ix<xmax; i++) 
		  {
		    dpxbin[ioutx] += dpybin[ix+xshift];
		    n0+=ndp[ix+xshift];
		    ix++;
		  }
/*
		printf("%d %d %f %d\n",ioutx,iouty,dpxbin[ioutx],n0);
*/
		if(n0!=0)
		  {
		    dpxbin[ioutx]/=(float)n0;
		  }
		else
		  {
		    if(rplc_ignor != NOT_REPLACE)
		      dpxbin[ioutx]=rplc_ignor;
		    else
		      dpxbin[ioutx]=(float)pixignr;
		  }

	      }
	    
	    /* output a line */
	    (void) imwl_rto( &imhout, fp2, dpxbin, iouty );
	  }

	free(dpxbin);
	free(dpybin);
	free(ndp);

      }	
    else
      {
	/* No binning */
	dpout=(float*)malloc(sizeof(float)*imhout.npx);

	if(dpout==NULL)
	  {
	    printf("Image too large. Cannot allocale memory for ndp.\n"); 
	    imclose( fp,&imhin,&icomin );
	    imclose( fp2,&imhout,&icomout );
	    exit(-1);
	  }

	/* Sep 28 temp; -> Feb5 */
	{
	  /**/
	  for( iy=ymin; iy<ymax; iy++ ) 
	    {
	      if(iy>=0 && iy<imhin.npy) 
		{
		  imrl_tor( &imhin, fp, dp, iy );
		  for( ix=xmin; ix<xmax; ix++ ) 
		    {
		      if(ix<0||ix>=imhin.npx|| dp[ix] == (float)pixignr)
			dpout[ix-xmin]=rplc_ignor;
		      else
			dpout[ix-xmin]=dp[ix];

		      /*
		      printf("%d %d\n",ix,ix-xmin);
		      */
		    }
		}	
	      else
		for( ix=xmin; ix<xmax; ix++ ) 
		  dpout[ix-xmin]=rplc_ignor;

	      (void) imwl_rto( &imhout, fp2, dpout, (iy-ymin));
	    }
	}
	free(dpout);
      }
    free(dp);
    
    printf(" Image Size is %d x %d\n\n", imhout.npx, imhout.npy );
    
    if (fp!=NULL) {imclose( fp,&imhin,&icomin );}
    if (fp2!=NULL) {imclose( fp2,&imhout,&icomout );}
    
    return 0;
}
示例#11
0
文件: skydet3b.c 项目: eterps/pwrake
int main(int argc,char **argv)
{
  char fnamin[BUFSIZ]="";
  char fnamout[BUFSIZ]="";

  struct icom icomin={0};
  struct imh imhin={""};

  float fact,fsigm;
  float gmax,gmean,gmin,gsd;
  int   npx,npy;
  int nmesh_x,nmesh_y;
  int   meshsiz_x=0,meshsiz_y=0,meshsiz_xy=0;
  int   ncycle;
  float pixignr;
  float *g;
  float *rmesh;
  float *sgmesh;


  float bscale=1.;



  FILE *fpin;
  float msky,msigm;

  int dtypein;
  int binflag;

  /***** parse options ******/
  getargopt opts[20];
  char *files[3]={NULL};
  int n=0;

  files[0]=fnamin;
  files[1]=fnamout;

  n=0;
  setopts(&opts[n++],"-mesh=", OPTTYP_INT , &meshsiz_xy,
	  "mesh size (default: image size)");
  setopts(&opts[n++],"-meshx=", OPTTYP_INT , &meshsiz_x,
	  "mesh x-size (default: image size)");
  setopts(&opts[n++],"-meshy=", OPTTYP_INT , &meshsiz_y,
	  "mesh y-size (default: image size)");
  /* not impl. yet */
  /*
  setopts(&opts[n++],"-xmin=", OPTTYP_INT , &xmin,
	  "");
  setopts(&opts[n++],"-xmax=", OPTTYP_INT , &xmax,
	  "");
  setopts(&opts[n++],"-ymin=", OPTTYP_INT , &ymin,
	  "");
  setopts(&opts[n++],"-ymax=", OPTTYP_INT , &ymax,
	  "");
  */
  setopts(&opts[n++],"",0,NULL,NULL);

  if(parsearg(argc,argv,opts,files,NULL)||fnamin[0]=='\0')
    {
      print_help("Usage: skydet [options] filein [fileout]",
		 opts,"");
      exit(-1);
    }
  

  /********* main loop *************/
  
  /*
   *** DATA INPUT ***
   */
    
  /**** read image ****/
  if ((fpin= imropen(fnamin,&imhin,&icomin))==NULL) 
    {
      fprintf(stderr,"File %s not found !!\n",fnamin);
      exit(-1);
    }
  
  pixignr=imget_pixignr( &imhin );
  
  if(imhin.dtype==DTYPFITS)
    {
      imc_fits_get_dtype( &imhin, &dtypein, NULL, &bscale, NULL );
      if(dtypein==FITSFLOAT || bscale!=1.0)
	binflag=0;
      else
	binflag=1;	    
    }
  else
    {
      if(imhin.dtype==DTYPR4 || imhin.dtype==DTYPR8)
	binflag=0;
      else
	binflag=1;
    }

  npx=imhin.npx;
  npy=imhin.npy;
  
  if(meshsiz_xy!=0) 
    {
      meshsiz_x=meshsiz_xy;
      meshsiz_y=meshsiz_xy;
    }

  if(meshsiz_x<1) meshsiz_x=npx;
  if(meshsiz_y<1) meshsiz_y=npy;
  
  g=(float*)malloc(sizeof(float)*npx*npy);
  if (g==NULL) 
    { 
      printf("Error cannot allocate image buffer"); 
      exit(-1);
    }
  
  if(!imrall_tor(&imhin,fpin,g,npx*npy)) 
    {
      fprintf(stderr,"Error. cannot read data.\n");
      exit(-1);
    }
      
  imclose(fpin,&imhin,&icomin);

  /*
   *** SATAISTICS
   */
    
  fact=2.0;
  ncycle=2;
  statsk(g,npx,npy,fact,ncycle,&gmax,&gmin,&gmean,&gsd,pixignr);

  printf("\n =>  GMAX GMIN GMEAN GSD= %f %f %f %f \n",gmax,gmin,gmean,gsd);

  /*
 *** SKY DETERMINATION AND SUBTRACTION ***
 */
    
  nmesh_x=(int)(((float)npx*2.)/meshsiz_x)-1; 
  if(nmesh_x<1) nmesh_x=1;  
  nmesh_y=(int)(((float)npy*2.)/meshsiz_y)-1; 
  if(nmesh_y<1) nmesh_y=1;
  
  rmesh=(float*)malloc(sizeof(float)*nmesh_x*nmesh_y);
  sgmesh=(float*)malloc(sizeof(float)*nmesh_x*nmesh_y);
  
  /* 97/09/12 Yagi */
  fsigm=70.0; /* default */

  skydet2b(g,npx,npy,rmesh,
	   nmesh_x,nmesh_y,
	   meshsiz_x,meshsiz_y,
	   gmean,gsd,fsigm,sgmesh,binflag,
	   pixignr);
  
  if(nmesh_x*nmesh_y>2)
    {
      msigm=skysigmadet(sgmesh,nmesh_x,nmesh_y);
      msky=medfilter_skysb(rmesh,nmesh_x,nmesh_y,1); 
    }
  else if (nmesh_x*nmesh_y==2)	
    {
      msky=0.5*(rmesh[0]+rmesh[1]);
      msigm=0.5*(sgmesh[0]+sgmesh[1]);
    }
  else if(nmesh_x*nmesh_y==1)
    {
      msky=rmesh[0];
      msigm=sgmesh[0];	 
    }
  else 
    {
      msky=0;/* Error */
      msigm=-1.0; /* Error */
    }
  
  printf("%g ",msky);
  printf("%g\n",msigm);

  if(fnamout[0]!='\0') 
    {
      skypattern(g,npx,npy,rmesh,nmesh_x,nmesh_y,meshsiz_x,meshsiz_y);
      makePostage(fnamout,g,npx,npy);
    }
  
  return 0;
}
示例#12
0
文件: osmed4.c 项目: eterps/pwrake
int main(int argc,char *argv[])
{
  struct imh imhin={""},imhout={""};
  struct icom icomin={0},icomout={0};

  char fnamin[100]="";
  char fnamout[100]="";
  char tmp[100]="";

  FILE *fp,*fp2;
  float dp[XMAX];
  float data[OSMAX]; /* temporary */
  int ix,iy;
  int xmin=-1,xmax=-1,ymin=-1,ymax=-1;
  int offst;
  float bzero=0,bscale=1.0,bzero_new=FLT_MIN,bscale_new=FLT_MIN;
  float blank_new=FLT_MIN;
  float pixignr=INT_MIN;
  int fitsdtype=-1;

  int efpmin1,efprng1,efpmin2,efprng2;

  int j=0;
  char dtype[BUFSIZ]="";

  int fit_param=-1;
  float os[4096];
  int notrim=0;

  getargopt opts[20];
  char *files[3]={NULL};
  int n=0;
  int helpflag;

  files[0]=fnamin;
  files[1]=fnamout;

  setopts(&opts[n++],"-xmin=", OPTTYP_INT , &xmin,
	  "effective region (default:0)");
  setopts(&opts[n++],"-xmax=", OPTTYP_INT , &xmax,
	  "effective region (default:npx-1)");
  setopts(&opts[n++],"-ymin=", OPTTYP_INT , &ymin,
	  "effective region (default:0)");
  setopts(&opts[n++],"-ymax=", OPTTYP_INT , &ymax,
	  "effective region (default:npy-1)");
  setopts(&opts[n++],"-notrim", OPTTYP_FLAG , &notrim,
	  "not trim off(default:trim)",1);
  /* */

  setopts(&opts[n++],"-bzero=", OPTTYP_FLOAT , &bzero_new,
	  "bzero");
  setopts(&opts[n++],"-bscale=", OPTTYP_FLOAT , &bscale_new,
	  "bscale");
  setopts(&opts[n++],"-dtype=", OPTTYP_STRING , dtype,
	  "datatyp(FITSFLOAT,FITSSHORT...)");
  setopts(&opts[n++],"-pixignr=", OPTTYP_FLOAT , &blank_new,
	  "pixignr value");
  /*
    setopts(&opts[n++],"-fit", OPTTYP_FLAG , &fit_param,
    "fitting (default:no)",1);
  */
  setopts(&opts[n++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);

  if(fnamout[0]=='\0')
   {
      fprintf(stderr,"Error: No input file specified!!\n");
      helpflag=1;
    }
  if(helpflag==1)
    {
      print_help("Usage: osmed4 <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  /*
   * ... Open Input
   */

  (void)printf("\n Input = %s\n",fnamin );

  if( (fp = imropen ( fnamin, &imhin, &icomin )) == NULL ) 
    {
      print_help("Usage: %s <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  imget_fits_value(&icomin,"EFP-MIN1",tmp);
  efpmin1=atoi(tmp);
  imget_fits_value(&icomin,"EFP-MIN2",tmp);
  efpmin2=atoi(tmp);
  imget_fits_value(&icomin,"EFP-RNG1",tmp);
  efprng1=atoi(tmp);
  imget_fits_value(&icomin,"EFP-RNG2",tmp);
  efprng2=atoi(tmp);


#if 0 /* included in imc_WCS 2002/05/07 */
  /* 2000/09/26 */
  imget_fits_value(&icomin,"CRPIX1",tmp);
  crpix1=atof(tmp);
  imget_fits_value(&icomin,"CRPIX2",tmp);
  crpix2=atof(tmp);
#endif

  if(xmin<0&&xmax<0&&ymin<0&&ymax<0)
    {
      xmin=efpmin1-1;
      ymin=efpmin2-1;
      xmax=xmin+efprng1-1;
      ymax=ymin+efprng2-1;
    }

  /*
     printf("xmin %d xmax %d ymin %d ymax %d\n",
	  xmin,xmax,ymin,ymax);
	  */

  if (xmin<0) xmin=0;
  if (xmax>imhin.npx-1||xmax<xmin) xmax=imhin.npx-1;
  if (ymin<0) ymin=0;
  if (ymax>imhin.npy-1||ymax<ymin) ymax=imhin.npy-1;

  printf("(%d,%d) - (%d,%d)\n",
	 xmin,ymin,xmax,ymax);

  /* output */
  
  imh_inherit(&imhin,&icomin,&imhout,&icomout,fnamout);
  if(!notrim)
    {
      imhout.npx   = (xmax - xmin + 1);
      imhout.npy   = (ymax - ymin + 1);
      imhout.ndatx = imhout.npx;
      imhout.ndaty = imhout.npy;
    }
  

  /* !! need 2000/07/02 or later version of IMC */

  if(dtype[0]=='\0')
    imc_fits_get_dtype( &imhout, &fitsdtype, &bzero, &bscale, &offst );
  else
    if ((fitsdtype=imc_fits_dtype_string(dtype))==-1)
      {
	printf("\nWarning: Unknown fits dtype %s. Inheriting original.\n",dtype);
	imc_fits_get_dtype( &imhout, &fitsdtype, &bzero, &bscale, &offst );
      }

  if(bzero_new!=FLT_MIN)
    {
      bzero=bzero_new;
    }
  if(bscale_new!=FLT_MIN)
    {
      bscale=bscale_new;
    }

  
  (void)imc_fits_set_dtype( &imhout, fitsdtype, bzero, bscale );

  if(blank_new!=FLT_MIN)
    imset_pixignr(&imhout,&icomout,(int)blank_new);    
  else
    {
      pixignr=(float)imget_pixignr(&imhin);
      imset_pixignr(&imhout,&icomout,(int)pixignr);
    }

  if (fit_param>0)
    {
      imaddhist(&icomout,"OSMED4: Overscan value is smoothed");
    }
  else
    {
      imaddhist(&icomout,"OSMED4: Overscan median is subtracted line by line.");
    }

  if (!notrim)
    {
      imaddhistf(&icomout,"OSMED4: And extracted [%d:%d,%d:%d] (0-origin)",
		 xmin,xmax,ymin,ymax);
    }

  (void)printf("\n Output = %s\n",fnamout );

  /* 2000/09/26 EFP-MIN revise */
  /* 2001/09/17 debug */
  if(efpmin1-xmin<1)
    {
      efprng1-=(xmin+1-efpmin1);
      efpmin1=xmin+1;
    }
  if(efpmin1-1+efprng1-1>=xmax)
    {
      efprng1=xmax-(efpmin1-1)+1;
    }
  if(efpmin2-ymin<1)
    {
      efprng2-=(ymin+1-efpmin2);
      efpmin2=ymin+1;
    }
  if(efpmin2-2+efprng2-1>=ymax)
    {
      efprng2=ymax-(efpmin2-1)+1;
    }

  if(!notrim)
    {


      imupdate_fitsf(&icomout, "EFP-MIN1",IMC_FITS_INTFORM,
		    efpmin1-xmin,
		    "Start position of effective frame in axis-1");

      imupdate_fitsf(&icomout, "EFP-MIN2",IMC_FITS_INTFORM,
		    efpmin2-ymin,
		    "Start position of effective frame in axis-2");

      imupdate_fitsf(&icomout, "EFP-RNG1",IMC_FITS_INTFORM,
		    xmax-xmin+1,
		    "Range of effective frame in axis-1");

      imupdate_fitsf(&icomout, "EFP-RNG2",IMC_FITS_INTFORM,
		    ymax-ymin+1,
		    "Range of effective frame in axis-2");

#if 0      
      /* 2000/09/26 CRPIX revise */
      imupdate_fitsf(&icomout, "CRPIX1",
		    "%20.1f / %-47.47s",
		    crpix1-(float)xmin,
		    "Reference pixel coordinate system in axis1");


      imupdate_fitsf(&icomout, "CRPIX2",
		    "%20.1f / %-47.47s",
		    crpix2-(float)ymin,
		    "Reference pixel coordinate system in axis2");
#else
      imc_shift_WCS(&icomout,(float)xmin,(float)ymin);
#endif
    }

  for( iy=0; iy<imhin.npy; iy++ ) 
    {
      j=0;
      (void) imrl_tor( &imhin, fp, dp, iy );
      for( ix=0; ix<xmin; ix++ ) 
	{
	  data[j++]=dp[ix];
	}
      for(ix=xmax+1;ix<imhin.npx;ix++)
	{
	  data[j++]=dp[ix];
	}
      os[iy]=floatmedian(j,data);
    }

  /* fit, if needed, not implemented */

  /**** OPEN output ****/

  if( (fp2 = imwopen( fnamout, &imhout, &icomout )) == NULL )
    {
      (void) imclose(fp,&imhin,&icomin);
      print_help("Usage: %s <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }
  if (notrim)
    {
      xmin=0;
      xmax=imhin.npx-1;
    }

  for( iy=0; iy<imhin.npy; iy++ ) 
    {
      j=0;
      (void) imrl_tor( &imhin, fp, dp, iy );
      for(ix=xmin;ix<=xmax;ix++)
	dp[ix]-=os[iy];
      (void) imwl_rto( &imhout, fp2, dp+xmin, iy);
    }

  (void) imclose(fp,&imhin,&icomin);  
  (void) imclose(fp2,&imhout,&icomout);
  return 0;
}
示例#13
0
int main(int argc, char** argv)
{
    struct imh	imhin={""};		/* imh header structure */
    struct icom	icomin={0};		/* imh icominent structure */


    
    char	fname[BUFSIZ]="";	/* image file name */
    char	fnamcatout[BUFSIZ]="";	/* output catalog file name */

    FILE	*fp_pix;	/* pointer to pix file */
    FILE	*fp;
    float	*pix;		/* pixel array */
    int 	pdim;		/* pixel data size */
    int 	npx, npy;	/* pixel data size */
    objrec_t	*psfob=NULL, *q=NULL;	        /* object record used to make PSF */

    int         sobj;           /* number of selected object */



    int         i,k;            /* do loop */



    float       infcri=0,supcri=10000;  /* selection criteria */







    

  
    float	DETECT_LEVEL = 3.0;
    float	DETECT_ISO = 0.0;   
    float	DETECT_ISO_FACTOR = 1.0;   

    int	        MINIMUM_PIXEL = 10;
    


    float   REJECT_CRIT_1 = 0.0;     /* Rejection criteria mean-(*)sigma
					for star selection (Ipeak/Npix test) */

    float   REJECT_CRIT_2 = 0.5;    /* Rejection criteria for star 
					selection.
					((xmax-xmin)/(ymax-ymin) test) */
    /* Needed */
    int     IM_RAD_MAX = 20;         /* Initial PSF Radius and Max Value
					when radius is undetermined */
    float SKY_SIGMA=0.;


    int nsky;
    float sky_mean,sky=FLT_MAX;
    float pixignr;

    int niter=5;
    int nstarmin=50,nstarmax=300;
    int flag;
    int ndiv=10;





    /* 2000/10/21 */
    float aprad=10.0;

  getargopt opts[20];
  int n=0;
  char *files[3]={NULL};
  int helpflag=0;

  files[0]=fname;

  n=0;
  setopts(&opts[n++],"-nskysigma=", OPTTYP_FLOAT , &DETECT_LEVEL,
	  "detection threshold=%%f * skysigma (default:3.0)");
  setopts(&opts[n++],"-iso=", OPTTYP_FLOAT, &DETECT_ISO,
	  "set detection threshold=%%f (default: not used)");
  setopts(&opts[n++],"-niso=", OPTTYP_FLOAT, &DETECT_ISO_FACTOR,
	  "-iso=%%f is multiplied by factor %%f (default: 1.0)");
  setopts(&opts[n++],"-npix=", OPTTYP_INT, &MINIMUM_PIXEL,
	  "minimum connected pixel (default:10)\n");
  setopts(&opts[n++],"-ndiv=", OPTTYP_INT , &ndiv,
	  "number of division of image in detection (default:10)");
  setopts(&opts[n++],"-sky=", OPTTYP_FLOAT , &sky,
	  "background sky (default:estimated from image)");
  setopts(&opts[n++],"-rpsf=", OPTTYP_INT, &IM_RAD_MAX,
	  "maximun radius for PSF (default:20)");



  setopts(&opts[n++],"-criteria1=", OPTTYP_FLOAT, &REJECT_CRIT_1,
	  "peak-npix criteria (default:0)");
  setopts(&opts[n++],"-aratiomin=", OPTTYP_FLOAT, &REJECT_CRIT_2,
	  "axial ratio minimum limit(default:0.5)");

  setopts(&opts[n++],"-peakmin=", OPTTYP_FLOAT , &infcri,
	  "minimum peak value (default:0)");
  setopts(&opts[n++],"-peakmax=", OPTTYP_FLOAT , &supcri,
	  "maximum peak value (default:10000)");

  setopts(&opts[n++],"-outmes=", OPTTYP_STRING , &fnamcatout,
	  "output catalog name (default: (infile).mes)");
  setopts(&opts[n++],"-aprad=", OPTTYP_FLOAT, &aprad,
	  "aperture flux radius(default:10.0)");


  setopts(&opts[n++],"-nmin=", OPTTYP_INT , &nstarmin,
	  "minimum number of output (default:50)");
  setopts(&opts[n++],"-nmax=", OPTTYP_INT , &nstarmax,
	  "maximum number of output (default:300)");
  setopts(&opts[n++],"-niter=", OPTTYP_INT , &niter,
	  "rejection iteration cycle (default:5)");

  setopts(&opts[n++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);

  if(ndiv<=1) ndiv=1;

  if(fname[0]=='\0')
    {
      printf("Error: No input file specified!!\n");
      helpflag=1;
    }    

  if(helpflag==1)
    {
      /* print usage */
      print_help("Usage: starsel3 [options] (imagefile)",
		 opts,"");
      exit(-1);
    }

    DETECT_ISO*=DETECT_ISO_FACTOR;
    
    /* Image file open to read */
    
    if ((fp_pix = imropen(fname, &imhin, &icomin)) == NULL)
      {
	fprintf(stderr,"Cannot read file %s\n",fname);
	exit(1);
      }
    
    /* Pick up pixignr value */
    pixignr = (float)imget_pixignr(&imhin);
    
    /* Allocaton of pixel data memory */
    
    npx  = imhin.npx;
    npy  = imhin.npy;
    pdim = npx * npy;
    
    pix = (float*) malloc(pdim*sizeof(float));
    
    /* Read pixel data */
    if (imrall_tor(&imhin, fp_pix, pix, pdim) == 0)
      {
	fprintf(stderr,"Cannot read file %s\n",fname);
	exit(1);
      }
    
    imclose(fp_pix,&imhin,&icomin);

    /* Detection */
    /* determine thres if -d is used */

    skydet(pix, npx, npy, &nsky, &sky_mean, &SKY_SIGMA, pixignr);

    if(sky==FLT_MAX) 
      sky=sky_mean;

    if(DETECT_ISO<=0)
      {
	DETECT_ISO=SKY_SIGMA*DETECT_LEVEL;
      }
    /* skysb */
    printf("sky=%f\n",sky);
    for(i=0;i<npx*npy;i++)
      if (pix[i]!=pixignr) 
	{
	  pix[i]-=sky;
	}

    /****************************************************************/

    printf("adopted number of PSFs [%d, %d]\n",
	   nstarmin, nstarmax);

    flag=0;
    for(k=0;k<niter;k++)
      {
	printf("\niso=%f npix=%d\n",DETECT_ISO,MINIMUM_PIXEL);
	sobj=detectpsf(pix,npx,npy,
		       DETECT_ISO, 
		       MINIMUM_PIXEL,
		       IM_RAD_MAX,		  
		       ndiv,
		       infcri,supcri,
		       REJECT_CRIT_1,
		       REJECT_CRIT_2,
		       pixignr,
		       &psfob);
	if(sobj<0)
	  {
	    /* no object detected */
	  }
	else if (sobj==0)
	  {
	    /* all objects are rejected */
	    REJECT_CRIT_1-=1.0;
	  }
	else if(sobj>nstarmax)
	  {
	    /* test. change iso */
	    printf("  too many. ");
	    if(flag==0)
	      DETECT_ISO*=2.0;
	    else
	      MINIMUM_PIXEL=(int)ceil((double)MINIMUM_PIXEL*1.5);
	    flag=(flag+1)%2;
	  }
	else if(sobj<nstarmin)
	  {
	    /* test change iso */
	    printf("  too few. ");
	    if(flag==0)
	      MINIMUM_PIXEL=(int)ceil((double)MINIMUM_PIXEL*0.65);
	    else
	      DETECT_ISO*=0.5;
	    flag=(flag+1)%2;
	  }
	else
	  {
	    printf("debug: thres=%f npix=%d crit1=%f\n",DETECT_ISO,MINIMUM_PIXEL,REJECT_CRIT_1);
	    break;
	  }
	if (k<niter-1) 
	  {
	    free_objrec_list(psfob);
	    psfob=NULL;
	    printf("  retrying ...\n");
	  }
	else printf("  iterated %d times\n",niter);
      }

    /****************************************************************/
	
    if (fnamcatout[0]=='\0')
      sprintf(fnamcatout,"%s.mes",fname);
    
    fp=fopen(fnamcatout,"wt");
    if(fp==NULL)
      {
	fprintf(stderr,"Cannot write output catalog \"%s\"\n",
		fnamcatout);
	exit(-1);
      }
    for(q=psfob; q != NULL; q=q->next)
      {
	/* 2000/10/21 aperture added */
	/* apphot */
	q->fiso=aperturePhotometry(pix,npx,npy,q->xc,q->yc,aprad);
	fprintf(fp, "%d %.3f %.3f %.0f %d %.0f %d %d %d %d %d %d\n",
		q->entnum, q->xc, q->yc, q->fiso, 
		q->npix,q->peak, 
		q->xmin, q->xmax, q->ymin, q->ymax, 
		q->ipeak, q->jpeak);
      }
    fclose(fp);

    free_objrec_list(psfob);
    free(pix);
    printf("\n");
    return 0;
}
示例#14
0
int main(int argc, char *argv[])
{
  FILE *fp; 
  /* log(matrix) file */
  /* 0->0 0->1, ... 0->n */
  
  int i,j,n=0,m,k,dim,dimmat,dimdat,idx;
  double *dx,*dy,*dm,*da; /* data */
  double *ex,*ey,*em,*ea; /* error */

  double dx0,dy0,da0; /* data */
  double ex0,ey0,ea0; /* error */
  
  double df0,ef0;
  double x,y;
  double eps_r=10.0,eps_f=0.5,eps_a=0.005,eps_m;

  int ndat,ndat0=0;

  double *ax,*ay,*am,*aa; /* ans */
  double *ax0,*ay0,*am0,*aa0; /* ans */
  double *mat_x,*mat_y,*mat_m,*mat_a;
  double *dat_x,*dat_y,*dat_m,*dat_a;
  double c,s;
  char **line=NULL;
  char **names=NULL;
  char buffer[BUFSIZ];
  char fnam1[BUFSIZ],fnam2[BUFSIZ],fnamcat[BUFSIZ]="";
  int nline=100,l=0;

  int *connect;
  int nc=1,flag;
  int ctmp;

  double *res=NULL,r0; 
  double *resx,*resy; 
  double *chisq=NULL,chisqmin;
  
  int *id=NULL;



  int quietmode=1;

  int ix1,ix2,id1,id2;
  int idm1, idm2;

  int niter=20;
  int ret;

  getargopt opts[10];
  char *files[3]={NULL};
  int helpflag;
  
  files[0]=fnamcat;

  setopts(&opts[n++],"-dr=",OPTTYP_DOUBLE,&eps_r,"error allowance of position.(default:10.0)");
  setopts(&opts[n++],"-df=",OPTTYP_DOUBLE,&eps_f,"error allowance of flux ratio.(default:0.5)");
  setopts(&opts[n++],"-da=",OPTTYP_DOUBLE,&eps_a,"error allowance of angle.(default:0.005)");
  setopts(&opts[n++],"-niter=",OPTTYP_INT,&niter,"");

  setopts(&opts[n++],"-quiet",OPTTYP_FLAG,&quietmode,"quiet mode(default)",1);
  setopts(&opts[n++],"-verbose",OPTTYP_FLAG,&quietmode,"verbose mode",0);
  setopts(&opts[n++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);
  if(helpflag==1||fnamcat[0]=='\0')
    {
      print_help("Usage: match_stack5b <options> (resultfile)",
		 opts,"");
      exit(-1);
    }
  
  /***************************************************************/
  /* read lines */

  fp=fopen(fnamcat,"r");
  if(fp==NULL)
    {
      fprintf(stderr,"Cannot open %s\n",fnamcat);
      exit(-1);
    }
  
  eps_m=fabs(log(eps_f));
  
  line=(char**)malloc(sizeof(char*)*nline);

  l=0; 
  n=0;
  while(1)      
    {
      if(fgets(buffer,BUFSIZ,fp)==NULL) break;
      if (sscanf(buffer,"%s %s",fnam1,fnam2)==2 && 
	  fnam1[0]!='#')
	{
	  n=adddic(n,&names,fnam1);
	  n=adddic(n,&names,fnam2);
	  line[l]=(char*)malloc(sizeof(char)*(strlen(buffer)+1));
	  strcpy(line[l],buffer);
	  l++;
	  if(l>=nline) 
	    {
	      nline*=2;
	      line=(char**)realloc(line,sizeof(char*)*nline);
	    }
	}
    }
  fclose(fp);

  nline=l;
  line=(char**)realloc(line,sizeof(char*)*nline);

  /***************************************************************/
  /* parse line, set data */

  dim=n*n;
  dx=(double*)calloc(dim,sizeof(double));
  dy=(double*)calloc(dim,sizeof(double));
  da=(double*)calloc(dim,sizeof(double));
  dm=(double*)calloc(dim,sizeof(double));

  ex=(double*)calloc(dim,sizeof(double));
  ey=(double*)calloc(dim,sizeof(double));
  ea=(double*)calloc(dim,sizeof(double)); 
  em=(double*)calloc(dim,sizeof(double));

  connect=(int*)calloc(n,sizeof(int));
  
  /* 2000/08/18 */
  /* banpei */
  for(i=0;i<dim;i++)
    em[i]=10000.0;

  for(l=0;l<nline;l++)
    {
      sscanf(line[l],"%s %s %lf %lf %lf %lf %lf %lf %lf %lf %d",
	     fnam1,fnam2,
	     &dx0, &dy0, &da0, &df0, &ex0, &ey0, &ea0, &ef0, &ndat);
      if(ex0>=0&&ef0>=0&&ea0>=0&&ef0>=0)
	{
	  i=name2no(n,names,fnam1);
	  j=name2no(n,names,fnam2);

	  /* 2001/05/22 */
	  /* ndat weight, how ??? */
	  idx=i+j*n;
	  dx[idx]=dx0;
	  ex[idx]=ex0;
	  dy[idx]=dy0;
	  ey[idx]=ey0;
	  da[idx]=da0;
	  ea[idx]=ea0;

	  if (fabs(ef0/df0)<1 && df0>0)
	    {
	      em[idx]=-log(1.0-fabs(ef0/df0));
	      dm[idx]=log(df0);
	    }
	  else
	    {
	      /* error */
	      em[idx]=10000.0;
	      dm[idx]=0.0;
	    }
	  free(line[l]);      
	}
    }
  free(line);

  if(n<1)
    {
      fprintf(stderr,"Error: no valid pairs\n");
      exit(-1);
    }

  /***************************************************************/
  
  ax=(double*)malloc((n-1)*sizeof(double));
  ay=(double*)malloc((n-1)*sizeof(double));
  aa=(double*)malloc((n-1)*sizeof(double));
  am=(double*)malloc((n-1)*sizeof(double));
  ax0=(double*)malloc((n-1)*sizeof(double));
  ay0=(double*)malloc((n-1)*sizeof(double));
  aa0=(double*)malloc((n-1)*sizeof(double));
  am0=(double*)malloc((n-1)*sizeof(double));

  dimdat=(n*(n-1))/2;
  dimmat=n*dimdat;

  mat_x=(double*)calloc(dimmat,sizeof(double));
  mat_y=(double*)calloc(dimmat,sizeof(double));
  mat_a=(double*)calloc(dimmat,sizeof(double));
  mat_m=(double*)calloc(dimmat,sizeof(double));

  dat_x=(double*)calloc(dimdat,sizeof(double));
  dat_y=(double*)calloc(dimdat,sizeof(double));
  dat_a=(double*)calloc(dimdat,sizeof(double));
  dat_m=(double*)calloc(dimdat,sizeof(double));


  /******************************************************************/
  /* check symmetry ?*/
  /* 1st path , a */

  m=0;
  for(i=0;i<n-1;i++)
    {
      for(j=i+1;j<n;j++)
	{
	  /* No xy symmetry check here */

	  /* 2001/03/13 */
	  id1=i+j*n;
	  id2=j+i*n;
	  ix1=i;
	  ix2=j;
	  
	  if(em[id1]==10000.0 && em[id2]!=10000.0) 
	    {
	      /* swap */
	      id1=j+i*n;
	      id2=i+j*n;
	      ix1=j; 
	      ix2=i;
	    }
	  idm1=(ix1-1)+m*(n-1);
	  idm2=(ix2-1)+m*(n-1);


	  if(em[id1]>eps_m)
	    {
	      if(em[id1]!=10000.0) /* banpei */
		{
		  if (!quietmode)
		    {
		      printf("%d %d %s - %s is not used\n",i,j,names[ix1],names[ix2]);
		      printf("%f(mag error) > %f(dm)\n",
			     em[id1],eps_m);
		    }
		}
	      else
		{
		  /* also not used */
		}
	    }
	  else if(ex[id1]*ex[id1]+ey[id1]*ey[id1]>eps_r*eps_r)
	    {
	      if (!quietmode)
		{
		      printf("%d %d %s - %s is not used\n",i,j,names[ix1],names[ix2]);
		  printf("%f(pos error^2) > %f(dr^2)\n",
			 ex[id1]*ex[id1]+ey[id1]*ey[id1],
			 eps_r*eps_r);
		}
	    }
	  else if(ea[id1]>eps_a)	     
	    {
	      if (!quietmode)
		{
		      printf("%d %d %s - %s is not used\n",i,j,names[ix1],names[ix2]);
		  printf("%f(angle error) > %f(da)\n",
			 ea[id1],eps_a);
		}
	    }	     
	  else if(fabs(dm[id1]+dm[id2])>eps_m &&
		  em[id2]!=10000.0) /* banpei */
	    {
	      if (!quietmode)
		{
		  printf("%d %d %s - %s is not used\n",i,j,names[ix1],names[ix2]);
		  printf("Flux information is not symmetric\n");	
		  printf("   ->  : %f (mag)\n",dm[id1]);
		  printf("   <-  : %f (mag)\n",dm[id2]);
		}
	    }
	  else if(fabs(da[id1]+da[id2])>eps_a && em[id2]!=10000.0)
	    {
	      if (!quietmode)
		{
		  printf("%d %d %s - %s is not used\n",i,j,names[ix1],names[ix2]);
		  printf("Angle information is not symmetric\n");	
		  printf("   ->  : %f (angle)\n",da[id1]);
		  printf("   <-  : %f (angle)\n",da[id2]);
		}
	    }
	  else
	    {
	      /* valid value */
	      if(em[id2]!=10000.0)
		{
		  da[id1]=0.5*(da[id1]-da[id2]);
		  ea[id1]=0.5*sqrt(ea[id1]*ea[id1]+
				   ea[id2]*ea[id2]);
		}

	      if(ea[id1]<1.e-7) ea[id1]=1.e-7;
	      
	      mat_a[idm2]=1.0/ea[id1];
	      
	      if(ix1>0)
		{
		  mat_a[idm1]=- mat_a[idm2];
		}
	      dat_a[m]=da[id1]/ea[id1];	      
	      
	      /* 2000/08/18 */

	      /* check connection */
	      if(connect[ix1]!=0)
		{
		  if(connect[ix2]==0)
		    connect[ix2]=connect[ix1];
		  else
		    {
		      ctmp=connect[ix2];
		      for(k=0;k<n;k++)
			if(connect[k]==ctmp)
			  connect[k]=connect[ix1];
		    }
		}
	      else
		{
		  if(connect[ix2]==0)
		    {
		      connect[ix2]=connect[ix1]=nc;
		      nc++;
		    }
		  else
		    connect[ix1]=connect[ix2];
		}
	      m++;
	    }
	}
    }

  /* here, ndat=m */

  /**********************************************************************/

  /* check connection */
  flag=0;
  for(k=0;k<n;k++)
    {
      if(connect[k]==0)
	{
	  printf("Error: %s is not connected to any other frame\n",
		 names[k]);
	  flag=1;
	  /* 2000/08/18, as rejection or partition is not inplemented yet */
	  if(k==0) break;
	}
      else if(connect[k]!=connect[0])
	{
	  printf("Error: %s is not connected to the reference frame %s\n",
		 names[k],names[0]);	  
	  flag=1;
	}
    }

  if(flag==1) 
    {
      /* rejection or partition is not inplemented yet (2000/08/18)*/
      exit(-1);
    }

  if(!quietmode)
    printf("calc angle.\n");

  /* 1st. solve the angle eqn. */
  /* mat_a * aa  = dat_a */

  /*******************************************************************/

  /* 2000/07/18 */
  if(m<n-1)
    {
      /* under determined */
      printf("Error: theta cannot be determined! too few constraints!\n");
      printf("       param=%d eqn=%d\n",n-1,m);
      printf("       all theta are set to be 0\n");
      for(i=0;i<n-1;i++)
	aa[i]=0.0;
    }
  else
    {
      /* main iteration loop */
      ndat=(m+n)/2;
      ndat0=n;

      chisq=(double*)malloc(niter*sizeof(double));
      chisqmin=100000.0;

      res=(double*)malloc(m*sizeof(double));
      id=(int*)malloc(m*sizeof(int));

      for (k=0;k<niter;k++)
	{
	  if(!quietmode)
	    printf("aitrer:k=%d ndat=%d\n",k,ndat);	  
	  chisq[k]=100000.0;

	  ret=solve(n-1,aa,ndat,dat_a,mat_a);

	  if(ret==1)
	    {
	      ndat=(m+ndat+1)/2;
	      continue;
	    }

	  /* here we get angles aa[i] */
	  if(!quietmode)
	    {
	      printf("iter %d\n",k);
	      for(i=0;i<n-1;i++)
		printf("%d a=%f\n",i+1,aa[i]);
	      printf("\n");
	    }

	  /* check chisq */
	  chisq[k]=0;
	  for(j=0;j<m;j++) /* not only used ndat, but also notused*/
	    {
	      id[j]=j;
	      r0=-dat_a[j];
	      for(i=0;i<n-1;i++)
		r0+=aa[i]*mat_a[i+j*(n-1)];
	      res[j]=fabs(r0);
	    }
	  heapsort2id(m,res,id);

	  id_reorder(m,id,sizeof(double),res);

	  chisq[k]=res[ndat-1]/ndat;


	  if (k==0 || chisq[k]<chisq[k-1])
	    {
	      /* OK, good */
	      id_reorder(m,id,(n-1)*sizeof(double),mat_a);
	      id_reorder(m,id,sizeof(double),dat_a);
	      id_reorder(m,id,(n-1)*sizeof(double),mat_x);
	      id_reorder(m,id,sizeof(double),dat_x);
	      id_reorder(m,id,(n-1)*sizeof(double),mat_y);
	      id_reorder(m,id,sizeof(double),dat_y);
	      id_reorder(m,id,(n-1)*sizeof(double),mat_m);
	      id_reorder(m,id,sizeof(double),dat_m);
	    }

	  if (chisq[k]<chisqmin*1.1)
	    {
	      if (chisq[k]<chisqmin) 
		{
		  chisqmin=chisq[k];
		  memcpy(aa0,aa,(n-1)*sizeof(double));
		  ndat0=ndat;
		}

	      if(k==0) /* initial */
		ndat=(m+n)/2;
	      else
		ndat=(m+ndat+1)/2;
	    }
	  else
	    { 
	      /* no good. retry */
	      if(ndat0==ndat) 
		break;
	      else
		ndat=(ndat0+ndat)/2;
	    }
	}
    }

  if(!quietmode)
    printf("recalc %d\n",ndat0);
  memcpy(aa,aa0,(n-1)*sizeof(double));

  /* MASK */
  for(j=ndat0;j<m;j++)
    {
      k=-1;
      for(i=0;i<n-1;i++)
	if(mat_a[i+j*(n-1)]!=0)
	  {
	    if(k==-1) k=i+1;
	    else 
	      {
		em[k+(i+1)*n]=em[(i+1)+k*n]=10000.0;

		if (!quietmode)
		  printf("Mask %s %s\n",names[k],names[i+1]);
		break;
	      }
	  }
      if(i==n && k!=-1)
	{
	  if (!quietmode)
	    printf("Mask %s %s\n",names[k],names[0]);
	  em[k]=em[k*n]=10000.0;
	}
    }

  /***************************************************************/

  /* Second path */
  /* rotate */

  if(!quietmode)
    printf("rotated.\n");

  for(i=1;i<n;i++)
    {
      /* 2000/08/18 !! */
      /* flag check needed ?? +aa or -aa ??? */
      /* => OK */
      c=cos(aa[i-1]);
      s=sin(aa[i-1]); 

      for(j=0;j<n;j++)
	{
	  id1=i+j*n;
	  /* rotate by aa[i]*/
	  x=dx[id1]*c-dy[id1]*s;
	  y=dx[id1]*s+dy[id1]*c;
	  dx[id1]=x;
	  dy[id1]=y;      
	  if(!quietmode)
	    if (x!=0||y!=0)
	      printf("%d %d x=%f y=%f\n",i,j,x,y);
	}  
    }

  /***************************************************************/

  /* clear up connection matrix */
  memset(connect,0,n*sizeof(int));

  m=0;
  for(i=0;i<n-1;i++)
    {
      for(j=i+1;j<n;j++)
	{

	  /* 2001/03/13 */
	  id1=i+j*n;
	  id2=j+i*n;
	  ix1=i;
	  ix2=j;

	  if(em[id1]==10000.0 && em[id2]!=10000.0) 
	    {
	      /* swap */
	      id1=j+i*n;
	      id2=i+j*n;
	      ix1=j; 
	      ix2=i;
	    }

	  idm1=(ix1-1)+m*(n-1);
	  idm2=(ix2-1)+m*(n-1);

	  if(em[id1]>eps_m)
	    {
	      if(em[id1]!=10000.0) /* banpei */
		{
		  if (!quietmode)
		    {
		      printf("%s - %s is not used\n",names[i],names[j]);
		      printf("%f(mag error) > %f(dm)\n",
			     em[id1],eps_m);
		    }
		}
	    }
	  else if(ex[id1]*ex[id1]+ey[id1]*ey[id1]>eps_r*eps_r)
	    {
	      if (!quietmode)
		{
		  printf("%s - %s is not used\n",names[ix1],names[ix2]);
		  printf("%f(pos error^2) > %f(dr^2)\n",
			 ex[id1]*ex[id1]+ey[id1]*ey[id1],
			 eps_r*eps_r);
		}
	    }
	  else if(ea[id1]>eps_a)	     
	    {
	      if (!quietmode)
		{
		  printf("%s - %s is not used\n",names[ix1],names[ix2]);
		  printf("%f(angle error) > %f(da)\n",
			 ea[id1],eps_a);
		}
	    }	     
	  else if(fabs(dm[id1]+dm[id2])>eps_m && em[id2]!=10000.0)
	    {
	      if (!quietmode)
		{
		  printf("%s - %s is not used\n",names[ix1],names[ix2]);
		  printf("Flux information is not symmetric\n");	
		  printf("   ->  : %f (mag)\n",dm[id1]);
		  printf("   <-  : %f (mag)\n",dm[id2]);
		}
	    }
	  else if(fabs(da[id1]+da[id2])>eps_a && em[id2]!=10000.0)
	    {
	      if (!quietmode)
		{
		  printf("%s - %s is not used\n",names[ix1],names[ix2]);
		  printf("Angle information is not symmetric\n");	
		  printf("   ->  : %f (angle)\n",da[id1]);
		  printf("   <-  : %f (angle)\n",da[id2]);
		}
	    }
	  else if(
		  ((dx[id1]+dx[id2])*(dx[id1]+dx[id2])+
		   (dy[id1]+dy[id2])*(dy[id1]+dy[id2])>eps_r*eps_r)
		  && em[id2]!=10000.0)
	    {
	      if (!quietmode)
		{
		  printf("%s - %s is not used\n",names[ix1],names[ix2]);
		  printf("Position information is not symmetric\n");	
		}
	    }
	  else
	    {
	      /* valid value */
	      if(em[id2]!=10000.0)
		{
		  dx[id1]=0.5*(dx[id1]-dx[id2]);
		  dy[id1]=0.5*(dy[id1]-dy[id2]);
		  dm[id1]=0.5*(dm[id1]-dm[id2]); 
		  
		  ex[id1]=0.5*sqrt(ex[id1]*ex[id1]+
				   ex[id2]*ex[id2]);
		  ey[id1]=0.5*sqrt(ey[id1]*ey[id1]+
				   ey[id2]*ey[id2]);
		  em[id1]=0.5*sqrt(em[id1]*em[id1]+
				   em[id2]*em[id2]);
		}

	      if(ex[id1]<0.005) ex[id1]=0.005;
	      if(ey[id1]<0.005) ey[id1]=0.005;
	      if(em[id1]<0.005) em[id1]=0.005;
	      
	      mat_x[idm2]=1.0/ex[id1];
	      mat_y[idm2]=1.0/ey[id1];
	      mat_m[idm2]=1.0/em[id1];

	      /* 2000/08/17 debug */
	      if(i>0)
		{
		  mat_x[idm1]= -mat_x[idm2]; 
		  mat_y[idm1]= -mat_y[idm2]; 
		  mat_m[idm1]= -mat_m[idm2]; 
		}

	      dat_x[m]=dx[id1]/ex[id1];
	      dat_y[m]=dy[id1]/ey[id1];
	      dat_m[m]=dm[id1]/em[id1];

	      /******************* check connection ****************/
	      if(connect[ix1]!=0)
		{
		  if(connect[ix2]==0)
		    connect[ix2]=connect[ix1];
		  else
		    {
		      ctmp=connect[ix2];
		      for(k=0;k<n;k++)
			if(connect[k]==ctmp)
			  connect[k]=connect[ix1];
		    }
		}
	      else
		{
		  if(connect[ix2]==0)
		    {
		      connect[ix2]=connect[ix1]=nc;
		      nc++;
		    }
		  else
		    connect[ix1]=connect[ix2];
		}
	      m++;
	    }
	 
	}
    }

  /***********************************************************************/

  /* check connection */
  flag=0;
  for(k=0;k<n;k++)
    {
      if(connect[k]==0)
	{
	  printf("Error: %s is not connected to any other frame after 1st rejection\n",
		 names[k]);
	  flag=1;
	  /* 2000/08/18, as rejection or partition is not inplemented yet */
	  if(k==0) break;
	}
      else if(connect[k]!=connect[0])
	{
	  printf("Error: %s is not connected to the reference frame %s after rejection\n",
		 names[k],names[0]);	  
	  flag=1;
	}
    }

  if(flag==1) 
    {
      /* rejection or partition is not inplemented yet (2000/08/18)*/
      exit(-1);
    }

  /******************************/

  /* 2000/07/18 */
  /* 2001/05/22 */
  if(m<n-1)
    {
      /* under determined */
      printf("Error: x,y,flux cannot be determined! too few constraints!\n");
      printf("       param=%d eqn=%d\n",n-1,m);
      printf("Exit\n");
      exit(-1);
    }
  else
    {
      /* main iteration loop */
      niter=20;
 
      ndat=(m+n)/2;
      ndat0=n;
      /* 2001/05/21 */
      /* check and reject */
      resx=(double*)malloc(m*sizeof(double));
      resy=(double*)malloc(m*sizeof(double));

      chisqmin=100000.0;

      for (k=0;k<niter;k++)
	{
	  chisq[k]=100000.0;
	  ret=0;
	  if (solve(n-1,ax,ndat,dat_x,mat_x)!=0 ||
	      solve(n-1,ay,ndat,dat_y,mat_y)!=0 ||
	      solve(n-1,am,ndat,dat_m,mat_m)!=0)
	    {
	      ret=1;	  
	      if(!quietmode)	  
		{
		  printf("Error: not solved ndat=%d\n",ndat);
		  printf("X=%d %d %d\n",solve(n-1,ax,ndat,dat_x,mat_x),n-1,ndat);
		  printf("Y=%d %d %d\n",solve(n-1,ax,ndat,dat_x,mat_x),n-1,ndat);
		  printf("M=%d %d %d\n",solve(n-1,ax,ndat,dat_x,mat_x),n-1,ndat);		
		  printf("Error: not solved. \n");
		}

	      if(ndat>=m)
		{
		  /* cannot solve */
		  ndat0=m;
		  break;
		}
	      ndat=(m+ndat+1)/2;
	      if(!quietmode)	  
		printf("Error: not solved. new ndat=%d\n",ndat);
	      continue;
	    }
	  else
	    {
	      /* calc residuals */
	      for(j=0;j<m;j++)
		{
		  id[j]=j;
		  resx[j]=-dat_x[j];
		  resy[j]=-dat_y[j];
		  for(i=0;i<n-1;i++)
		    {
		      resx[j]+=ax[i]*mat_x[i+j*(n-1)];
		      resy[j]+=ay[i]*mat_y[i+j*(n-1)];
		    }
		  res[j]=fabs(resx[j])+fabs(resy[j]);
		}	  
	      
	      /* sort by residual */
	      heapsort2id(m,res,id);

	      id_reorder(m,id,sizeof(double),res);

	      
	      chisq[k]=res[ndat-1]/ndat;
	    }

	  if (k==0 || chisq[k]<chisq[k-1])
	    {
	      /* OK, good */
	      id_reorder(m,id,(n-1)*sizeof(double),mat_x);
	      id_reorder(m,id,sizeof(double),dat_x);
	      id_reorder(m,id,(n-1)*sizeof(double),mat_y);
	      id_reorder(m,id,sizeof(double),dat_y);
	      id_reorder(m,id,(n-1)*sizeof(double),mat_m);
	      id_reorder(m,id,sizeof(double),dat_m);
	    }

	  if (chisq[k]<chisqmin*1.1)
	    {
	      if (chisq[k]<chisqmin) 
		{
		  chisqmin=chisq[k];
		  memcpy(ax0,ax,(n-1)*sizeof(double));
		  memcpy(ay0,ay,(n-1)*sizeof(double));
		  memcpy(am0,am,(n-1)*sizeof(double));
		  ndat0=ndat;
		}
	      if(k==0) /* initial */
		ndat=(m+n)/2;
	      else
		ndat=(m+ndat+1)/2;
	    }
	  else
	    { 
	      if(ndat0==ndat) 
		break;
	      else
		ndat=(ndat0+ndat)/2;
	    }
	}
    }

  if(!quietmode)
    printf("recalc %d\n",ndat0);
  
  /* recalc */
  memcpy(ax,ax0,(n-1)*sizeof(double));
  memcpy(ay,ay0,(n-1)*sizeof(double));
  memcpy(am,am0,(n-1)*sizeof(double));

  /*********************************************************************/
  printf("%s %f %f %f %f\n",names[0],0.0,0.0,0.0,1.0);
  for(i=0;i<n-1;i++)
    {
      printf("%s %f %f %f %f\n",names[i+1],ax[i],ay[i],aa[i],
	     exp(am[i]));
    }

  /* free */

  for(i=0;i<n;i++)
    free(names[i]);

  free(names);
  free(dx);
  free(dy);
  free(da);
  free(dm);
  free(ex);
  free(ey);
  free(ea);
  free(em);
  free(mat_x);
  free(mat_y);
  free(mat_a);
  free(mat_m);
  free(dat_x);
  free(dat_y);
  free(dat_a);
  free(dat_m);
  free(ax);
  free(ay);
  free(aa);
  free(am);
  free(connect);

  return 0;
}
示例#15
0
文件: skysb3b.c 项目: eterps/pwrake
int main(int argc,char **argv)
{
  float fact,fsigm;
  float gmax,gmean,gmin,gsd;
  int   npx,npy,meshsiz_x,meshsiz_y;

  int   nmesh_x=0,nmesh_y=0,mesh=0;
  int   ncycle;
  char fnamin[BUFSIZ]="";
  char fnamout[BUFSIZ]="";
  struct icom icomin={0},icomout={0},icomref={0};
  struct imh imhin={""},imhout={""},imhref={""};               

  int i,j;

  float *g,*g2;
  float *rmesh;
  float *sgmesh;

  char fnamref[BUFSIZ]="";
  char buffer[BUFSIZ];
  char skymap[BUFSIZ]="";

  float bzero=0.,bscale=1.;
  float bzero_new=FLT_MIN,bscale_new=FLT_MIN;
  int bzeroset=0;

  int fitsdtype;

  FILE *fpin,*fpout,*fpref;
  FILE *fmap;
  int mode;
  char dtype[80]="";


  float msky,msigm;

  int dtypein;
  int binflag;
  float ignor=(float)INT_MIN;
  float imax=(float)INT_MIN;
  float imin=(float)INT_MAX;

  int pixignr;


  getargopt opts[20];
  char *files[3]={NULL};
  int n=0;
  int helpflag;

  /***************************************/

  files[0]=fnamin;
  files[1]=fnamout;

  setopts(&opts[n++],"-mesh=", OPTTYP_INT , &mesh,
	  "mesh size (default:full image)");
  setopts(&opts[n++],"-meshx=", OPTTYP_INT , &nmesh_x,
	  "mesh x-size (default:not used)");
  setopts(&opts[n++],"-meshy=", OPTTYP_INT , &nmesh_y,
	  "mesh y-size (default:not used)");

  setopts(&opts[n++],"-skyref=", OPTTYP_STRING , &fnamref,
	  "sky determination reference (default:use input image)");

  setopts(&opts[n++],"-imax=", OPTTYP_FLOAT , &imax,
	  "flux upper limit to estimate sky(default:unlimited)");
  setopts(&opts[n++],"-imin=", OPTTYP_FLOAT , &imin,
	  "flux lower limit to estimate sky(default:unlimited)");

  /* */

  setopts(&opts[n++],"-bzero=", OPTTYP_FLOAT , &bzero_new,
	  "bzero");
  setopts(&opts[n++],"-bscale=", OPTTYP_FLOAT , &bscale_new,
	  "bscale");
  setopts(&opts[n++],"-dtype=", OPTTYP_STRING , dtype,
	  "datatyp(FITSFLOAT,FITSSHORT...)");
  setopts(&opts[n++],"-pixignr=", OPTTYP_FLOAT , &ignor,
	  "pixignr value");

  /* To be implemented in next major version */
  /*
    setopts(&opts[n++],"-fit", OPTTYP_FLAG , &fit_param,
    "fitting (default:no)",1);
  */

  setopts(&opts[n++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);

  if(fnamout[0]=='\0')
   {
      fprintf(stderr,"Error: No input file specified!!\n");
      helpflag=1;
    }
  if(helpflag==1)
    {
      print_help("Usage: skysb3b <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  if(nmesh_x==0) nmesh_x=mesh;
  if(nmesh_y==0) nmesh_y=mesh;

  if(bzero_new!=FLT_MIN)
    {
      bzero=bzero_new;
      bzeroset=1;
    }
  if(bscale_new!=FLT_MIN)
    {
      bscale=bscale_new;
      bzeroset=1;
    }

  /*
    printf("debug:nmesh_x=%d nmesh_y=%d\n",nmesh_x,nmesh_y);
  */
  
  mode=1;     /* default */
  fsigm=70.0; /* default */


  /*
 *** DATA INPUT ***
 */
  
  /**** read image ****/
  fprintf(stderr,"%s\n",fnamin);  
  if ((fpin= imropen(fnamin,&imhin,&icomin))==NULL) 
    {
      printf("File %s not found !!\n",fnamin);
      exit(-1);
    }
  
  pixignr=(int)imget_pixignr( &imhin );
  
  printf("pixignr_in=%f\n",(float)pixignr);
  
  if(imhin.dtype==DTYPFITS)
    {
      imc_fits_get_dtype( &imhin, &dtypein, NULL, NULL, NULL);
      if(dtypein==FITSFLOAT)
	binflag=0;
      else
	binflag=1;	    
    }
  else
	{
	  if(imhin.dtype==DTYPR4 || imhin.dtype==DTYPR8)
	    binflag=0;
	  else
	    binflag=1;
	}

      npx=imhin.npx;
      npy=imhin.npy;


      if(nmesh_x<1) nmesh_x=npx;
      if(nmesh_y<1) nmesh_y=npy;

      g=(float*)malloc(sizeof(float)*npx*npy);
      g2=(float*)malloc(sizeof(float)*npx*npy);
      if (g==NULL||g2==NULL) { printf("Error cannot allocate image buffer"); exit(-1);}
      
      if(imrall_tor(&imhin,fpin,g2,npx*npy)) 
	printf("npx, npy =%d %d \n",npx,npy);
      else {
	printf("Error. cannot read data.\n");
	exit(-1);
      }

      /* 2002/05/21 */
      if(fnamref[0]=='\0') 
	{
	  memcpy(g,g2,sizeof(float)*npx*npy);	  
	}
      else
	{
	  if ((fpref=imropen(fnamref,&imhref,&icomref))==NULL) 
	    {
	      printf("Reference File %s not found !!\n",fnamref);
	      exit(-1);
	    }
	  if (npx!=imhref.npx||npy!=imhref.npy)
	    {
	      printf("Error: Ref. size (%dx%d) differ from input (%dx%d)\n",
		     imhref.npx,imhref.npy,npx,npy);
	      exit(-1);
	    }
	  if(! imrall_tor(&imhref,fpref,g,npx*npy)) 
	    {
	      printf("Error: cannot read ref data.\n");
	      exit(-1);
	    }
	  imclose(fpref,&imhref,&icomref);
	}
      
      /* 2001/07/19 preformat (masking) */
      
      if(imax>(float)INT_MIN||imin<(float)INT_MAX)
	for(i=0;i<npx*npy;i++)
	  if(g[i]>imax||g[i]<imin) g[i]=pixignr;
      
      /*
     *** SATAISTICS
     */
      
      printf("Calculating statistics \n");

      /* TODO */
      /* to be tunable ?*/
      fact=2.0;
      ncycle=2;
      statsk(g,npx,npy,fact,ncycle,&gmax,&gmin,&gmean,&gsd,pixignr);
      
      printf("\n");
      printf(" =>  GMAX GMIN GMEAN GSD= %f %f %f %f \n",gmax,gmin,gmean,gsd);
      
      /*
       *** SKY DETERMINATION AND SUBTRACTION ***
       */

      printf("Sky subtraction under way\n");

      meshsiz_x=(int)((npx*2.)/nmesh_x)-1; /* meshsiz_x > 0 */
      if(meshsiz_x<1) meshsiz_x=1;

      meshsiz_y=(int)((npy*2.)/nmesh_y)-1; /* meshsiz_y > 0 */
      if(meshsiz_y<1) meshsiz_y=1;

      rmesh=(float*)malloc(sizeof(float)*meshsiz_x*meshsiz_y);
      sgmesh=(float*)malloc(sizeof(float)*meshsiz_x*meshsiz_y);

      /* 97/09/12 Yagi */
      skydet2b(g,npx,npy,rmesh,meshsiz_x,meshsiz_y,
	       nmesh_x,nmesh_y,gmean,gsd,fsigm,sgmesh,binflag,pixignr);

      if(meshsiz_x*meshsiz_y>2)
	{
	  /* 3X3 median filter */
	  /* 
	     msky=skysigmadet(rmesh,meshsiz_x,meshsiz_y);
	  */
	  msky=medfilter_skysb
	    (rmesh,meshsiz_x,meshsiz_y,1);
	  msigm=skysigmadet(sgmesh,meshsiz_x,meshsiz_y);
	}
      else if (meshsiz_x*meshsiz_y==2)	
	{
	  msky=0.5*(rmesh[0]+rmesh[1]);
	  msigm=0.5*(sgmesh[0]+sgmesh[1]);
	}
      else if(meshsiz_x*meshsiz_y==1)
	{
	  msky=rmesh[0];
	  msigm=sgmesh[0];	 
	}
      else 
	{
	  msky=0;/* Error */
	  msigm=-1.0; /* Error */
	}

      printf("SSB-EST %g\n",msky);
      printf("SSGM-EST %g\n",msigm);

      /* Write skymap to file*/
      
      if(skymap[0]!='\0') 
	{
	  if(skymap[0]=='-')
	    {
	      fmap=stdout;
	      printf("mapfile:stdout\n");
	      fprintf(stderr,"mapfile:stdout\n");
	    }
	  else
	    {
	      printf("mapfile:%s\n",skymap);
	      fprintf(stderr,"mapfile:%s\n",skymap);
	      fmap=fopen(skymap,"a");
	    }

	  if(fmap==NULL) 
	    {
	      printf("Cannot write to \"%s\" -- writeing to stdout.\n",skymap);
	      fprintf(stderr,
		      "Cannot write to \"%s\" -- writeing to stdout.\n",skymap);
	      fmap=stdout;
	    }

	  fprintf(fmap,"# %s\n",fnamin);
	  fprintf(fmap,"# %d %d # (mesh size)\n",nmesh_x,nmesh_y);
	  fprintf(fmap,"# %d %d # meshsiz_x meshsiz_y\n",meshsiz_x,meshsiz_y);
	  fprintf(fmap,"# %g %g # msky msigma\n",msky,msigm);
	  for(j=0;j<meshsiz_y;j++)
	    {
	      for(i=0;i<meshsiz_x;i++)
		{
		  fprintf(fmap,"%d %d %6.2f\n",i,j,rmesh[i+meshsiz_x*j]);
		}
	    }
	  if(fmap!=stdout) fclose(fmap);
	}


      /*
       *** prepare for output ***
       */  

      /* Now sky subtract */

      skysub(g2,npx,npy,rmesh,meshsiz_x,meshsiz_y,
	     nmesh_x,nmesh_y,mode,pixignr);
      free(rmesh);
      free(sgmesh);      

      statsk(g2,npx,npy,fact,ncycle,&gmax,&gmin,&gmean,&gsd,pixignr);
      
      /***** set output format *******/

      fprintf(stderr,"%s\n",fnamout);

      imh_inherit(&imhin,&icomin,&imhout,&icomout,fnamout);
      imclose(fpin,&imhin,&icomin);

      if (imhout.dtype==DTYPFITS)
	{
	  if(dtype[0]=='\0'||(fitsdtype=imc_fits_dtype_string(dtype))==-1)
	    (void)imc_fits_get_dtype( &imhout, &fitsdtype, NULL, NULL, NULL);

	  /* 2000/07/02 */
	  if(bzeroset!=1)
	    (void)imc_fits_get_dtype( &imhout, NULL, &bzero, &bscale, NULL);

	  /* re-set bzero & bscale */
	  if(imc_fits_set_dtype(&imhout,fitsdtype,bzero,bscale)==0)
	    {
	      printf("Error\nCannot set FITS %s\n",fnamout);
	      printf("Type %d BZERO %f BSCALE %f\n",fitsdtype,bzero,bscale);
	      exit(-1);
	    }
	}
      else
	{	  
	  if (strstr(dtype,"I2"))
	    {
	      imhout.dtype=DTYPI2;
	    }
	  else if (strstr(dtype,"INT"))
	    {
	      imhout.dtype=DTYPINT;
	    }
	  else if (strstr(dtype,"I4"))
	    {
	      imhout.dtype=DTYPI4;
	    }
	  else if (strstr(dtype,"R4"))
	    {
	      imhout.dtype=DTYPR4;
	    }
	  else if (strstr(dtype,"R8"))
	    {
	      imhout.dtype=DTYPR8;
	    }
	  else
	    {
	      imhout.dtype=DTYPU2;
	      imset_u2off(&imhout,&icomout,500);  
	    }
	}
    

      if(ignor!=(float)INT_MIN)
	{
	  imset_pixignr(&imhout, &icomout, (int)ignor);
	  /* replace pixignr */
	  for(i=0;i<imhout.npx*imhout.npy;i++)
	    if(g2[i]==(float)pixignr) g2[i]=(float)ignor;
	  pixignr=ignor;
	}
      else
	{
	  imset_pixignr(&imhout, &icomout, pixignr);
	}

      /**** output image ****/


      imaddhistf(&icomout,
		 "Sky subtracted by skysb3b, mesh %3dx%3d sky%7.2f+%7.2f",
		 nmesh_x,nmesh_y,msky,msigm);
      
      if (imget_fits_value(&icomout, "SSBMSH-I", buffer )==0)
	{
	  imupdate_fitsf(&icomout, "SSBMSH-I", "%20d / %-46.46s", 
		      nmesh_x , "SKY MESH X PIXEL" );
	  imupdate_fitsf(&icomout, "SSBMSH-J", "%20d / %-46.46s", 
		      nmesh_y , "SKY MESH Y PIXEL" );
	  imupdate_fitsf(&icomout, "SSB-EST", "%20.4f / %-46.46s", 
		      msky, "TYPICAL SKY ADC ESTIMATED" );
	  imupdate_fitsf(&icomout, "SSGM-EST", "%20.4f / %-46.46s", 
		      msigm, "TYPICAL SKY SIGMA ADC ESTIMATED" );
	}                  
	  
      if ((fpout= imwopen(fnamout,&imhout,&icomout))==NULL) 
	{
	  printf("Cannot open file %s !!\n",fnamout);
	  exit(-1);
	}

      imwall_rto( &imhout, fpout, g2 );
     
      free(g);
      imclose(fpout,&imhout,&icomout);


      /*
	printf("\n");
	printf("                 --- skysb3b  PROGRAM ENDED ---\n");
      */
  return 0;
}
示例#16
0
文件: cpost.c 项目: pmuellr/cpost
/*------------------------------------------------------------------
 * parse command line for options
 *------------------------------------------------------------------*/
static void GetOptions(
   int   *argc,
   char  *argv[],
   Info  *info
   )
   {
   int            oHelp;
   char          *oBrack;
   char          *oTabs;
   char          *oCtype;
   char          *oHtype;
   char          *oSort;
   char          *oFile;
   char          *oSpace;
   char          *oKeys;
   char          *oBreak;
   char          *oTemp;
   char          *oImbed;
   char          *oDuplex;
   char          *oXlate;
   char          *numLeft;
   char          *s1;
   char          *s2;
   char          *oWrap;
   char          *oRepHdr;

   /*---------------------------------------------------------------
    * parse arguments
    *---------------------------------------------------------------*/
   parsearg(argc,argv,0,PROGRAM_ENVV,"-",
            Strcopy("? b@ c@ d@ h@ k@ i@ n@ o@ p@ r@ s@ t@ w@ x@ y@"),
            &oHelp,&oBrack,&oCtype,&oDuplex,&oHtype,&oKeys,&oImbed,
            &oSpace,&oFile,&oBreak,&oRepHdr,&oSort,&oTabs,&oWrap,
            &oXlate,&oTemp);

   /*---------------------------------------------------------------
    * check parms
    *---------------------------------------------------------------*/
   if (oHelp || (*argc < 2))
      Usage();

   if ('?' == *argv[1])
      Usage();

   /*---------------------------------------------------------------
    * apply option defaults
    *---------------------------------------------------------------*/
   if ((NULL == oBrack ) || ('\0' == *oBrack ))  oBrack  = "+";
   if ((NULL == oCtype ) || ('\0' == *oCtype ))  oCtype  = "c";
   if ((NULL == oDuplex) || ('\0' == *oDuplex))  oDuplex = "-";
   if ((NULL == oHtype ) || ('\0' == *oHtype ))  oHtype  = "h";
   if ((NULL == oKeys  ) || ('\0' == *oKeys  ))  oKeys   = "";
   if ((NULL == oImbed ) || ('\0' == *oImbed ))  oImbed  = "";
   if ((NULL == oSpace ) || ('\0' == *oSpace ))  oSpace  = "2";
   if ((NULL == oFile  ) || ('\0' == *oFile  ))  oFile   = NULL;
   if ((NULL == oBreak ) || ('\0' == *oBreak ))  oBreak  = "+";
   if ((NULL == oRepHdr) || ('\0' == *oRepHdr))  oRepHdr = "";
   if ((NULL == oSort  ) || ('\0' == *oSort  ))  oSort   = "tn";
   if ((NULL == oTabs  ) || ('\0' == *oTabs  ))  oTabs   = "4";
   if ((NULL == oWrap  ) || ('\0' == *oWrap  ))  oWrap   = "";
   if ((NULL == oXlate ) || ('\0' == *oXlate ))  oXlate  = Strcopy("0,0");
   if ((NULL == oTemp  ) || ('\0' == *oTemp  ))  oTemp   = "";

   /*---------------------------------------------------------------
    * bracketing option
    *---------------------------------------------------------------*/
   info->oBrack = (int) strtol(oBrack,NULL,10);
   if (0 == info->oBrack)
      {
      if ((1 != strlen(oBrack)) || (NULL == strchr("-+",*oBrack)))
         cPostError(1,"invalid value on -b option");

      if ('+' == *oBrack)
         info->oBrack = 1000;
      else
         info->oBrack = 0;
      }

   /*---------------------------------------------------------------
    * extensions for C files
    *---------------------------------------------------------------*/
   info->oCtype = oCtype;

   /*---------------------------------------------------------------
    * duplex
    *---------------------------------------------------------------*/
   if ((1 != strlen(oDuplex)) || (NULL == strchr("-+",*oDuplex)))
      cPostError(1,"invalid value on -d option");

   info->oDuplex  = ('+' == *oDuplex);

   /*---------------------------------------------------------------
    * extensions for H files
    *---------------------------------------------------------------*/
   info->oHtype = oHtype;

   /*---------------------------------------------------------------
    * reserved words
    *---------------------------------------------------------------*/
   InitializeReservedHash(info,oKeys);

   /*---------------------------------------------------------------
    * imbed option
    *---------------------------------------------------------------*/
   info->oImbed  = oImbed;

   /*---------------------------------------------------------------
    * space option
    *---------------------------------------------------------------*/
   info->oSpace = (int) strtol(oSpace,&numLeft,10);
   if (*numLeft || (info->oSpace < 0))
      cPostError(1,"invalid value on -n option");

   /*---------------------------------------------------------------
    * output file option
    *---------------------------------------------------------------*/
   if (NULL == oFile)
      info->oFile = stdout;
   else
      {
      info->oFile = fopen(oFile,"w");
      if (NULL == info->oFile)
         cPostError(1,"error opening output file %s for writing",oFile);
      }

   /*---------------------------------------------------------------
    * page break option
    *---------------------------------------------------------------*/
   if ((1 != strlen(oBreak)) || (NULL == strchr("-+",*oBreak)))
      cPostError(1,"invalid value on -p option");

   info->oBreak  = ('+' == *oBreak);

   /*---------------------------------------------------------------
    * replace PS header
    *---------------------------------------------------------------*/
   info->oRepHdr = oRepHdr;

   /*---------------------------------------------------------------
    * sort option
    *---------------------------------------------------------------*/
   if ((0 != Stricmp("nt",oSort)) && (0 != Stricmp("tn",oSort)))
      cPostError(1,"invalid value on -s option");

   info->oSort  = Strupr(oSort);

   /*---------------------------------------------------------------
    * tabs option
    *---------------------------------------------------------------*/
   info->oTabs = (int) strtol(oTabs,NULL,10);
   if (0 == info->oTabs)
      cPostError(1,"invalid value on -t option");

   /*---------------------------------------------------------------
    * wrap PS around output
    *---------------------------------------------------------------*/
   info->oWrapB = strtok(oWrap,";");
   info->oWrapA = strtok(NULL,"");

   /*---------------------------------------------------------------
    * translate option
    *---------------------------------------------------------------*/
   s1 = strtok(oXlate,",");
   s2 = strtok(NULL,"");

   if (!s1 || !s2)
      cPostError(1,"invalid value on -x option");

   info->oXlateX = (int) strtol(s1,NULL,10);
   info->oXlateY = (int) strtol(s2,NULL,10);

   /*---------------------------------------------------------------
    * temp path
    *---------------------------------------------------------------*/
   if (!strlen(oTemp))
      info->oTemp = "";

   else
      {
      char c;

      c = oTemp[strlen(oTemp) - 1];
      if (('\\' == c) || ('/' == c))
         info->oTemp = oTemp;
      else
         {
         info->oTemp = malloc(2+strlen(oTemp));
         strcpy(info->oTemp,oTemp);
         strcat(info->oTemp,"/");
         }
      }


   }
示例#17
0
文件: distcorr5.c 项目: eterps/pwrake
int main(int argc, char **argv)
{
  float *f,*g;
  int npx=2046,npy=4090;

  float pixignr=0;
  double xcen=5000,ycen=4192;
  double xpos=-FLT_MAX,ypos=-FLT_MAX;

  double a[N+1]={0,A1,A2,A3,A4,A5,A6,A7};
  int npx2,npy2,xshift,yshift;
  int i;
  char fnamin[255]="";
  char fnamout[255]="";
  char dtype[255];
  int ignor=INT_MIN;
  float bzero=0.0,bscale=1.0;
  FILE *fpin,*fpout;
  struct imh imhin={""}, imhout={""};
  struct icom icomin={0}, icomout={0};
  int quickmode=0; /* default slow */
  int keepSB=1; /* default keep SB, not flux */





  /* for WCS */


  double b11=1.0,b12=0.0,b21=0.0,b22=1.0;



  /***** parse options ******/

  getargopt opts[20];
  char *files[3]={NULL};
  int n=0;
  int keepflux=0;

  files[0]=fnamin;
  files[1]=fnamout;

  n=0;
  setopts(&opts[n++],"-x=", OPTTYP_DOUBLE , &xpos,
	  "chip offset x from the center(always needed)");
  setopts(&opts[n++],"-y=", OPTTYP_DOUBLE , &ypos,
	  "chip offset y from the center(always needed)");


  setopts(&opts[n++],"-quick", OPTTYP_FLAG , &quickmode,
	  "quick mode (default: quick)",1);
  setopts(&opts[n++],"-keepflux", OPTTYP_FLAG , &keepflux,
	  "keep flux mode (default:keep SB)",1);

  /*
    setopts(&opts[n++],"-reverse", OPTTYP_FLAG , &reverse,
	  "reverse(not impl.)",1);
  */

  setopts(&opts[n++],"-a2=", OPTTYP_DOUBLE , &(a[2]),
	  "a2(default:0)");
  setopts(&opts[n++],"-a3=", OPTTYP_DOUBLE , &(a[3]),
	  "a3(default:4.15755e-10)");
  setopts(&opts[n++],"-a4=", OPTTYP_DOUBLE , &(a[4]),
	  "a4(default:0)");
  setopts(&opts[n++],"-a5=", OPTTYP_DOUBLE , &(a[5]),
	  "a5(default:1.64531e-18)");
  setopts(&opts[n++],"-a6=", OPTTYP_DOUBLE , &(a[6]),
	  "a6(default:0)");
  setopts(&opts[n++],"-a7=", OPTTYP_DOUBLE , &(a[7]),
	  "a7(default:-4.62459e-26)");

  setopts(&opts[n++],"-b11=", OPTTYP_DOUBLE , &(b11),
	  "b11(default:1.0)");
  setopts(&opts[n++],"-b12=", OPTTYP_DOUBLE , &(b12),
	  "b12(default:0.0)");
  setopts(&opts[n++],"-b21=", OPTTYP_DOUBLE , &(b21),
	  "b21(defaulr:0.0)");
  setopts(&opts[n++],"-b22=", OPTTYP_DOUBLE , &(b22),
	  "b22(default:1.0)");

  setopts(&opts[n++],"-bzero=", OPTTYP_FLOAT , &bzero,
	  "bzero");
  setopts(&opts[n++],"-bscale=", OPTTYP_FLOAT , &bscale,
	  "bscale");
  setopts(&opts[n++],"-dtype=", OPTTYP_STRING , dtype,
	  "data_typ(FITSFLOAT,FITSSHORT...)");

  setopts(&opts[n++],"-pixignr=", OPTTYP_FLOAT , &ignor,
	  "pixignr value");

  setopts(&opts[n++],"",0,NULL,NULL);

  if(parsearg(argc,argv,opts,files,NULL)
     ||fnamout[0]=='\0' || xpos==-FLT_MAX || ypos==-FLT_MAX)
    {
      print_help("Usage: distcorr5 [options] filein fileout",
		 opts,"");
      exit(-1);
    }

  if(keepflux==1) keepSB=0;
 
  xcen=-xpos;
  ycen=-ypos;
  
  /* read FILE */
  if ((fpin= imropen(fnamin,&imhin,&icomin))==NULL) 
    {
      printf("File %s not found !!\n",fnamin);
      exit(-1);
    }
  pixignr=(float)imget_pixignr( &imhin );
  npx=imhin.npx;
  npy=imhin.npy;

  f=(float*)malloc(npx*npy*sizeof(float));
  imrall_tor(&imhin,fpin,f,npx*npy);
	
  /* 2002/04/01 */
  /* only "quick" version is implemented */
  g=distcorr_lintrans_quick3(f,npx,npy,pixignr,xcen,ycen,N,a,
			     b11,b12,b21,b22,
			     &npx2,&npy2,&xshift,&yshift,keepSB);

  /* replace pixignr */
  imh_inherit(&imhin,&icomin,&imhout,&icomout,fnamout);
  imclose(fpin,&imhin,&icomin);

  imc_fits_set_dtype(&imhout,FITSFLOAT,bzero,bscale);

  if(ignor!=INT_MIN) 
    {
      for(i=0;i<npx2*npy2;i++)
	if (g[i]==pixignr) g[i]=(float)ignor;
      imset_pixignr(&imhout,&icomout,ignor);
    }
  else
    {
      imset_pixignr(&imhout,&icomout,(int)pixignr);
    }
  imhout.npx=npx2;  
  imhout.npy=npy2;
  imhout.ndatx=npx2;  
  imhout.ndaty=npy2;


  imaddhistf(&icomout,"Distortion corrected with center=(%f,%f)",xcen,ycen);
  if (keepSB==1)
    imaddhistf(&icomout," keep-SB mode.");
  else
    imaddhistf(&icomout," keep-flux mode.");
  imaddhistf(&icomout,"  matrix=(%f,%f)(%f,%f)",b11,b12,b21,b22);
  imaddhistf(&icomout,"  coeff:a2=%e a3=%e a4=%e",a[2],a[3],a[4]);
  imaddhistf(&icomout,"  coeff:a5=%e a6=%e a7=%e",a[5],a[6],a[7]);

  /* WCS revise */
  imc_shift_WCS(&icomout,(float)xshift,(float)yshift);

  /* write FILE */
  if ((fpout= imwopen(fnamout,&imhout,&icomout))==NULL) 
    {
      printf("Cannot open file %s !!\n",fnamout);
      exit(-1);
    }

  imwall_rto( &imhout, fpout, g );
  imclose(fpout,&imhout,&icomout);
  free(g);
  return 0;
}
示例#18
0
文件: total.c 项目: eterps/pwrake
int main(int argc,char **argv)
{
 float *g;
 int i;
 struct imh imhin={""};
 struct icom icomin={0};
 FILE *fp;
 int npx,npy;
 int pixignr;
 double total=0.;
 int disable_pixignr=0;
 char fnamin[BUFSIZ]="";


 /* for getarg */
 /* Ver3. */
 getargopt opts[20];
 char *files[3]={NULL};
 int n=0;
 int helpflag;
 
 files[0]=fnamin;
 
 setopts(&opts[n++],"-disable_pixignr",OPTTYP_FLAG,&disable_pixignr,
	 "add pixignr(blank) as a normal pix.",1);
 setopts(&opts[n++],"",0,NULL,NULL);
 
 helpflag=parsearg(argc,argv,opts,files,NULL);

  if(fnamin[0]=='\0')
   {
      fprintf(stderr,"Error: No input file specified!!\n");
      helpflag=1;
    }
  if(helpflag==1)
    {
      print_help("Usage: total [option] (infilename)",
		 opts,"");
      exit(-1);
    }
 
  /*
   * ... Open Input
   */
 
 if ((fp=imropen(fnamin,&(imhin),&(icomin)))==NULL)
   {
     printf("File %s not found !! ignore. \n",fnamin);
     return -1;
   }
 
 npx=imhin.npx;
 npy=imhin.npy;
 g=(float*)malloc(sizeof(float)*(npy+1)*(npx+1));
 
 imrall_tor(&imhin, fp, g, npx*npy);
 pixignr=imget_pixignr(&imhin);
 
 imclose(fp,&imhin,&icomin);

 if(disable_pixignr==1) 
   for(i=0;i<npx*npy;i++)
     {
       total+=(double)g[i];
     }
 else
   for(i=0;i<npx*npy;i++)
     {
       if(g[i]!=(float)pixignr)
	 total+=(double)g[i];
     }
 
 printf("%f\n",total);
 free(g);
 return 0;
}
示例#19
0
int main(int argc, const char *argv[])
{
	fake * fk = newfake();

	// 解析参数
	int parseret = parsearg(fk, argc, argv);
	if (parseret != 0)
	{
		return parseret;
	}

	if (g_iscompiled)
	{
		fksetargv(fk, argc - 1, argv + 1);
	}
	else
	{
		fksetargv(fk, argc - 2, argv + 2);
	}
	fkopenalllib(fk);
	fkseterrorfunc(fk, error_log);

	// for test
	fkreg(fk, "test_cfunc1", test_cfunc1);
	fkreg(fk, "new_test_class1", new_test_class1);
	fkreg(fk, "new_test_class2", new_test_class2);
	fkreg(fk, "delete_test_class1", delete_test_class1);
	fkreg(fk, "delete_test_class2", delete_test_class2);
	fkreg(fk, "test_memfunc1", &test_class1::test_memfunc1); 
	fkreg(fk, "test_memfunc1", &test_class2::test_memfunc1); 
	fkreg(fk, "test_memfunc2", &test_class2::test_memfunc2); 

	// 编译后文件
	if (g_iscompiled)
	{
		// 打开自己
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, 0, selftmpbuf, selfsize))
		{
			return -1;
		}

		int startpos = 0;
		int size = 0;
		memcpy(&startpos, g_replacebuff, sizeof(startpos));
		memcpy(&size, g_replacebuff + 4, sizeof(size));

		if (fkloadfunc(fk, selftmpbuf + startpos, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(selftmpbuf);
	}
	// 解析文件
	else if (!g_isload)
	{
		fkparse(fk, argv[1]);
		if (fkerror(fk))
		{
			return -1;
		}
	}
	// 读文件
	else
	{
		// 读文件
		char * tmpbuf = 0;
		int size = 0;
		if (!readfile(argv[1], 0, tmpbuf, size))
		{
			return -1;
		}

		if (fkloadfunc(fk, tmpbuf, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(tmpbuf);
		printf("load from %s ok, size %d\n", argv[1], size);
	}

	// 存文件
	if (g_issave)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("save func fail\n");
			return -1;
		}

		const char * filename = "fake.bin";
		if (!writefile(filename, tmpbuf, size))
		{
			return -1;
		}
		free(tmpbuf);
		
		printf("save to %s ok, size %d\n", filename, size);
		
		return 0;
	}

	// 编译到一起
	if (g_iscompile)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("compile func fail\n");
			return -1;
		}

		// 打开自己
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, size, selftmpbuf, selfsize))
		{
			return -1;
		}

		// 替换内存中的字符串
		bool isfind = false;
		for (int i = 0; i < selfsize; i++)
		{
			if (memcmp(selftmpbuf + i, g_replacebuff, strlen(g_replacebuff)) == 0)
			{
				memcpy(selftmpbuf + i, &selfsize, sizeof(selfsize));
				memcpy(selftmpbuf + i + 4, &size, sizeof(size));
				isfind = true;
				break;
			}
		}
		if (!isfind)
		{
			printf("replace %s pos fail\n", argv[0]);
			return -1;
		}

		// 复制后面的
		memcpy(selftmpbuf + selfsize, tmpbuf, size);
		free(tmpbuf);

		// 输出
		const char * filename = "out.exe";
		if (!writefile(filename, selftmpbuf, selfsize + size))
		{
			return -1;
		}
		free(selftmpbuf);

		printf("compile to %s ok, size %d\n", filename, selfsize + size);

		return 0;
	}

#ifndef WIN32
	if (g_isopengoogleprofile)
	{
		ProfilerStart("fake.prof");
	}
#endif

	uint32_t begintime = time(0);
	int fkret = 0;

	// run
	for (int i = 0; i < g_testnum; i++)
	{
		if (!g_isopenjit)
		{
			if (g_isstep)
			{
				fkret = fkdebugrun<int>(fk, "main");
			}
			else
			{
				fkret = fkrun<int>(fk, "main");
			}
		}
		else
		{
			fkret = fkrunjit<int>(fk, "main");
		}
	}
	
	uint32_t endtime = time(0);

#ifndef WIN32
	if (g_isopengoogleprofile)
	{
		ProfilerStop();
	}
#endif

	if (fkerror(fk))
	{
		return -1;
	}

	if (g_isopenprofile)
	{
		printf("\n%s", fkdumpprofile(fk));
	}

	if (g_isprintoutput)
	{
		printf("main return : %d, use time %d\n", fkret, endtime - begintime);
	}

	delfake(fk);

	return 0;
}
示例#20
0
int main(int argc,char *argv[])
{
  struct imh imhin={""},imhout={""};
  struct icom icomin={0},icomout={0};

  char fnamin[100]="";
  char fnamout[100]="";
  char tmp[100]="";

  FILE *fp,*fp2;
  float *f,*g,*h;
  int i;
  int xmin=-1,xmax=-1,ymin=-1,ymax=-1;
  int ymin2,ymax2;
  int offst;
  float bzero=0,bscale=1.0,bzero_new=FLT_MIN,bscale_new=FLT_MIN;
  float blank_new=FLT_MIN;
  float pixignr=INT_MIN;
  int fitsdtype=-1;

  int npx,npy,npx2,npy2,npxos,npyos,npxef[NREGION],npyef[NREGION];
  int npxef0=0;
  int xflip,yflip;
  int region;
  char regid[2],key[10],comment[80];

  int efminx[NREGION],efmaxx[NREGION],efminy[NREGION],efmaxy[NREGION];
  int osminx[NREGION],osmaxx[NREGION],osminy[NREGION],osmaxy[NREGION];

  int j=0;
  char dtype[BUFSIZ]="";

  int notrim=0; 
  int no_y=0;

  /* test */
  int flag_norm=0;

  float gain[NREGION]={0};


  int fit_param=-1;


  getargopt opts[20];
  char *files[3]={NULL};
  int nopt=0;
  int helpflag;

  files[0]=fnamin;
  files[1]=fnamout;


  /* only trim version is supported now */
  setopts(&opts[nopt++],"-notrim", OPTTYP_FLAG , &notrim,
	  "not trim off(default:trim)",1);
  setopts(&opts[nopt++],"-no-y", OPTTYP_FLAG , &no_y,
	  "not subtract y-overscan(default:subtract)",1);

  setopts(&opts[nopt++],"-bzero=", OPTTYP_FLOAT , &bzero_new,
	  "bzero");
  setopts(&opts[nopt++],"-bscale=", OPTTYP_FLOAT , &bscale_new,
	  "bscale");
  setopts(&opts[nopt++],"-dtype=", OPTTYP_STRING , dtype,
	  "datatyp(FITSFLOAT,FITSSHORT...)");
  setopts(&opts[nopt++],"-pixignr=", OPTTYP_FLOAT , &blank_new,
	  "pixignr value");
  setopts(&opts[nopt++],"",0,NULL,NULL);

  helpflag=parsearg(argc,argv,opts,files,NULL);

  if(fnamout[0]=='\0')
   {
      fprintf(stderr,"Error: No input file specified!!\n");
      helpflag=1;
    }
  if(helpflag==1)
    {
      print_help("Usage: osmed4 <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  /*
   * ... Open Input
   */

  (void)printf("\n Input = %s\n",fnamin );

  if( (fp = imropen ( fnamin, &imhin, &icomin )) == NULL ) 
    {
      print_help("Usage: %s <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  npx=imhin.npx;
  npy=imhin.npy;

  /* get information here */
  npx2=0;
  npy2=0;
  npxos=0;
  npyos=0;

  imget_fits_value(&icomin,"S_XFLIP",tmp);
  printf("debug: xflip [%s]\n",tmp);
  if (tmp[0]=='T') xflip=1; else xflip=0;

  imget_fits_value(&icomin,"S_YFLIP",tmp);
  if (tmp[0]=='T') yflip=1; else yflip=0;

  xmin=npx;
  xmax=-1;
  ymin=npy;
  ymax=-1;
  ymin2=npy;
  ymax2=-1;

  for(region=0;region<NREGION;region++)
    {
      if (xflip==0)
	sprintf(regid,"%1d",region+1);
      else
	sprintf(regid,"%1d",NREGION-region);

      sprintf(key,"S_EFMN%c1",regid[0]);
      imget_fits_int_value(&icomin,key,&(efminx[region]));
      sprintf(key,"S_EFMX%c1",regid[0]);
      imget_fits_int_value(&icomin,key,&(efmaxx[region]));
      sprintf(key,"S_EFMN%c2",regid[0]);
      imget_fits_int_value(&icomin,key,&(efminy[region]));
      sprintf(key,"S_EFMX%c2",regid[0]);
      imget_fits_int_value(&icomin,key,&(efmaxy[region]));
     
      efminx[region]--;
      efmaxx[region]--;
      efminy[region]--;
      efmaxy[region]--;

      printf("debug:EF: %d %d %d %d\n",
	     efminx[region],efmaxx[region],efminy[region],efmaxy[region]);

      if(efmaxx[region]<efminx[region]) exit(-1);
      if(efmaxy[region]<efminy[region]) exit(-1);

      npxef[region]=efmaxx[region]-efminx[region]+1;
      npyef[region]=efmaxy[region]-efminy[region]+1;    
      
      if(xmin>efminx[region]) xmin=efminx[region];
      if(xmax<efmaxx[region]) xmax=efmaxx[region];
      if(ymin>efminy[region]) ymin=efminy[region];
      if(ymax<efmaxy[region]) ymax=efmaxy[region];

      if(ymin2>efminy[region]) ymin2=efminy[region];
      if(ymax2<efmaxy[region]) ymax2=efmaxy[region];

      printf("debug: npx2=%d\n",npx2);
      npx2+=npxef[region];

      printf("debug: region %d: %d x %d \n",
	     region,npxef[region],npyef[region]);

      sprintf(key,"S_OSMN%c1",regid[0]);
      imget_fits_int_value(&icomin,key,&(osminx[region]));
      sprintf(key,"S_OSMX%c1",regid[0]);
      imget_fits_int_value(&icomin,key,&(osmaxx[region]));
      sprintf(key,"S_OSMN%c2",regid[0]);
      imget_fits_int_value(&icomin,key,&(osminy[region]));
      sprintf(key,"S_OSMX%c2",regid[0]);
      imget_fits_int_value(&icomin,key,&(osmaxy[region]));

      osminx[region]--;
      osmaxx[region]--;
      osminy[region]--;
      osmaxy[region]--;

      printf("debug:OS: %d %d %d %d\n",
	     osminx[region],osmaxx[region],osminy[region],osmaxy[region]);

      if(ymin2>osminy[region]) ymin2=osminy[region];
      if(ymax2<osmaxy[region]) ymax2=osmaxy[region];

      if (npxos<osmaxx[region]-osminx[region]+1)
	npxos=osmaxx[region]-osminx[region]+1;

      if (flag_norm==1)
	{
	  sprintf(key,"S_GAIN%c",regid[0]);
	  imget_fits_float_value(&icomin,key,&(gain[region]));
	}
      if (npyos<osmaxy[region]-osminy[region]+1)
	npyos=osmaxy[region]-osminy[region]+1;
    }
  npy2=ymax-ymin+1;

  printf("debug: y %d-%d\n",ymin,ymax);
  printf("debug: effective size: %dx%d\n",npx2,npy2);

  /* output */
  

  imh_inherit(&imhin,&icomin,&imhout,&icomout,fnamout);
  if(!notrim)
    {
      imhout.npx   = npx2;
      imhout.npy   = npy2;
      imhout.ndatx = imhout.npx;
      imhout.ndaty = imhout.npy;
    }
  else
    {
      imhout.npx   = npx;
      imhout.npy   = npy;
      imhout.ndatx = imhout.npx;
      imhout.ndaty = imhout.npy;
    }

  if(dtype[0]=='\0')
    {
      imc_fits_get_dtype( &imhout, &fitsdtype, &bzero, &bscale, &offst );
      /** force FLOAT **/
      fitsdtype=FITSFLOAT;
    }
  else
    if ((fitsdtype=imc_fits_dtype_string(dtype))==-1)
      {
	printf("\nWarning: Unknown fits dtype %s. Inheriting original.\n",dtype);
	imc_fits_get_dtype( &imhout, &fitsdtype, &bzero, &bscale, &offst );
      }

  if(bzero_new!=FLT_MIN)
    {
      bzero=bzero_new;
    }
  else
    bzero=0;

  if(bscale_new!=FLT_MIN)
    {
      bscale=bscale_new;
    }
  else
    bscale=1.0;
  
  (void)imc_fits_set_dtype( &imhout, fitsdtype, bzero, bscale );

  if(blank_new!=FLT_MIN)
    imset_pixignr(&imhout,&icomout,(int)blank_new);    
  else
    {
      pixignr=(float)imget_pixignr(&imhin);
      imset_pixignr(&imhout,&icomout,(int)pixignr);
    }

  if (fit_param>0)
    {
      imaddhist(&icomout,"OSMED5: Overscan value is smoothed");
    }
  else
    {
      imaddhist(&icomout,"OSMED5: X-Overscan median is subtracted line by line.");
      if(no_y==0)
	imaddhist(&icomout,"OSMED5: Y-Overscan median is subtracted row by row.");
    }

  if (!notrim)
    {
      imaddhistf(&icomout,"OSMED5: And trimmed");
    }
  (void)printf("\n Output = %s\n",fnamout );


  if(!notrim)
    {
      imupdate_fitsf(&icomout, "EFP-MIN1",IMC_FITS_INTFORM,
		     1,
		     "Start position of effective frame in axis-1");
      
      imupdate_fitsf(&icomout, "EFP-MIN2",IMC_FITS_INTFORM,
		     1,
		     "Start position of effective frame in axis-2");
      
      imupdate_fitsf(&icomout, "EFP-RNG1",IMC_FITS_INTFORM,
		     npx2,
		     "Range of effective frame in axis-1");
      
      imupdate_fitsf(&icomout, "EFP-RNG2",IMC_FITS_INTFORM,
		     npy2,
		     "Range of effective frame in axis-2");
      imc_shift_WCS(&icomout,(float)xmin,(float)ymin);

      /* 2008/08/28 header revision more */
      /* tenuki kimeuchi */
      /* ch1->ch4 ? ch4->ch1?? */

      /* tenuki again */
      npxef0=0;
      for (i=0;i<NREGION;i++)
	{
	  if (xflip==0)	
	    j=i+1;
	  else
	    j=NREGION-i;
	 
	  sprintf(key,"S_EFMN%d1",j);
	  sprintf(comment,"MIN pixel of x-effective range for ch%d",j);
	  imupdate_fitsf(&icomout,key,IMC_FITS_INTFORM,
			 npxef0+1,comment);
	  sprintf(key,"S_EFMX%d1",j);
	  sprintf(comment,"MAX pixel of x-effective range for ch%d",j);
	  imupdate_fitsf(&icomout,key,IMC_FITS_INTFORM,
			 npxef0+npxef[i],comment);

	  npxef0+=npxef[i];

	  sprintf(key,"S_EFMN%d2",j);
	  sprintf(comment,"MIN pixel of y-effective range for ch%d",j);
	  imupdate_fitsf(&icomout,key,IMC_FITS_INTFORM,
			 1,comment);
	  sprintf(key,"S_EFMX%d2",j);
	  sprintf(comment,"MAX pixel of y-effective range for ch%d",j);
	  imupdate_fitsf(&icomout,key,IMC_FITS_INTFORM,
			 npy2,comment);
	}
    }

  f=(float*)malloc(npx*npy*sizeof(float));  
  imrall_tor(&imhin, fp, f, npx*npy );
  imclose(fp,&imhin,&icomin);

  g=(float*)calloc(npx*npy,sizeof(float));  

  /* overscan estimation and subtract */
  for(region=0;region<NREGION;region++)
    {
      overscansub_x(npx,npy,f,g,
		    efminx[region],efmaxx[region],
		    osminx[region],osmaxx[region],
		    ymin2,ymax2);
      if(no_y==0)
	{
	  /* 2008/07/26 Overscan Y added*/
	  overscansub_y(npx,npy,g,f,
			efminy[region],efmaxy[region],
			osminy[region],osmaxy[region],
			efminx[region],efmaxx[region]);
	}
    }
  if(no_y!=0)
    memcpy(f,g,npx*npy*sizeof(float));


  if( (fp2 = imwopen( fnamout, &imhout, &icomout )) == NULL )
    {
      print_help("Usage: %s <options> [filein] [fileout]",
		 opts,
		 "");
      exit(-1);
    }

  if(notrim)
    {
      imwall_rto( &imhout, fp2, h);
    }
  else
    {
      /* copy effective regions to g */
      i=0;
      for(region=0;region<NREGION;region++)
	{
	  for(j=ymin;j<=ymax;j++)
	    {
	      memcpy(g+i+(j-ymin)*npx2,f+efminx[region]+j*npx,
		     (efmaxx[region]-efminx[region]+1)*sizeof(float));
	    }
	  i+=(efmaxx[region]-efminx[region]+1);
	}
      imwall_rto( &imhout, fp2, g);	  
    }

  (void) imclose(fp2,&imhout,&icomout);
  return 0;
}