Ejemplo n.º 1
0
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;
}
Ejemplo n.º 2
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 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;
}
Ejemplo n.º 3
0
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;
}
Ejemplo n.º 4
0
/* --------------------------------------------------------------- */
FILE *imwopen_fits (
/* ---------------------------------------------------------------
 *
 * Description:  <IM>age <W>rite <OPEN>
 * ============
 *
 *      imwopen_fits() writes the header portion of a fits
 *      file. It does not fill pixel data but returns a FILE
 *      pointer where the pixel data should start.
 *
 *      Note:
 *      0) The File name SHOULD BE xxx.fits
 *      1) pix file is NOT closed by imwopen. Someone should close it.
 *      2) FILE pointer IS MOVED to the start of pixel data by imwopen.
 *
 * Condition prior to call:
 * ========================
 *
 *      There are many paremeters in imh header to be filled. 
 *	imwopen_fits() fills most of them for you. You have to
 *      fill the following parameters prior to call imwopen:
 *
 *      imhp->dtype     iraf data type
 *      imhp->npx       x image size
 *      imhp->npy       y image size
 *
 *      If you like to add more comments, please do so using
 *      imaddcom.
 *
 * Arguments:
 * ==========
 */
        char        *fnam,      /* (in) file name WITH .fits */
        struct imh  *imhp,      /* (in) ptr to imh header structure */
        struct icom *comp)      /* (in) ptr to comment struct */
/*
 * Return value:
 * =============
 *      File pointer address where pixel data starts.
 *      Will be NULL pointer if faile to open files.
 *
 * Caution:
 * ========
 *      (1) imwopwn DOES OVERWRITE the existing files with the 
 *	    same name. Users should check the existing files 
 *          if needed.
 *
 * ---------------------------------------------------------------
 */
{
  char /**cp,*/ zero=' ';
  char **fh;

  char temp[NCHAFITS+1];
  int i, nlin;
  int dtype;
  int odd, nzero;
  int pixoff;
#ifdef HAVE_FSEEKO
  off_t nblk;
  off_t filloff;
  off_t size;
  off_t total_size;
#else
  int nblk;
  int filloff;
  int size;
  int total_size;
#endif
  float bzero;
  float bscale;
  FILE *fp;
  int mfitsh=MFITSH;
  /* Yagi added */
  /*
    char key[10],val[80],com[80];
    float fval;
    int ival;
  */

  /* 2003/11/04 */
  imhp->buff=NULL;

  fh=(char**)malloc(sizeof(char*)*mfitsh);
  if(fh==NULL)
    {
      fprintf(stderr,"Cannot allocate memory for fh in imwopen_fits\n");
      /* 2000/09/19 */
      /* mfitsh should be set smaller and retry*/
      /* but not implemented yet...*/
      exit(-1);
    }

  for(i=0;i<mfitsh;i++)
    {
      fh[i]=(char*)malloc(sizeof(char)*(NCHAFITS+1));
      if(fh[i]==NULL)
	{
	  fprintf(stderr,"Cannot allocate memory for fh[%d] in imwopen_fits\n",i);
	  exit(-1);
	}


      /* fill space */
      memset((&fh[i][0]),' ',(NCHAFITS+1));
    }
  /*
   * ... check input paramters
   */
  
  /* ... check FITS date type ... */
  if( imhp->dtype != DTYPFITS ) {
    (void) printf("Imwopen_fits: wrong imh.dtype\n");
    return NULL;
  }
  
#ifndef FORCEFITS
  /* ... check file name ... */
  if( strstr( fnam, FITSEXTEN ) == NULL ) {
    (void) printf("Imwopen_fits: file name should be xx.fits\n");
    return NULL;
  }
#endif
  
  /* ... check npx & npy ... */
  if( imhp->npx < 0 || imhp->npy < 0 ) {
    (void) printf("Imwopen_fits: npx or npy < 0\n");
    return NULL;
  }
  
  if( imhp->npx == 0 && imhp->npy == 0 ) {
    (void) printf("Imwopen_fits: npx = npy =0\n");
    return NULL;
  }
  
  /* ... Check dtype ... */
  (void)imc_fits_get_dtype(imhp,&dtype,&bzero,&bscale,&pixoff);
  /* printf("debug: 2006-08-02 %f %f\n",bzero,bscale); */
  
  if( dtype != FITSCHAR  &&
     dtype != FITSSHORT &&
     dtype != FITSINT   &&
     dtype != FITSFLOAT ) {
    (void) printf("Imwopen_fits: Unkown BITPIX %d\n",dtype);
    (void) printf("Make sure to use pointer of imhd for imc_fits_set_dtype()\n");
    return NULL;
  }
  
  /* ... Determine Naxis ... */
  imhp->naxis = 0;
  if( imhp->npx > 0 ) imhp->naxis++ ;
  if( imhp->npy > 0 ) imhp->naxis++ ;
  
  
  /*
   * ... make FITS header
   */
  
  
  nlin = 0;
  (void)imc_fits_mklog  (fh[nlin++],"SIMPLE",(int)1,"FITS STANDARD");
  (void)imc_fits_mkint  (fh[nlin++],"BITPIX",dtype,"FITS BITS/PIXEL");
  (void)imc_fits_mkint  (fh[nlin++],"NAXIS",(int)imhp->naxis,"NUMBER OF AXES");
  (void)imc_fits_mkint  (fh[nlin++],"NAXIS1",(int)imhp->npx,"NUMBER OF PIX IN 1ST AXIS");
  (void)imc_fits_mkint  (fh[nlin++],"NAXIS2",(int)imhp->npy,"NUMBER OF PIX IN 2ND AXIS");
  
  /* 2006/08/02 */
  /* here we should add EXTEND keyword */
  (void)imc_fits_mklog  (fh[nlin++],"EXTEND",(int)0,"FITS dataset may contain extensions");
  /* write only NON-EXTEND FITS */

  if(dtype!=FITSFLOAT || bscale!=1.0 || bzero!=0.0)
    {
      (void)imc_fits_mkfloat(fh[nlin++],"BSCALE",bscale,
			     "REAL = FILE*BSCALE + BZERO");
      (void)imc_fits_mkfloat(fh[nlin++],"BZERO",bzero,
			     "REAL = FILE*BSCALE + BZERO");
    }
  /* 2002/07/31 */
  /*
    (void)imdecs( imhp->title, strg );
    (void)imc_fits_mkstrg (fh[nlin++],"OBJECT",strg,"Name of object");
    (void)imdecs( imhp->institute, strg );
    (void)imc_fits_mkstrg (fh[nlin++],"ORIGIN",strg,"Origin");
  */

  /* add iraf comments */
  for(i=0; i<comp->ncom; i++) {
    /* format check needed here (98/06/24)*/
    /*
       (void) imdecs( comp->com[i], strg);
       (void) sprintf( fh[nlin++], "%-80.80s", strg);
    */
    (void) sprintf( fh[nlin++], "%-80.80s", comp->com[i]);
  }
  
  /* ternimate line */
  memset(temp,' ',NCHAFITS);
  (void) sprintf( fh[nlin++], "END%77.77s", temp);
  
  /*
   * ... Open & write to file
   */
  
  if( (fp=fopen(fnam,"w")) == NULL ) {
    (void) printf("Imwopen_fits: can not open %s\n",fnam);
    return NULL;
  }
  
  for( i=0; i<nlin; i++ ) 
    {
      if( fwrite(fh[i],(int)NCHAFITS,(size_t)1,fp) != 1 ) 
	{
	  (void) printf("Imwopen_fits: error writing header\n");
	  return NULL;
	}
    }
  
  /*
   * ... Locate pixel data
   */
  
  odd = (nlin * NCHAFITS) % NBYTEBLK;
  nblk= (nlin * NCHAFITS) / NBYTEBLK;
  if (odd == 0) pixoff =  nblk    * NBYTEBLK;
  else          pixoff = (nblk+1) * NBYTEBLK;
  nzero= pixoff - nlin * NCHAFITS;
  
  /*
    fprintf(stderr,"%d %d %d\n",pixoff,nblk,nlin);
    */
  
  /* write empty data to fill block */
  for( i=0; i<nzero; i++ ) {
    if( fwrite(&zero,(size_t)1,(size_t)1,fp) != 1 ) {
      (void) printf("Imwopen_fits: error filling block\n");
      return NULL;
    }
  }
  
  /*
   * ... Fill Dummy Pix Data
   */
  
  /* pix data byte size */
#ifdef HAVE_FSEEKO
  size = (off_t)(abs(dtype)/8) * (off_t)(imhp->npx) * (off_t)(imhp->npy);
  odd  = size % (off_t)NBYTEBLK;
  nblk = size / (off_t)NBYTEBLK;

  /* debug */
  /*
    printf("debug: sizeof(off_t)=%d\n",sizeof(off_t));
    printf("debug: size=%f\n",(double)size);
    printf("debug: odd=%f\n",(double)odd);
    printf("debug: nblk=%f\n",(double)nblk);
  */
#else
  size = abs(dtype)/8 * imhp->npx * imhp->npy;
  odd  = size % NBYTEBLK;
  nblk = size / NBYTEBLK;
#endif

  /* 2007/05/01 revised */
  
#ifdef HAVE_FSEEKO
  total_size = (off_t)(nblk+1) * (off_t)NBYTEBLK;
#else
  total_size = (nblk+1) * NBYTEBLK;
#endif

  zero='\0';

  if( odd != 0 ) 
    {
#ifdef HAVE_FSEEKO
  filloff = (off_t)pixoff + size;
  if( fseeko(fp,filloff,SEEK_SET) != 0 ) 
#else
    filloff = pixoff + size;
  if( fseek(fp,filloff,SEEK_SET) != 0 ) 
#endif
    {
      (void) printf("Imwopen_fits: Error in fseek to dummy data\n");
      return NULL;
    }
      /* wirte zeros */
      nzero      = total_size - size;
      for( i=0; i<nzero; i++ ) {
	if( fwrite(&zero,(int)1,(size_t)1,fp) != 1 ) {
	  (void) printf("Imwopen_fits: error filling dummy data\n");
	  return NULL;
	}
      }
    } /* end if */
  else
    {
      /* put last data */
#ifdef HAVE_FSEEKO
  filloff = (off_t)pixoff+size-1;
  if( fseeko(fp,filloff,SEEK_SET) != 0 ) 
#else
    filloff = pixoff+size-1;
  if( fseek(fp,filloff,SEEK_SET) != 0 ) 
#endif
    {
      (void) printf("Imwopen_fits: Error in fseek to dummy data\n");
      return NULL;
    }
      if( fwrite(&zero,(int)1,(size_t)1,fp) != 1 ) {
	(void) printf("Imwopen_fits: error filling dummy data\n");
	return NULL;
      }
    }

  /* relocate to first real data */
  if( fseek(fp,pixoff,SEEK_SET) != 0 ) {
    (void) printf("Imwopen_fits: Error in fseek to 1st data\n");
    for(i=0;i<mfitsh;i++)
      free(fh[i]);
    free(fh);
    return NULL;
  }
  
  /*
   * ... Fill some parametes
   */
  
  for(i=0;i<4;i++) 
    imhp->void_2[VID2SIZ-PXOFF-i]=fitsbuff_i1(&pixoff)[i];

  /* free fh */

  for(i=0;i<mfitsh;i++)
    free(fh[i]);
  free(fh);
  
  return( fp );
}
Ejemplo n.º 5
0
/* ------------------------------------------------------------------------ */
int imc_fits_wl(
/* --------------------------------------------------------------------------
 *
 * Description: <IMC> <FITS> <W>rite <L>ine
 * ============
 *      imc_fits_wl() writes real*4 data in a line to a pixel file.
 *      It can write the following data types:
 *
 *	signed char  ( integer*1 )
 *      signed short ( integer*2 )
 *      signed int  ( integer*4 )
 *      float  ( real*4 )
 *
 *      When writing data to u2 or i4, the trancation is
 *      performed since C does not do this automatically:
 *
 *              if( data > i4_max ) data = i4_max
 *              if( data < i4_min ) data = i4_min, or
 *
 *              if( data > u2_max ) data = u2_max
 *              if( data <      0 ) data = 0
 *
 *      These requires addtional CPU time.
 *
 * Arguments:
 * ==========
 */
        struct imh *imhp,       /* (in) ptr to imh struct */
        FILE       *fp,         /* (in) ptr to pixel file */
        float      *dp,        /* (in) ptr to pixel data array */
        int         iy)         /* (in) line # starting with 0 */
/*
 * Note:
 * =====
 *      imc_fits_wl() loads pixel data in an internal array 
 *      whose size is 64K in u_short. The xdim should not exceed
 *      this size.
 *
 * Caution:
 * ========
 *      imwl_fits_wl() writes data into a pixel file according to:
 *
 *              imhp->npx, imhp->npy,
 *              imhp->ndatx, imhp->ndaty.
 *
 *      Since the FITS header is already written when you call
 *      imwopen_fits(), no one can change or adjust ndatx or ndaty.
 *      Please be carfull not to change ndatx or ndaty after
 *      calling imwopen_fits().
 *
 * Revision history:
 * =================
 *    Apr 25, 93: (Maki Sekiguchi) Original creation
 *
 * -----------------------------------------------------------------
 */
{
size_t  size;           /* data size (in byte) to read */

#ifdef HAVE_FSEEKO
off_t pntr_offset;
#else
int pntr_offset;
#endif

int pixignr;
int dtype;
int pixoff;
int ix;
int nbyte;
float *rp;
float bzero;
float bscale;
float bzero_up;

/*
 * ... Check Input Parameters
 */

/* ... check FITS date type ... */
if( imhp->dtype != DTYPFITS ) {
    (void) printf("Imc_fits_wl: wrong imh.dtype\n");
    return( (int)0 );
    }

if( imhp->npx == 0 ) {
   (void) printf("Imc_fits_wl:npx =0\n");
   return( (int)0 );
   }

/* ... Check dtype ... */
(void)imc_fits_get_dtype(imhp,&dtype,&bzero,&bscale,&pixoff);

if( dtype != FITSCHAR  &&
    dtype != FITSSHORT &&
    dtype != FITSINT   &&
    dtype != FITSFLOAT ) {
   (void) printf("Imc_fits_wl: Unknown BITPIX %d",dtype);
   return( (int)0 );
   }

if( bscale == 0.0 ) {
   (void) printf("Imc_fits_wl: Bscale=0\n");
   return( (int)0 );
   }

/*... check work area size */
nbyte= abs(dtype/8);
size = imhp->npx * nbyte;
bzero_up = bzero - 0.5; 

/*
if( size > WRKSIZ ) {
   (void) printf("Imc_fits_wl: Internal buffer too small\n");
   return( (int)0 );
   }
*/
 imhp->buff=realloc(imhp->buff,size);

/*
 * ... Locate pixel pntr
 */

/* offset is in byte */
#ifdef HAVE_FSEEKO
pntr_offset = (off_t)pixoff + (off_t)iy * (off_t)nbyte * (off_t)(imhp->npx);
if( fseeko(fp,pntr_offset,SEEK_SET) != 0 ) 
#else
pntr_offset = pixoff + iy * nbyte * imhp->npx;
if( fseek(fp,pntr_offset,SEEK_SET) != 0 ) 
#endif
  {
   (void) printf("Imc_fits_rl: Error in fseeking\n");
   return( (int)0 );
   }

/*
 * ... Write Data Out
 */
pixignr=imget_pixignr(imhp);

switch ( dtype ) {
  
  /* ============*/
   case FITSCHAR:
  /* ============*/

      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	     fitsbuff_i1(imhp->buff)[ix] = (char)floor( *rp-bzero_up );
         }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_i1(imhp->buff)[ix] = (char)floor( (*rp-bzero)/bscale+0.5);
         }
      if( fwrite((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      break;

  /* ============*/
   case FITSSHORT:
  /* ============*/

      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_i2(imhp->buff)[ix] = (short)floor( (*rp-bzero_up) );
         }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_i2(imhp->buff)[ix] = (short)floor( (*rp-bzero)/bscale+0.5 );
         }
      if(BSWAP) (void)imc_fits_swap16((imhp->buff),(int)(size/SHORT_SIZE)); 
      if( fwrite((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      break;

  /* ============*/
   case FITSINT:
  /* ============*/

      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_i4(imhp->buff)[ix] = (int)floor(*rp-bzero_up);
         }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_i4(imhp->buff)[ix] = (int)floor( (*rp-bzero)/bscale+0.5);
         }
      if(BSWAP) (void)imc_fits_swap32((imhp->buff),(int)(size/INT_SIZE)); 
      if( fwrite((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      break;

  /* ============*/
   case FITSFLOAT:
  /* ============*/

      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            fitsbuff_r4(imhp->buff)[ix] = (float)(*rp - bzero);
         }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	   {
	     fitsbuff_r4(imhp->buff)[ix] = (float) ((*rp - bzero) / bscale);
	   }
         }
      if(BSWAP) 
	(void)imc_fits_swap32((imhp->buff),(int)(size/FLOAT_SIZE));
      if( fwrite((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      break;

  /* ======*/
   default:
  /* ======*/

      (void) printf("Imc_fits_wl: Unsupported data type = %d\n", dtype);
      return 0;
      /* break; */

   } /* end switch */

return 1;

err:
(void) printf("Imc_fits_wl: Error writing pixel data\n");
return( (int)0 );
}
Ejemplo n.º 6
0
/* ------------------------------------------------------------------------ */
int imc_fits_rl( 
/* --------------------------------------------------------------------------
 *
 * Description: <IMC> <FITS> <R>ead <L>ine
 * ============
 *      imc_fits_rl reads line data from a FITS file into a given
 *      real*4 arrray. It can read the following data types:
 *
 *      signed short ( integer*2 )
 *      signed int  ( integer*4 )
 *      float  ( real*4 )
 *
 * Arguments:
 * ==========
 */
        struct imh *imhp,       /* (in) ptr to imh struct */
        FILE       *fp,         /* (in) ptr to pixel file */
        float      *dp,         /* (out) ptr to pixel array to be filled */
        int       iy)          /* (in) Line # start with 0 */
/*
 * Note:
 * =====
 *      Some internal check is (like pix size consistence)
 *      eliminated for speed.
 *
 * Revision history:
 * =================
 *
 * --------------------------------------------------------------------------
 */
{
  size_t size;
  int dtype;
  int pixoff;
  int nbyte;
  int ix;
#ifdef HAVE_FSEEKO
  off_t offset;
#else
  int offset;
#endif
  
  float *rp;
  float bzero;
  float bscale;
  int pixignr;
  
  /*
   * ... Check Input Parameters
   */
  
  /* ... check if this is a fits type ... */
  if( imhp->dtype != DTYPFITS ) {
    (void)printf("Imc_fits_rl: This is not FITS type\n");
    return 0;
  }
  
  if( imhp->npx == 0 ) {
    (void) printf("Imc_fits_rl: npx=0\n");
    return 0;
  }
  
  (void)imc_fits_get_dtype( imhp, &dtype, &bzero, &bscale, &pixoff );
  nbyte= abs(dtype/8);
  
  size = imhp->npx * nbyte;
  
  /*
    
    if( size > WRKSIZ ) {
    (void) printf("Imc_fits_rl: Internal buffer too small\n");
    return 0;
    }
  */
  
  
  /* 2003/11/04 */
  imhp->buff=realloc(imhp->buff,size);
  
  /* ... Reposition file pointer ... */
  
  /* offset is in byte */
#ifdef HAVE_FSEEKO
  offset = (off_t)pixoff + (off_t)iy * (off_t)nbyte * (off_t)(imhp->ndatx);
  if( fseeko(fp,offset,SEEK_SET) != 0 ) 
#else
    offset = pixoff + iy * nbyte * imhp->ndatx;
  if( fseek(fp,offset,SEEK_SET) != 0 ) 
#endif
    {
      (void) printf("Imc_fits_rl: Error in fseeking\n");
      printf("pixoffset=%d offset=%ld\n",pixoff,(long)offset);
      return 0;
    }
  
  /*
   * ... Read Data In
   */
  
  pixignr=imget_pixignr(imhp);
  
  switch ( dtype ) {
    
    /* ============ */ 
  case FITSCHAR:
    /* ============ */ 

      if( fread((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            *rp = bzero + (float)fitsbuff_i1(imhp->buff)[ix];
         }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
            *rp = bzero + bscale * (float)fitsbuff_i1(imhp->buff)[ix];
         }
      break;

  /* ============ */ 
   case FITSSHORT:
  /* ============ */ 

      if( fread((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      if(BSWAP) (void)imc_fits_swap16((imhp->buff),(int)(size/SHORT_SIZE)); 
      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + (float)fitsbuff_i2(imhp->buff)[ix];
	 }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + bscale * (float)fitsbuff_i2(imhp->buff)[ix];
         }
      break;

  /* ============ */ 
   case FITSINT:
  /* ============ */ 

      if( fread((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      if(BSWAP) (void)imc_fits_swap32((imhp->buff),(int)(size/INT_SIZE)); 
      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + (float)fitsbuff_i4(imhp->buff)[ix];
	 }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + bscale * (float)fitsbuff_i4(imhp->buff)[ix];
         }
      break;

  /* ============ */ 
   case FITSFLOAT:
  /* ============ */ 

      if( fread((imhp->buff),size,(size_t)1,fp) != 1 ) goto err;
      if(BSWAP) (void)imc_fits_swap32((imhp->buff),(int)(size/FLOAT_SIZE)); 
      if( bscale == 1.0 ) {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + (float)fitsbuff_r4(imhp->buff)[ix];
	 }
      else {
         for(ix=0,rp=dp;ix<imhp->npx;ix++,rp++)
	    *rp = bzero + bscale * (float)fitsbuff_r4(imhp->buff)[ix];
	 }
      break;

 /* ====== */
   default:
 /* ====== */

      (void) printf("Imc_fits_rl: Unsupported data type = %d\n", dtype);
      return 0;
      /* break; */

   } /* end switch */

return 1;

err:
(void) printf("Imc_fits_rl: Error reading pixel data\n");
return 0;
}
Ejemplo n.º 7
0
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;
}
Ejemplo n.º 8
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;
}