
/**************************************************************************
 *                                                                        *
 * Copyright (c) 1996 Michael Richmond and Richard Treffers               *
 *                                                                        *
 *                    This software may be copied and distributed for     *
 *                    educational, research and not for profit services   *
 *                    provided that this copyright and statement are      *
 *                    included in all such copies.                        *
 *                                                                        *
 **************************************************************************/


	/* 
	   place data from an image into a two-dimensional array 
	   THE SPACE FOR WHICH IS ALLOCATED BY THIS ROUTINE.

	   user supplies:
	   	fh            file handle to some image file
	   	boxno         box number (-1 means "use the whole image")
	   	imrows        number of rows in image
	   	imcols        number of columns in image
	   returns in args
	    boxrows       number of rows in box (or whole image)
	    boxcols       number of columns in box (or whole image)

	   a pointer to the array is returned if all went well - 
	   or NULL if there was a problem.

	   11/18/91 - modified to allow boxno=-1 to mean "use the whole image"
	              MWR 
	*/


#include "pcvista.h"
#include "fits.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int16 **
boxdata(fh, boxno, imrows, imcols, boxrows, boxcols)
FITS_HANDLE fh;
int boxno;
int imcols, imrows, *boxrows, *boxcols;
{
	static int row, sr, sc, nr, nc;
	static unsigned int nbytes;
	int16 **p, **pp, *q;

	if (boxno != -1) {
		if (getbox(boxno, &sr, &sc, &nr, &nc))
			error(-1, "box not found");
		check_box(boxno, imrows, imcols);
		*boxcols = nc;
		*boxrows = nr;
	}
	else {
		sr = 0;
		sc = 0;
		nr = imrows;
		nc = imcols;
		*boxcols = imcols;
		*boxrows = imrows;
	}

	/* now make sure we can allocate enough space for the array */
	nbytes = nr*sizeof(int16 *);
	if ((p = (int16 **) malloc(nbytes)) == NULL) {
		fprintf(stderr, "can't allocate %d bytes for data array\n", nbytes);
		return(NULL);
	}
	pp = p;

	nbytes = nc*sizeof(int16); 
	for (row = sr; row < (sr + nr); row++) {
		if ((q = (int16 *) malloc(nbytes)) == NULL) {
			fprintf(stderr, "can't allocate %d bytes for data array\n", nbytes);
			return(NULL);
		}
		*pp++ = q;
		fits_get_data(fh, row, sc, q, nc);
	}
	return(p);

}
