function sot_bitdecomp, data, lut, version=progver, name=prognam $
                        , verbose=verbose,    rlutdir = rlutdir

;+
; NAME:
;       SOT_BITDECOMP
;
; PURPOSE:
;       Decompress MDP bit compression. 
;       The FITS reformatter takes care of the decompression
;       in Level-0 data.
;
; CATEGORY:
;	Engineering
;
; SAMPLE CALLING SEQUENCE:
;	DATA_OUT = SOT_BITDECOMP(DATA_IN, N_LUT $
;                     [, /VERBOSE, RLUTDIR=RLUTDIR, NAME=NAME, VERSION=VERSION])
;
; INPUTS:
;	DATA_IN	  - Input data (any dimension, should be <12bit)
;	N_LUT	  - Bit compression Look-Up-Table number. 
;                   0: no compression
;                   1: 16U   -> 12U
;                   2: 14U   -> 12U
;                   3: 16S   -> 12U
;                   4: 14.5S -> 12U
;                   5: 13S   -> 12U
;                   6: 12U   -> 12U
;
; OUTPUTS:
;       DATA_OUT  - Output data, same size with DATA_IN
;
; OPTIONAL INPUT KEYWORD PARAMETERS: 
;	VERBOSE   - Set for a few more messages
;       RLUTDIR   - Directory for the reverseLUT files
;                   default = concat_dir('$SOT_CALIBRATION','bitcomp')
; 
; OUTPUT KEYWORD PARAMETERS: 
;	VERSION   - The current version number of the program
;       NAME      - The name of this routine
;
; MODIFICATION HISTORY:
;V1.0 20-Feb-2008. Created   YK
;
;-

prognam = 'SOT_BITCOMP.PRO'
progver = 'V1.0'

loud = 0b
if KEYWORD_SET(verbose) then loud = 1b

; Check LUT number input
IF (lut lt 0) or (lut ge 7) then begin
    MESSAGE, 'The look-up-table number is out of range!',/cont
    MESSAGE, 'Return the original data as is.',/cont
    RETURN, data
ENDIF

str = ['No compression','16U->12U','14U->12U','16S->12U' $
      ,'14.5S->12U','13S->12U','12U->12U']

IF loud THEN begin
    MESSAGE, /info,'Bit compression LUT: #'+string(lut,form='(I1)') $
      +' ('+str[lut]+')'
endif

; If LUT#0, return the original data
IF lut eq 0 then RETURN, data

; file path 
if n_elements(rlutdir) eq 0 then $
  rlutdir = concat_dir(getenv('SOT_CALIBRATION'),'bitcomp')

; read revereLUT
files_RLUT = ['RLUT0v0b020.lut','RLUT1v0b021.lut','RLUT2v0b022.lut' $
             ,'RLUT3v0b023.lut','RLUT4v0b024.lut','RLUT5v0b025.lut' $
             ,'RLUT6v0b026.lut']

; read file
file = concat_dir(rlutdir, files_RLUT[lut])
openr, unit, file, /get_lun, /swap_if_little
if (lut ge 3) and (lut le 5) then rlut = intarr(4096) $ ; Signed
else rlut = uintarr(4096); Unsigned
readu, unit, rlut
free_lun, unit

IF loud THEN begin
    MESSAGE, /info,'Reverse LUT file: '+file
endif

data_out = rlut(data<4095>0)

RETURN, data_out

END
