;pro Fits_Return_Pixel_Median
;
;PURPOSE: 
;	To return the median value of the pixels XStart to XStop, YStart to YStop 
;	for frames ZStart to ZStop.  This function is written solely for the purpose 
;	of avoiding crashes and memory allocation errors with 4096x4096xN datacubes
;	from the H4RG Devices.  
;
;INPUTS:
;	Position - The byte number indicating the end of the fits header 
;		   and the beginning of the data.  This should be returned
;		   by fits_open_datacube
;	XStart - The beginning column pixel number
;	XStop  - The end column pixel number
;	YStart - The beginning row pixel number
;	YStop  - The end row pixel number
;	ZStart - The beginning frame number
;	ZStop  - The end frame number
; 	Naxis1 - The Number of Columns in the full frame
;	Naxis2 - The Number of Rows in the full frame
;
;COMMON:
;	FCB - the file control block of the (already opened fits file)
;
;
;OUTPUTS:
;	CubeRegion :
;	      An (XStop - XStart, YStop - YStart, ZStop - ZStart)
;	      array holding the data
;
function Fits_Return_Pixel_Median, $
	      XStart, XStop, YStart, YStop, ZStart, ZStop,$
	      Naxis1, Naxis2

Common FitsCube, FCB, unit

;Form a 3-d Array based on the Input Coordinates
XSize = XStop - XStart + 1
YSize = YStop - YStart + 1
ZSize = ZStop - ZStart + 1
MedianData = UIntArr(XSize, YSize, ZSize)

;Loop through the datacube and obtain the pixel value for the given reads
for Row = YStart, YStop do begin
    print, 'Row Number' + Strtrim(Row, 2)
    for Col = XStart, XStop do begin

    MedianData(Col, Row) = median(Fits_Read_Datacube_Region(Col, Col, Row, Row, 0, 10, $
						  Naxis1, Naxis2))

   endfor
endfor

return, MedianData

end

