#include <stdio.h>
#define n1 4096
#define n2 4032
char a[n2][n1],head[36][80],b[15];
FILE *fp;
char f1[80];
main(int ac,char **av)
{
  int i,j,k,x1,x2;
  if(ac<2){ printf("\n\t*** produce uband badpixel_fit ***\n");
            printf("\n\t good=0, sigma5=5, sigma10=10\n");
            printf("\n\tUSage: ubad2fit 1  (1~4)\n\n");
            exit(0);
  }
  k=av[1][0]-48; if(k<1)k=1; if(k>4)k=4;
  for(i=0;i<n2;i++)for(j=0;j<n1;j++)a[i][j]=0;

  sprintf(f1,"/line3/uband-data/exchange/data/badpixels/5sigma/ccd%d-all.bad",k);
  fp=fopen(f1,"r"); if(fp==0){ printf("\n%s file not found!\n\n",f1); exit(0); }
l10:
  fgets(b,15,fp); if(feof(fp))goto l20;
  sscanf(b,"%d %d",&x1,&x2);
  if(k==1 && x2==571)goto l10;   // ccd_1, bad line not include here
//  printf("%d %d\n",x1,x2);
  a[x2-1][x1-1]=5;
  goto l10;
l20:
  fclose(fp);

  sprintf(f1,"/line3/uband-data/exchange/data/badpixels/10sigma/ccd%d-all.bad",k);
  fp=fopen(f1,"r"); if(fp==0){ printf("\n%s file not found!\n\n",f1); exit(0); }
l30:
  fgets(b,15,fp); if(feof(fp))goto l40;
  sscanf(b,"%d %d",&x1,&x2);
  if(k==1 && x2==571)goto l30;   // ccd_1, bad line not include here
  a[x2-1][x1-1]=10;
  goto l30;
l40:
  fclose(fp);

  for(i=0;i<36;i++)for(j=0;j<80;j++)head[i][j]=32;
  strcpy(&head[ 0][0], "SIMPLE  =                    T ");
  strcpy(&head[ 1][0], "BITPIX  =                    8 ");
  strcpy(&head[ 2][0], "NAXIS   =                    2 ");
  strcpy(&head[ 3][0], "NAXIS1  =                 4096 ");
  strcpy(&head[ 4][0], "NAXIS2  =                 4032 ");
  strcpy(&head[35][0], "END");
  for(i=0;i<5;i++)head[i][31]='/'; head[35][3]=32;
  sprintf(f1,"ubad_%d.fit",k);
  fp=fopen(f1,"wb"); fwrite(head,36,80,fp); fwrite(a,n1,n2,fp); fclose(fp);
  printf("\n\t%s  produced!\n\n",f1);
}
