;pro fits_recover_corrupted_file
;
;PURPOSE:
;	To open up a datacube that has not been properly written (this may be
;	a matter of the file not complying with the 2880 block size protocol)
;	and rewrite a datacube that can be opened by ds9 and the idl fits 
;	routines.
;
;INPUTS:
;	FitsFileName - The path to the file that contains the naxis1 x naxis2 x
;				   number of reads x number of windows data cube
;
;KEYWORDS:
;	FITSDIR - The directory where the file lives
;
;	
pro fits_recover_corrupted_file, FitsFileName, FitsDir = FitsDir, $
	Date = Date

Common FitsCube, FCB, unit

If not(keyword_set(Date)) then Date = '07Apr26/'
If not(keyword_set(FitsDir)) then FitsDir = '/nfs/slac/g/ki/ki09/lances/'+Date
If not(keyword_set(ScaleImage)) then ScaleImage = 0
cd, FitsDir

;Open the FitsFile to the first valid data byte after the header.
;The common file control block FCB holds the structure to the fits file
Position = fits_open_datacube(FitsFileName, Header, 'Read')

;The parameters intended for this datacube
naxis1 = fcb.axis(0)
naxis2 = fcb.axis(1)
naxis3 = fcb.axis(2)
naxis4 = fcb.axis(3)
bitpix = fcb.bitpix(0)
bzero = fcb.bzero(0)
bytes_per_word = (abs(bitpix)/8)
stop
;The Array to hold the data that will be written 
Datacube = UIntArr(naxis1, naxis2, naxis3, naxis4)

;Doesn't yet work since the program will crash when the end of the binary
;file is reached

for FrameNum = 0 , Naxis3 - 1 do begin
  for windownum = 0, Naxis4 - 1 do begin
    print, 'Frame Number' , FrameNum, 'Window Number', WindowNum

    ;Get the 2-dimensional Frame
    Data = (asic_fits_read_datacube(position, naxis1, naxis2))

    ;Append it to the datacube at the right position
    DataCube(*, *, FrameNum, WindowNum) = Data
 
    position = position + long(naxis1)*long(naxis2)*bytes_per_word


   endfor

endfor


close, unit

stop
end
