; Copyright (c) 1998-2016 A.P. Hitchcock  All rights reserved
;+
;NAME:
;	IMG_LOAD
;
;LAST CHANGED: -----------------------------------  28 Sep 2018 (aph)
;
;PURPOSE:
;	This function reads in an image from (*.tif, *.bmp, *.gif) format files
; and returns it as a '2d' or '3d' type axis structure
; Also reads in Elmitec exported tif files
;
;CATEGORY:
;	AXIS: image utility (runs stand alone)
;
;CALLING SEQUENCE:
;	Result = img_load(NOF=nof, error=err, values = values, silent=silent,  $
;   	TIF=tif, BMP=bmp, GIF=gif, elmitec=elmitec, lox=lox, _extra=e)
;
;CALLED FROM AXIS:
;	->Image->Other->{*.tif, *.bmp, *.gif, *.jpg, *.png}
;
;INPUTS:
;	All input parameters are passed as keywords.
;
;KEYWORDS:
;	NOF	- no filter
;   FILE - file name (no prompt unless that file is not found)
;	VALUES - if set, store as 2d-structure to allow axis display & mainpulation of data values
;			otherwise, store as 3d-structure; if VALUES GT 1 then use Red channel if 3-channel
;	TIF  - TIF read-in
;	GIF - GIF read-in
;   JPG - JPG read-in (JPEG)
;	BMP - BMP read-in
;	PNG - PNG read-in
;	ELMITEC - file is in UView2002 format
;	LOX   - file is in Lox format
;   SILENT  - do not print (axis_log) the details
;
;OUTPUTS: none
;
;COMMON BLOCKS:
;	@AXIS_COM	standard set of common blocks
;
;MODIFICATION HISTORY:
; (20-feb-98 aph) first written
; (14-jun-98 aph) axis_com
; (20-jan-99 aph) convert to data!
; (11-jun-99 aph) make tif-read get and set RBG tables; remove reversal
; (25-jun-99 aph) use ax_names to generate fileshort
; (31-jan-00 aph) attempt to get RBG working
; (15-apr-00 aph) AXIS standard documentation
; (16-apr-00 aph) store 3-channel images properly - revise {3d} structure
; (31-dec-01 aph) PNG format added - evetually converge to this one for > IDL 5.1 compatibility
; (17-apr-02 aph) adapt for Elmitec read-in
; (29-apr-02 aph) revise to adapt for axis_c setting of E, size
; (05-may-02 aph) adapt for Sphinx 16-bit tif format
; (14-may-02 aph) reverse PNG
; (16-jul-02 aph) fix up Elmitec PEEM read in - scale too large since used unsigned keyword
; (23-may-04 aph) add lox read-in
; (29-Oct-05 aph) add keyword SILENT
; (22-feb-06 aph) add tmp.E (energy) to output; fix  /values for tif, png
; (25-apr-06 aph) add jpg read-in; add provision to use 1-channel for values
; (07-jan-07 aph) flip Lox Tif images vertically
; (01-Aug-09 aph) use fileshort in axis_log; improve png reading
; (21-Feb-10 aph) improve png reading - flip vertically
; (20-Dec-16 aph) make silent keyword work for tif read-ins
; (28-Sep-18 aph) adapt to read unsigned interger tiffs using query_tif
;                 to identify unsigned interger NSRRC peem images
;-

Function img_load, NOF=nof, file=file, error=err, values = values, silent=silent,  $
    TIF=tif, BMP=bmp, GIF=gif, JPG=jpg, PNG=png, elmitec=elmitec, lox=lox, _extra=e

@axis_com
on_error,2

s = 0


if not keyword_set(file) then begin
	fltr='*.*'
	if keyword_set(tif) then fltr='*.tif'
	if keyword_set(bmp) then fltr = '*.bmp'
	if keyword_set(gif) then fltr = '*.gif'
	if keyword_set(jpg) then fltr = '*.jpg'
	if keyword_set(png) then fltr = '*.png'
	if keyword_set(lox) then fltr = '*.lox'
	if keyword_set(nof) then fltr='*'
	if keyword_set(filter) then fltr=filter
	file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath, title = 'Select image file')
	if strlen(file) EQ 0 THEN RETURN,s ; bail-out if no filename
endif
WIDGET_CONTROL, Bad_Id = BadID, /Hourglass

t = ax_name(file)
fileshort = t(1)+'.'+t(2)
if t(2) EQ 'bmp' then bmp = 1
if t(2) EQ 'tif' then tif = 1
if t(2) EQ 'gif' then gif = 1
if t(2) EQ 'jpg' then jpg = 1
if t(2) EQ 'png' then png = 1
if t(2) EQ 'lox' then lox = 1
if keyword_set(lox) then tif = 0
r = indgen(256)
g = indgen(256)
b = indgen(256)
energy = 5.
; ---------------------------------- GIF (NB IDL only reads '1-plane' type GIFs) -------
if keyword_set(gif) then begin
   	read_gif, file, tmp, R, G, B
;  	tmp = reverse(tmp,1)
;	ts = size(tmp) & nx = ts(1) & ny = ts(2)    ; DONEin PLOTBUF
;	main = 360*gr_scale
;	gif_scl = floor(main/max([nx,ny]))
; 	tmp = congrid(tmp, gif_scl*nx, gif_scl*ny)
  	if n_elements(R) NE 0 then begin
      	TVLCT, R, G, B
      	TVLCT, UserR, UserG, UserB, /get        ; sets default color table !
  	endif
endif

; ------------------------------------ BITMAP ------------------------
if keyword_set(bmp) then begin
	if query_bmp(file, bmp_info) EQ 0 then begin
	 	axis_log, fileshort + ' is not a BMP file or cannot be read by IDL'
	 	return, 0
	endif
	if bmp_info.has_palette EQ 1 then begin
		tmp = read_bmp(file, R, G, B)
;		if keyword_Set(value) then begin			; attempt to use IDL to convert to grayscale
;			write_jpeg, 't.jpg', tmp.d
;			read_jpeg,'t.jpg', tmp, /grayscale
;		endif
	endif else begin
		tmp = read_bmp(file)
	endelse
endif

; ------------------------------------ JPEG (greyscale only) ------------------------
if keyword_set(jpg) then begin
;	if query_jpeg(file, jpg_info) EQ 0 then begin
;	 	axis_log, fileshort + ' is not a JPG file or cannot be read by the IDL READ_JPG routine'
;	 	return, 0
;	endif
;	if jpg_info.has_palette EQ 1 then begin
;		read_jpeg,file, tmp
;	endif else begin
		read_jpeg,file, tmp, /grayscale
;	endelse
endif

; ----------------------------------- PNG -----------------------
if keyword_set(png) then begin
	if query_png(file, png_info) EQ 0 then begin
	 	axis_log, fileshort + ' is not a PNG file or cannot be read by IDL'
	 	return, 0
	endif
	if png_info.has_palette EQ 1 then begin
		tmp =read_png(file, R, G, B)
		TVLCT, R, G, B
	endif else begin
		tmp = read_png(file)
	endelse
endif

; --------------------------------- TIF format -----------------
if keyword_set(TIF) then begin
	test = query_tiff(file,tif_info)
	if test EQ 1 then begin
		if tif_info.channels EQ 3 then begin  ; 3 channel tif; separate images
			if not keyword_set(silent) then print, ' Reading first channel of a 3-channel tif'
;		  	if widget_info(/active) EQ 1 then begin
;		  		nsav=get_num(Prompt = 'select all(0), Red(1), Green(2) or Blue(3) component',val=0, group=axis_ID)
;		  	endif else nsav=get_num(Prompt = 'select all(0), Red(1), Green(2) or Blue(3) component',val=0)
			WIDGET_CONTROL, Bad_Id = BadID, /Hourglass
			tmp = read_tiff(file,R,G,B)
;		  	case strcompress(string(fix(nsav))) of
;		  		' 0': BEGIN  ; generate 1-plane image and R, G, B palettes
;
;		  		    END
;				' 1': tmp = reform(tmp(0,*,*))
;				' 2': tmp = reform(tmp(1,*,*))
;				' 3': tmp = reform(tmp(2,*,*))
;				ELSE: print, 'improper channel selection'
;		  	endcase
			if keyword_set(elmitec) then begin
				tmp = reform(tmp(0,*,*))
			endif
;				energy = get_num(prompt='Photon energy', val = energy, group = axis_ID)
		tmp = reverse(tmp,3)        ;files written by AXIS are up/down reversed
		endif else begin		; 1 channel tif
			if not keyword_set(silent) then print, ' Reading in 1-channel tif'
		  	tmp = read_tiff(file, R, G, B)
			q_info = query_tiff(file, info)
			if info.pixel_type EQ 12 then begin				; 28-Sep-18 (aph) adapt for NSRCC unsigned integer
		  		print, 'Reading in unsigned integer tiff file'
		  	endif else	if min(tmp) LT -16000 then tmp = tmp + 2^15
		  	if n_elements(R) GT 0 then begin
			   	TVLCT, R, G, B
			   	TVLCT, UserR, UserG, UserB, /get        ; sets default color table !
		   	endif
			tmp = reverse(tmp,2)        ;files written by AXIS are up/down reversed
		endelse
	endif
endif

; --------------------Lox special TIF format -----------------
if keyword_set(lox) then begin
	t = ax_name(file)
	file = t(0) + t(1) + '.tif'
;	if not keyword_set(silent) then print, 'Reading Lox image from ', file
	test = query_tiff(file,tif_info)
;	print, 'Query_tiff reports :'
;	help, tif_info, /structure
	if test EQ 1 then begin
			tmp = read_tiff(file,R,G,B)
			R = reform(tmp(0,*,*))
			G = reform(tmp(1,*,*))
			tmp = R + 256*G
			ts = size(tmp)
 		 	nx = ts(1) &  ny = ts(2)
 		 	x = findgen(nx)
 			y = findgen(ny)
			s = {t:'2d', x:x, y:y, E: energy, d:reverse(float(tmp),2), $
			      xl:'  ', yl:'  ', dl: fileshort}
;			if not keyword_set(silent) then $
;			     axis_log, 'Lox image read from: ', file, '     ', string(nx), ' x ', string(ny)
			return, s
	endif else begin
		print, 'Not special Lox format tif file'
		return, s
	endelse
endif

; ------------- output to standard AXIS data strutures ---------------
 ts = size(tmp)
 if ts(0) EQ 2 then begin
 	nx = ts(1) &  ny = ts(2)
 endif else begin	; assume 3-channel
 	nx = ts(2) &  ny = ts(3)
 endelse
 x = findgen(nx)
 y = findgen(ny)
 if keyword_set(values) then begin
 ;   first convert 3-channel to 1-channel & palette
 ; Note this causes image distortion !!
 	if ts(0) EQ 3 then begin
		if values EQ 1 then begin
 		tmp = color_quan(bytscl(tmp),1,R,G,B, cube=6)  ; colors = ax_top_color_index,
 		if not keyword_set(silent) then axis_log, 'RGB image converted to grayscale '
 		endif else begin
 			tmp2=fltarr(nx, ny)		; use only Red channel
 			tmp2=tmp(0,*,*)
 			tmp=reform(tmp2)
	 		if not keyword_set(silent) then axis_log, 'Red image used for values '
 		endelse
 	endif
;	TVLCT, R, G, B		; remove setting of RGB for values  (29-apr-02 aph)
;  	TVLCT, UserR, UserG, UserB, /get        ; set color table
	s = {t:'2d', x:x, y:y, E: energy, d:float(tmp), xl:'  ', yl:'  ', dl: fileshort}
endif else begin
	  s = {t:'3d', x:x, y:y, E: energy, d:tmp, r: R, g: G, b: B, xl:'  ', yl:'  ', dl: fileshort}
endelse
if not keyword_set(silent) then axis_log, 'image read from: ' + fileshort

return, s
end