; Copyright (c) 1998-2019 A.P. Hitchcock  All rights reserved
;+
;NAME:
;		READ_ASCII_IMG.PRO
;
;LAST CHANGED: ----------------------------------- 	26-Jun-19
;
; PURPOSE:
;	This function reads ascii (x,y) arrays into axis2000 format images
;
; CATEGORY:
;	data read. can execute outside of aXis2000
;
; CALLING SEQUENCE:
;	Result = READ_ASCII_IMG(file=file, filter=filter, normalize=normalize, $
;                 store=store, silent=silent, group = group)
;
; INPUTS:
;
; KEYWORDS:
;	FILE:  name of file
;	FILTER: extension (default is '*.txt')
;	GROUP:  grou_ID of parent if called from aXis2000
;	NORMALIZE: if set, modify intensities to standard ring current (value of normalize parameter
;	STORE: if set, write *.axb (aXis2000 format) binary file of image
;	SILENT: if set, do not print tracking comments
;
; OUTPUTS:
;	No explicit outputs.
;
; COMMON BLOCKS:
;	AXIS_COM	standard set of common blocks
;
; SIDE EFFECTS: none
;
; RESTRICTIONS: none
;
; PROCEDURE:
;adapted from crate_nc.pro supplied by Jurgen Thieme
;
;
; MODIFICATION HISTORY:
; (12-Jun-10 aph) first version
; (26-Jun-19 aph) modify to read *.csv files written by CLS ptycho processng
;-

function read_ascii_img, file=file, filter=filter, $
           normalize=normalize, store=store, silent=silent, group = group
@axis_com
on_error,2

if n_elements(file) eq 0 then begin  ;popup file dialog box
   if not keyword_set(filter) then filter=['*.txt','*.csv','*.asc']
	file=dialog_pickfile(/read, title='Select file with ascii image', $
	       dialog_parent=axis_ID, filter=filter, path = defpath, get_path=defpath)
;   file=PICKFILE2(/Read, FILTER=filter, /LPATH, DEFPATH=defpath)
endif

if strlen(file) GT 0 THEN BEGIN
	name_bits = ax_name(file)	; sort the name into its parts
	path = name_bits(0)
	fileshort = name_bits(1)
    ext = name_bits(2)
 endif else begin
	print, 'Filename ', file,' is not defined, or does not exist'
endelse

if not keyword_set(silent) then print, 'Reading ascii (x,y) array from ', file

; ====================================================
;Reading the file

check=query_ascii(file, info)

b = read_ascii(file, delimiter = ',')	; this assumes no header, so the image (x,y) is first entry in
image_data = b.(0)      ; the structure that read_ascii generates
; image_data = rotate(image_data,7) ; for txt data sent by Ebi Jun 2010
t = size(image_data)
n_rows = t(1)
n_cols = t(2)
if not keyword_set(silent) then print, 'image size (rows, cols) = ', n_rows, n_cols


; -----------------  generate an axis2000 format structure
xstart = 0 & xstep = 1
ystart = 0 & ystep = 1
x = findgen(n_cols)
y = findgen(n_rows)
energy = 100.
dwell  =1000.
xl = string(FORMAT='("x (pixels)     E = ",f8.3," eV     dwell = ",f6.2," ms")', $
      energy, dwell)
yl = ' '
s={t:'2d', d:image_data, x:x, y:y, e: energy, xl:xl, yl: yl, dl:fileshort}

if not keyword_set(silent) then axis_log, 'read ascii (x,y) image file ' + fileshort

if keyword_set(store) then begin
	t=axb_save(s)
endif
return, s
end