; Copyright (c) 2013 -  A.P. Hitchcock, Florian Meirer, Dieter Ingerle  All rights reserved

;+
;NAME:
;		AX_READ_TXRM
;
;LAST CHANGED: ----------------------------------- 	09-may-2013
;
; PURPOSE:
;	This function uses an external call to a Java routine to read
;  Xradia *.txrm images, stored in Microsoft Structured Storage (COM) format
; use SSViewer [http://www.mitec.cz/ssv.html]  to see the content of *.TXRM files
;
; CATEGORY:
;	Image  read in
;
; CALLING SEQUENCE:
;	Result = AX_READ_TXRM(, [FILE=FILE, NOF=NOF, SILENT=SILENT])
;
; INPUTS: none
;
; KEYWORDS:
;	FILE	filename (with path)
;	GROUP  defines the group_ID
;   NOF	    if set, do not specify *.txrm as the extension
;	NO_NORM  if set, do NOT normalize to the per-pixel time
;	SELECT  if set, allow user to select specfic image within a file
;   SILENT	if set, do not provide printed comments
;
; OUTPUTS:
;	image is returned as a aXis2000 IDL structure
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;	BSIF_COM	image parameters
;	STACK_PROCESS_COM	stack parameters
;
; SIDE EFFECTS: none
;
; RESTRICTIONS:
;
; PROCEDURE:
; The Java class txmreader creates a java list of java objects,
; one for each image stored in the txrm file. For SSRF there are 3 images stored in each *.tcrm file
; this reader only reads the first one
;
; EXAMPLE:
;
; MODIFICATION HISTORY:
; (30-Apr-13 aph) first version; AXIS standard header added
; (09-may-13 aph) extend to read the mesh and pixel-time maps
;-


FUNCTION ax_read_txrm, file=file, group=group, nof=nof, no_norm = no_norm, select=select, silent = silent
@axis_com
@stack_process_com
@bsif_com
on_error,2


;-------- set Path and environmental variable of a Windows machine to access the Java code in "CodePath\java\"
;print, 'CodePath is set to ', CodePath

JavaPath = CodePath +'java' + ax_sep()

; old_path=getenv('Path')
; tmp_path = old_path + JavaPath + 'idljavab.jar;' + CodePath + 'java;'
; tmp_path = tmp_path + JavaPath + 'TxmImage.jar;' + JavaPath + 'poi-3.9-20121203.jar'
; setenv, 'Path='+tmp_path

java_env=getenv('IDLJAVAB_CONFIG')
setenv,'IDLJAVAB_CONFIG='+JavaPath+'idljavabrc'+java_env

; ----- create the Java object --------
oJTxmImgFactory = OBJ_NEW("IDLJavaObject$TXMREADER_TXMIMAGEFACTORY", "txmreader.TxmImageFactory")


; --- get the filename if not supplied
IF NOT keyword_set(file) then begin
	fltr='*.txrm'
	if keyword_set(nof) then fltr='*'
	file = pickfile2(/READ, FILTER=fltr, /LPATH, DEFPATH=defpath)
ENDIF
s = ''
if file EQ '' THEN RETURN, s  ; bail-out if no filename
check = findfile(file)		 ; bail-out if non-existent file
if strlen(check(0)) EQ 0 then begin
	axis_log, 'Cannot find ' + file
	return, s
endif

; ---- generate short file name
t=ax_name(file)
fileshort = t(1)

; ---- read in *.txrm file
oJFullTXMData = oJTxmImgFactory -> getData(file)
;
; this object is an IDLJAVAOBJECT$JAVA_UTIL_ARRAYLIST
; for methods see: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
; now get the number of images inside

NoOfImages = oJFullTXMData -> size()
; get data for all images: NOTE indexing starts from 0
;
ii = 0
; --------- SELECT individual images in the file
if keyword_Set(select) then begin
	print, Fileshort, ' contains ', NoOfImages, ' images'
	ii=-1
	while ii EQ -1 do begin
		txrm_img_type = 'I'
		if keyword_set(group) then $
			txrm_img_type = get_text(prompt ='<I>mage, <P>ixel_time_map, <M>esh_signal_map', val=txrm_img_type, group=group) $
			else txrm_img_type = get_text(prompt ='<I>mage, <P>ixel_time_map, <M>esh_signal_map', val=txrm_img_type)

		txrm_img_type = STRUPCASE(txrm_img_type)
		if txrm_img_type EQ 'I' then ii=0
		if txrm_img_type EQ 'M' then ii=1
		if txrm_img_type EQ 'P' then ii=2
		if ii LT 0 or ii GT 2 then ii = -1
	endwhile
endif

; -------- use the following syntax to read image, ii
;    oJTxmImg = oJFullTXMData -> get(ii)
; this is now an IDLJavaObject$TXMREADER_TXMIMAGE

; use SSViewer [http://www.mitec.cz/ssv.html]  to see the content of TXRM files

; To access individual variables, use the following format
;pix_size = oJTxmImg -> getPixelSize()
;angle    = oJTxmImg -> getAngles()
;AxisNames =  oJTxmImg -> getAxisNames()
;Motor_Positions =  oJTxmImg -> getMotorPositions()
;Scan_Size =  oJTxmImg -> getScanSize()
	; and so on ...

; -------- get the pixel_time map if will normalize
if NOT keyword_set(no_norm) then begin
	    oJTxmImg = oJFullTXMData -> get(2)
	    time_norm = oJTxmImg -> getPixels()
endif

; ------ Now go get the real image
    oJTxmImg = oJFullTXMData -> get(ii)
    img = oJTxmImg -> getPixels()

; -----  extract other parameters
h = oJTxmImg -> getImageHeight()		; NB it is POSSIBLE that w is height, h is width due to transpose
w = oJTxmImg -> getImageWidth()
energy = oJTxmImg -> getEnergy()
dwell = 1000.*oJTxmImg -> getExpTimes()
xrf_dwell = dwell   ; store dwell in this variable in axis_com common block for future use

; ----- normalize if requested and the image being read is the actual image
if NOT keyword_set(no_norm) AND ii EQ 0 then begin
	time_norm = dwell*time_norm/mean(time_norm)
;	print, 'Mean of image = ', mean(img)
;	print, 'Mean of time = ', mean(time_norm)
	img = mean(time_norm)*img / time_norm
endif

; ------- put in the correct orientation (x --> y,  y -->x  = transpose)
    img = rotate(img, 4)

xstart =  oJTxmImg -> getXPosition()
ystart =  oJTxmImg -> getYPosition()

Xpix_size = oJTxmImg -> getPixelSizeX()
Ypix_size = oJTxmImg -> getPixelSizeY()

x=findgen(w) & x =xstart + x*Xpix_size		; ARE TXRM images restricted to square pixels ?
y=findgen(h) & y =ystart + y*Ypix_size

yl = 'TXRM image     y (um)'
xl = string(energy, dwell, format= $
	  '(" x"," um.      E =",f7.2," eV.       Dwell =",f6.2," ms.")')

s = {t:'2d', x:x, y:y, d:img, e: energy, xl:xl, yl:yl, dl: fileshort}

if not keyword_set(silent) then begin
	print, 'AX_TXRM_READ: read file from ', file
	axis_log, 'TXRM file: ' + fileshort
	text = string(w, h, energy, dwell, format= $
  '(i4," x",i4," pixels. E =",f7.2," eV. Dwell =",f6.2," ms.")')
	axis_log, text
endif


; Cleanup the object.
OBJ_DESTROY, oJTxmImgFactory
OBJ_DESTROY, oJFullTXMData
OBJ_DESTROY, oJTxmImg

; ------ restore Path and java environmental variables
; setenv, 'Path='+old_path
setenv, 'IDLJAVAB_CONFIG='+java_env

; ----- return the image
return, s

END