;+
; NAME:
;	ice_read
; PURPOSE:
;	Reads a compressed file written by ice_write into an integer array
; CATEGORY:
;	Bits and bytes
; CALLING SEQUENCE:
	FUNCTION ice_read, cFile, Orig, info=info
; INPUTS:
;	cFile		scalar; type: string
;				file name of compressed file
; OUTPUTS:
;	Result		scalar; type: integer
;				0: failure (an error message is displayed)
;				1: success
;	Orig		array; type: long integer
; OPTIONAL OUTPUT PARAMETERS:
;	info=info	scalar; type: string
;				trailer string extracted from end of file
; INCLUDE:
	@compile_opt.pro	; On error, return to caller
; CALLS:
;	ice_unpack
; SEE ALSO:
;	ice_write, ice_pack
; MODIFICATION HISTORY:
;	AUG-2000, Paul Hick (UCSD/CASS; pphick@ucsd.edu)
;	AUG-2000, Kevin Nguyen translated from Fortran to IDL
;-

nbits = 32L
nRecl = 128

;iVers = lonarr(2)
;cVers = '        '

status = 0B

on_ioerror, CLEANUP

openu, unit, cFile, /get_lun

nstore = lonarr(nRecl)
readu, unit, nstore

nOrig  = nstore[2]
nbit   = nstore[3]
kmax   = nStore[4]
kshift = nStore[5]
lenbit = nStore[6] 
sign   = nStore[7]
ninfo  = nStore[8]
perm   = nStore[8+1:8+kmax-kshift+1]


nPack = 1+(nbit-1)/nbits
Pack = lonarr( ceil( float(nPack)/nRecl ) *nRecl )
readu, unit, Pack
Pack = Pack[0:nPack-1]


info = bytarr(ninfo)
readu, unit, info
info = string(info)


ibit = ice_unpack(nbit, Pack, Orig, kmax=kmax, kshift=kshift, lenbit=lenbit, sign=sign, perm=perm)
iOrig = n_elements(Orig)

message, /info, 'max='+strcompress(kmax, /rem)+		$
		' ; shift='+strcompress(kshift, /rem)+	$
		' ; lenbit='+strcompress(lenbit, /rem)+	$
		' ; sign ='+strcompress(sign)
message, /info, 'perm ='+strjoin( strcompress(perm), /single )

status = ibit EQ nbit AND iOrig EQ nOrig

IF NOT status THEN BEGIN
	message, /info, 'Unpacked'+strcompress(ibit)+	$
		'bits into'+strcompress(iOrig)+' long integers'
	message, /info, 'Expected'+strcompress(nbit)+	$
		'bits into'+strcompress(nOrig)+' long integers'
ENDIF

CLEANUP:

on_ioerror, NULL
IF IsType(unit,/defined) THEN free_lun, unit

RETURN, status  &  END
