function Rd_PEEM, file, bits12=bits12, Energy=energy, $
         CCD_bgnd=CCD_bgnd, scale=scale, smth=smth, white = white, $
         region = region, NOFILTER=nof, _extra=e
;+
; FUNCTION RD_PEEM, file, bits12 = bits12, Energy = energy, $
;         CCD_bgnd = CCD_bgnd, scale = scale, smth = smth, white = white, $
;         region = region, NOFILTER=nof, _extra=e
;
; last changed ------------------------------------------------ 20-Apr-01 (aph)
;
; PURPOSE
;   This function reads in a PEEM-2 image file in either the as-recorded 12-bit
;  or the converted 16-bit unsigned tif.
;
; INPUT
;	FILE = file name to be readin (if absent pickfile dialog is launched)
;
; KEYWORDS
;	BITS12 = if set to 12 this turns on the 12-bit read routine
;	ENERGY = sets energy PEEM image was recorded at
;	CCD_bGND = average CCD background that is ssubtracted (as 16-bit scale)
;	SCALE = pixel size in microns
;	SMTH = if set, applies a 3-point median smooth
;	WHITE = if set, divides the image by the contents of the 'whitexx.tif'
;           (gives response of CCD to uniform illumination)
;	REGION = a 4-number vector [x_start, x_stop, y_start, y_stop]
;			defining the region of the image to be selected
;			(if scale set, in real space units. Otherwise, in pixels)
;	NOFILTER = if set, then pickfile dialog does not have filter set to '*.tif'
;
; COMMON
;	AXIS_COM general common blocks for AXIS
;
; WARNINGS
;	1024x1024 images from CCD camera can be slow loading with older computers
;
; ------- REVISION HISTORY --------------
; (14-may-99 aph) first version
; (15-may-99 aph) save scale (pix_siz), region (cur, cll) values in common
; (08-jun-99 aph) add group to get_num call
; (25-jun-99 aph) report short gile name only
; (17-jul-99 aph) CCD_bgnd used
; (01-nov-99 ads) add nobits keyword & option for reading 12bit PEEM2 images
; (26-dec-99 aph) incorporated in AXIS 1.8c
; (23-oct-00 aph) 12-bit read in from arbitrary size - use Query_Tiff to obtain dimensions
;                  dump first 5 columns
; (20-apr-01 aph) getting 1024x1024 12-bit files to read
;-

; on_error,2
@axis_com

if n_elements(file) eq 0 then begin  ;popup file dialog box
   fltr='*.tif'
   if keyword_set(nof) then fltr='*'
   file=PICKFILE2(/Read, FILTER=fltr, /LPATH, DEFPATH=defpath)
endif
s = 0
IF strlen(file) NE 0 THEN BEGIN

; --------------------------------- read in image as 12-bit or 16-bit TIFF
WIDGET_CONTROL, /Hourglass
name_bits = ax_name(file)
fileshort = name_bits(1)
IF keyword_set(bits12) then begin
;
; routine to read illegal 12-bit tif files from ALS PEEM2 system
; structure is 2 x 12 bit pixels split over 3x 8bit bytes
; files recorded on a PC which is 'little endian', byte order needs
; to be swapped if using a 'big endian' system - e.g. Mac or Sun.
;
; seem to be missing the first byte of each line - therefore skip first two pixels.
; (Added ADS 12/11/99)
;
	test = query_tiff(file,tif_info)
    img_x = tif_info.dimensions(0)
    img_y = tif_info.dimensions(1)
    print, file, ': 12-bit tif image: ', img_x, ' x ', img_y
; -------
; there are 2 cases for mapping 2 *12-bits into 3 * 8-bits
	test = float(img_x/2.)-floor(img_x/2)
; CASE 1:  img_x  is EVEN		e.g. 2 12-bits takes 3 8-bits
    IF test EQ 0 then rawline = 3*floor(img_x/2) else $
; CASE 2:  img_x  is ODD		e.g. 3 12-bits takes 5 8-bits
    rawline = 3*floor(img_x/2) + 2
	print, ' each line will have ', rawline, ' bytes'
	rawimg=bytarr(rawline,img_y)
	on_ioerror, read_error
    openr, filelun, file, /GET_LUN , /SWAP_IF_BIG_ENDIAN
;	header = bytarr(3*floor(img_x/2))
;	readu, filelun, header  ; build in offset for header info
    readu, filelun, rawimg
    close, filelun, /all
    a = uintarr(img_x,img_y)
    aone = uintarr(img_x,img_y)
; read image by extracting 3 12-bit pixels from every pair of 16-bit pixels  (* = each line)
    FOR i=2,rawline-3,3 DO BEGIN
; 		if i LT 8 then print, '3 bytes: ', uint(rawimg(i,0)), uint(rawimg(i+1,0)), uint(rawimg(i+2,0))
        ki=(i*2)/3
        aone(ki,*)=ishft(uint(rawimg(i,*)),4) + ishft(uint(rawimg(i+1,*) AND 240),-4)
        ki=ki+1
        aone(ki,*)=ishft(uint(rawimg(i+1,*) AND 15),8) + uint(rawimg(i+2,*))
;        if i LT 8 then print, aone(ki-1,0), aone(ki,1)
    ENDFOR
;  --   amplify signal to occupy top 12bits, packing bottom 4 bits with zero
    aone = ishft(aone,4)
;  --   invert image (so's right way up.)
	a = reverse(aone,2)
;     FOR i=0,img_y-1 DO  a(*,i) = aone(*,(img_y-1-i))

ENDIF ELSE BEGIN
; ------ read in 16-bit tifs
	a = read_tiff(file, /unsigned)
;	reverse y-order
	a = reverse(a,2)
	t = size(a)
	print, file, ': 16-bit ALS PEEM image: ', t(1), ' x ', t(2)
ENDELSE
; ------------- dump first 2 columns to remove 21-bit header error - BOTH 12-bit & 16-bit
 offset = 4
 t = size(a) &	b=a(1 + offset:(t(1)-1),1:(t(2)-1-offset)) & a = b
 t = size(a) & print,' converted to ', t(1), ' x ', t(2)
;
; -- keyword set WHITE option
;
	IF keyword_set(white) THEN BEGIN
		q = findfile(string(white), count = cnt)
		IF cnt EQ 0 THEN BEGIN
			print, 'Select file for CCD correction'
			WIDGET_CONTROL, Uprompt, Bad_ID = badID, SET_VALUE='Select file for CCD correction'
		   	white=PICKFILE2(/Read, FILTER='*.tif', /LPATH, DEFPATH=defpath)
		ENDIF
	WIDGET_CONTROL, /Hourglass
	IF white NE '' THEN b = read_tiff(white, /unsigned) ELSE b = 1.
	ENDIF ELSE b = 1.
;
; -- keyword set CCD-bgnd option
;
; ------- have data; now process for CCD_Bgnd and white (CCD pattern noise) correction
	IF keyword_set(CCD_bgnd) THEN a = a - CCD_Bgnd
;
	a = float(a)/float(b)
	ntests=1	; ------------- replace NaN and inf values with adjacent
	test = a(where(finite(a) EQ 1)) & check = n_elements(a) - n_elements(test)
	WHILE check NE 0 AND ntests LT 5 DO BEGIN
		print, 'Ratio generated ', check, ' math errors. Attempt to correct ', ntests
		cor = where(finite(a) EQ 0) +1      ;take next point
		cor(where(cor EQ n_elements(a))) = n_elements(a) - 2
		a(where(finite(a) EQ 0)) = a(cor)
		test = a(where(finite(a) EQ 1)) & check = n_elements(a) - n_elements(test)
		ntests = ntests + 1
	ENDWHILE
	test = a(where(finite(a) EQ 1)) & check = n_elements(a) - n_elements(test)
	IF check GT 0 THEN BEGIN
		print, 'Residual math errors - replace with average'
		a(where(finite(a) EQ 0)) = mean(a(where(finite(a) EQ 1)))
	ENDIF
;
; -- keyword set SMTH option
;
	IF keyword_set(smth) THEN a = median(a,3)   ; median filter to remove hot spots
;
	t = size(a)
;
; -- keyword set ENERGY - if not specified in call then prompt for it
;
	IF not keyword_set(energy) THEN BEGIN
		IF widget_info(/active) EQ 1 THEN BEGIN
			Energy = get_num(Prompt = 'Energy', Val = Energy, group = axis_id)
		ENDIF ELSE Energy = get_num(Prompt = 'Energy', Val = Energy)
	ENDIF
;
; -- keyword set SCALE option - set (x,y) scale if requested ----------
;
	IF keyword_set(scale) THEN pix_siz = scale
	IF not keyword_set(scale) THEN BEGIN
		IF widget_info(/active) EQ 1 THEN BEGIN
			pix_siz = get_num(Prompt = 'um / pixel', Val = pix_siz, group = axis_id)
		ENDIF ELSE pix_siz = get_num(Prompt = 'um / pixel', Val = pix_siz)
	ENDIF
	xl = 'um     E = ' + strcompress(string(Energy))+' eV'
	x = pix_siz*indgen(t(1))  & y = pix_siz*indgen(t(2))
;
; -- keyword set REGION option - extracts subset of image ---------------
;
	IF keyword_set(region) THEN BEGIN
		t = size(region)
		IF t(1) NE 4 THEN BEGIN  ; ask user for xmin, xmax, ymin, ymax
			xlow = min(x, max=xhi) & ylow = min(y, max=yhi)
			IF widget_info(/active) EQ 1 THEN BEGIN
				xlow = get_num(Prompt = 'X_min',Val=xlow, group = axis_id)
				xhi  = get_num(Prompt = 'X_max',Val=xhi, group = axis_id)
				ylow = get_num(Prompt = 'Y_min',Val=ylow, group = axis_id)
				yhi  = get_num(Prompt = 'Y_max',Val=yhi, group = axis_id)
			ENDIF ELSE BEGIN
				xlow = get_num(Prompt = 'X_min',Val=xlow)
				xhi  = get_num(Prompt = 'X_max',Val=xhi)
				ylow = get_num(Prompt = 'Y_min',Val=ylow)
				yhi  = get_num(Prompt = 'Y_max',Val=yhi)
			ENDELSE
		ENDIF ELSE BEGIN
			xlow = region(0)  &  xhi = region(1)
			ylow = region(2)  &  yhi = region(3)
		ENDELSE
; -------------- save region for future use -------------
		cll(0) = xlow & cll(1) = ylow
		cur(0) = xhi  & cur(1) = yhi
		xind=where(x GE xlow AND x LE xhi)
		yind=where(y GE ylow AND y LE yhi)
		d = a(xind(0):xind(n_elements(xind)-1), yind(0):yind(n_elements(yind)-1))
		s = {t:'2d', x: x(xind), y: y(yind), d: d, xl:xl, yl: 'als-PEEM   ', dl: fileshort}
	ENDIF ELSE BEGIN
		s = {t:'2d', x: x, y: y, d: a, e: energy, xl:xl, yl: 'als-PEEM   ', dl: fileshort}
	ENDELSE
	print, 'Read TIF file ', file
ENDIF

return, s

read_error:
print, 'RD_PEEM: read error'
return, 0
END

