/* @(#)readima.c	19.1 (ESO-DMD) 02/25/03 14:01:45 */
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.COPYRIGHT    (c)  1988   European Southern Observatory
.IDENT        readima.c
.LANGUAGE     C
.AUTHOR       K. Banse   ESO/IPG
.KEYWORDS     Data Import, Bulk data frames, Images
.PURPOSE      Example program for reading in a binary Midas image
.VERSION      1.00  950713:   Creation 

 020502		last modif
 
---------------------------------------------------------------------*/

#include   <stdio.h>
#include <sys/types.h>




main(argc,argv)
int argc;
char *argv[];


{
int nobyt;
int  *datpntr, datinfo[6], nr, stat, fid;


char    fcb[512], pixbuf[512];
char    infile[64], outbuf[80];



if (argc > 1)				/* we're with command line args. */
   (void) strcpy(infile,argv[1]);
else
   {
   printf("Execute as: readima.exe `image_name'\n");
   exit(1);
   }

fid = open(infile,0);		/* read only */
if (fid < 0)
   {                     
   printf("Could not open file %s \n\r",infile);
   exit(1);
   }


/* now we read the File Control Block (512 bytes) of the image */

nobyt = 512;
stat = read(fid,fcb,nobyt);
if (stat != nobyt)
   {       
   printf("Could not read file control block of %s \n\r",infile);
   exit(1);
   }


/* at byte no. 52 we find the 6 basic (integer) values for the image */

datpntr = (int *) &fcb[52];
for (nr=0; nr<6; nr++) datinfo[nr] = *datpntr++;

/*
datinfo[0] = no. of axes of image
datinfo[1] = no. of pixels in 1. axis
datinfo[2] = no. of pixels in 2. axis
datinfo[3] = no. of pixels in 3. axis	 so only useful if dim < 4 !!
datinfo[4] = format of pixels:
	D_I1_FORMAT     1     byte             
	D_I2_FORMAT     2     short integer    
	D_UI2_FORMAT  102     unsigned short integer
	D_I4_FORMAT     4     integer        
	D_R4_FORMAT    10     real
	D_R8_FORMAT    18     double
datinfo[5] = byte no. of first pixel of image (counting begins at 0, like in C)
*/


printf("Naxis = %d, Npix(1,2,3) = %d, %d, %d\n",datinfo[0],datinfo[1],
       datinfo[2],datinfo[3]);
printf("data format = %d\nfirst pixel is at byte no. %d\n",
       datinfo[4],datinfo[5]);



/*  as an example we get the first 10 data values for real or byte pixels */


stat = (int)osdseek(fid,datinfo[5],FILE_START);	/* relative to start of file */
if (stat != -1) stat = read(fid,pixbuf,nobyt);


if (datinfo[4] == 10)				/* real data */
   {
   float  *fpix, fdata[10];

   printf("first 10 pixels are:\n");
   fpix = (float *) pixbuf;
   for (nr=0; nr<10; nr++)
      {
      fdata[nr] = *fpix++;
      printf("%f\n",fdata[nr]);
      }
   }
else if (datinfo[4] == 1)			/* byte data */
   {
   unsigned char  *cpix, cdata[10];

   printf("first 10 pixels are:\n");
   cpix = (unsigned char *) pixbuf;
   for (nr=0; nr<10; nr++)
      {
      cdata[nr] = *cpix++;
      printf("%d\n",cdata[nr]);
      }
   }
else 
   printf("only real + byte images handled in this example program...\n");

close(fid);      
}

