#include <stdio.h>
#include <string.h>
FILE *fp,*fp0,*fp1;
char head[36][80],f1[80],f2[80];
unsigned short c[20000];
short h[99];
int n1,n2,n12;
main(int ac, char **av)
{
  int i,j,k,ip=0;
  if(ac<2){ printf("\n\t====  *.tif --> *.fits  ====");
            printf("\n\t                 jiangzhaoji,20111206\n");
            printf("\n\tUsage: tif2fit filename[.tif]");
            printf("\n\t       tif2fit d*");
            printf("\n\t       tif2fit *\n\n");
            exit(0);
  }
  for(j=0;j<36;j++)for(i=0;i<80;i++)head[j][i]=32;
  sprintf(head[ 0],"SIMPLE  =                    T ");
  sprintf(head[ 1],"BITPIX  =                   16 ");
  sprintf(head[ 2],"NAXIS   =                    2 ");
  sprintf(head[ 3],"NAXIS1  =                      ");
  sprintf(head[ 4],"NAXIS2  =                      ");
  sprintf(head[ 5],"FILENAME=                      ");
  sprintf(head[ 6],"BZERO   =              32768.0 ");
  sprintf(head[ 7],"BSCALE  =                  1.0 ");
  sprintf(head[ 8],"END                            ");
  strcpy(f1,av[1]);
  for(i=0;i<strlen(f1);i++)if(f1[i]=='.')f1[i]=0;
  sprintf(f2,"dir/b %s.tif >tif2fit.tmp",f1); system(f2);
  fp0=fopen("tif2fit.tmp","r");
l10:
  fgets(f2,80,fp0);
  if(feof(fp0)){ fclose(fp0); system("del tif2fit.tmp"); exit(0); }
  k=strlen(f2); f2[k-1]=0;
  printf("%3d: %s",++ip,f2);
  fp=fopen(f2,"rb"); if(fp==0){ printf(" not found!\n"); goto l10; }
  fread(h,2,99,fp);  sprintf(&f2[k-4],"fits");
  n1=h[15]; n2=h[21];  n12=n1*2;
  if(h[16]|h[22]){ printf(" not a raw tif_file!\n"); goto l98; }
  if(n1>20000){ printf(" I'm afraid X_axis is too bigger>20000\n"); goto l98; }
  sprintf(&head[3][21],"%9d ",n1);
  sprintf(&head[4][21],"%9d ",n2);
  sprintf(&head[5][10],"'%s '",f1); k=strlen(f1); head[5][13+k]=32;
  for(j=0;j<9;j++)head[j][31]=32;
  fp1=fopen(f2,"wb");
  fwrite(head,36,80,fp1);    k=n2*n12+198;
  for(j=0;j<n2;j++){
    k-=n12;            fseek(fp,k,0);
    fread(c,2,n1,fp);  for(i=0;i<n1;i++)c[i]-=32768;
    swap2(c,n12);      fwrite(c,2,n1,fp1);
  }
  fclose(fp1); printf("  ---->   %s  ok!\n",f2);
l98: fclose(fp);
  goto l10;
}

swap2(char *c, int k)
{
  char a; int i;
  for(i=0;i<k;i+=2){
    a=c[i]; c[i]=c[i+1]; c[i+1]=a;
  }
}
