function xop = gtLoadReflections(xop_dir)
% GTLOADREFLECTIONS  Loads the list of reflections (hkl, intensity, 
%                    multiplicity, 2theta, d-spacing) from text files saved from Diamond 
%                    (.csv) or XOP (.dat).
%
%     xop = gtLoadReflections(xop_dir)
%     --------------------------------
%     Searches for .dat or/and .csv files in the local directory. If both
%     found, it picks the latest file.
%     If not found, givee the instructions to get them.
%     Diamond -> .csv parameters file
%         XOP -> .dat parameters file
%
%     INPUT: 
%       xop_dir = directory for the input file for xop
%
%     OUTPUT:
%       xop = structure with fields from the text file
%
%     
%     Version 002 08-03-2012 by PReischig
%       Adapted field names.
%       Bug fix to find latest crystallography file.   


if ~exist('xop_dir','var') || isempty(xop_dir)
    parameters=[];
    load('parameters.mat');
    xop_dir=parameters.xop.xop_dir;
    clear parameters
end

a2=dir(fullfile(xop_dir, '*.csv'));
for i=1:length(a2)
    o2{i}=a2(i).name;
end

a1=dir(fullfile(xop_dir, '*.dat'));
for i=1:length(a1)
    o1{i}=a1(i).name;
end

if isempty(a2) && isempty(a1)
    disp('If you have a .cif file for the current material, open it with Diamond')
    disp('  and let the program create the structure picture. Check the option ''Create packaing diagram''')
    disp('  and leave unchecked the option ''Connect atoms''.')
    disp('  When finished, show the powder pattern (top right corner) and select a wavelength')
    disp('  value in Angstrom, 2theta minimum and maximum in degrees.')
    disp('  Press enter when finished to calculate the reflection parameters.')
    disp('  Right-Click on the table header and save it as .csv file in the local directory. Close Diamond.')
    disp(' ')
    disp('If you don''t have a .cif file for the current material, open xop shell program.')
    disp('  On the top menu choose ''Optics'', ''Crystals'' and ''XPOWDER''.')
    disp('  In the tab ''Unit Cell'' insert the lattice parameters')
    disp('  and the atoms positions in the unit cell. Refer to the International Tables of Crystallography.')
    disp('  When done, click on tab ''Reflections'' and ''Set Parameters''.')
    disp('  Set the wavelength and the maximum value for 2-theta and click on ''Accept''.')
    disp('  Finally save the table in a .dat file in the local directory and use the function ''gtLoadReflections'' again.')
    disp(' ')
    disp('If you are really depressed, use this link to find the atoms positions:')
    disp('    http://it.iucr.org/Ab/ch7o1v0001/')
    isreflections=false;
elseif ~isempty(a2) && ~isempty(a1)
    isreflections=true;
    
    % Merged list of filenames to find latest file
    aa = [a1; a2]; 
    [~, maxind] = max([aa.datenum]);
    file = aa(maxind).name;
    
    if ~isempty(strfind(file,'.csv')) % .csv file
        delim=';';
        pattern='%d8 %f32 %f32 %f32 %f32 %d8 %d8 %d8 %d8';
        a=6;b=7;
        columns=9;
    elseif ~isempty(strfind(file,'.dat')) && ~strcmpi(file,'spacegroups.dat') % .dat file
        delim='space';
        pattern='%d8 %d8 %d8 %f32 %f32 %f32 %f32 %d8 %f32 %f32';
        a=1;b=2;
        columns=10;
    else
        error('The file name is wrong.');
    end
elseif isempty(a1) && ~isempty(a2) % .csv file
    delim=';';
    pattern='%d8 %f32 %f32 %f32 %f32 %d8 %d8 %d8 %d8';
    a=6;b=7;
    columns=9;
    isreflections=true;
    file=o2{1}; % file to be opened
elseif isempty(a2) && ~isempty(a1) % .dat file
    delim='space';
    pattern='%d8 %d8 %d8 %f32 %f32 %f32 %f32 %d8 %f32 %f32';
    a=1;b=2;
    columns=10;
    isreflections=true;
    file=o1{1}; % file to be opened
end % end if


file=fullfile(xop_dir,file);

if isreflections
    disp(['Opening file ' char(file) '...'])
    fid=fopen(file,'r');
    if fid==-1
        disp('Error opening file...')
        return
    end
    if strcmpi(delim,'space')
        testo = textscan(fid,'%s',columns);
        C = textscan(fid,pattern);
    else
        testo = textscan(fid,'%s',columns,'delimiter',delim);
        C = textscan(fid,pattern,'delimiter',delim);
    end
    fclose(fid);

    testo=char(testo{1});
    for i=1:columns
        title = testo(i,:);
        title = strtrim(title);
        title = lower(title);
        title = strrep(title,'.','');
        title = regexprep(title,'[^a-zA-Z]','');
        title = regexprep(title,'theta','twotheta');
        if length(title)==1
            title = regexprep(title,'m','mult');
            title = regexprep(title,'^f','formfactor');
        end
        title = strtrim(title);
        title = strrep(title,'dspc','dspacing');
        if ~strcmpi(title,'no')
            reflections.(title)=C{i};
        end
    end

    reflections.hkl=[reflections.h reflections.k reflections.l];
    reflections=rmfield(reflections,{'h','k','l'});

    xop = reflections;
    ind=strfind(file,filesep);
    xop.filename = file(ind(end)+1:end);
    xop.xop_dir  = xop_dir;
end

end % end of function

