#include <stdio.h>
#include <string.h>
FILE *fp,*fp1;
short h[539];
int cols,rows;
unsigned char a[30000],f1[30],f2[30],head[36][80],c;
main(int ac, char **av)
{
  int i,j,k,it=0,ir=0,m;
  if(ac<2){ printf("\n\t**** change bmp(256) --> fit(8) ****\n");
            printf("\n\tUsage: bmp2fit in[.bmp] [1,2,3,4] [!]\n");
            printf("\n\t 1:  1-->1  no trun");
            printf("\n\t 2:  1-->2 means round X_AXIS turn 180 degree");
            printf("\n\t 3:  1-->3 means round Y_AXIS turn 180 degree");
            printf("\n\t 4:  1-->4 means round  (0,0) turn 180 degree");
            printf("\n\t !:  white_black reverse\n\n");
            exit(0); }
  strcpy(f1,av[1]);  if(ac>2)sscanf(av[2],"%d",&it);
  if(it!=2 && it!=3 && it!=4)it=1;
  if(ac>3)ir=1;
  for(i=0;i<strlen(f1);i++)if(f1[i]=='.')f1[i]=0;
  sprintf(f2,"%s.bmp",f1);
  fp=fopen(f2,"rb"); if(fp==0){printf("%s not found!\n",f2); exit(0); }
  fread(h,2,539,fp);
  if(h[14]!=8){ fclose(fp); printf("%s not 256 grey BMP!\n",f2); exit(0); }
  cols=h[9]; rows=h[11]; k=(cols+3)/4*4;
  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  =                    8 /");
  sprintf(head[ 2],"NAXIS   =                    2 /");
  sprintf(head[ 3],"NAXIS1  =                 %4d /",cols);
  sprintf(head[ 4],"NAXIS2  =                 %4d /",rows);
  sprintf(head[35],"END                             ");
  for(j=0;j<36;j++)head[j][32]=32;
  sprintf(f2,"%s.fit",f1);
  fp1=fopen(f2,"wb");  fwrite(head,36,80,fp1);
  m=rows*k+1078;
  for(j=0;j<rows;j++){
    m-=k; if(it%2==0)fseek(fp,m,0);  fread(a,1,k,fp);
    if(ir)for(i=0;i<cols;i++)a[i]=255-a[i];
    if(it>2)for(i=0;i<cols/2;i++){ c=a[i]; a[i]=a[cols-1-i]; a[cols-1-i]=c; }
    fwrite(a,1,cols,fp1);
  }
  fclose(fp); fclose(fp1);
  printf("%s ok!\n",f2);
}

