function [jasondata]=jasonimport(DataType,path,varargin)
%   [jasondata]=jasonimport()
%   Imports NMR data in JASON format
%
%   DataType specifies wheter it is raw or processed data.
%           DataType == 0 raw data
%                    == 1 processed, 
%                    == 2 raw data for an array
%                    == 3 processed data for an array
%   Path specifies wheter it is raw or processed data.
%           DataType == 0 single experiment
%                    == string raw data for an array, 
%
%   Checking optional inputs for jasonimport:
%          varargin{1} = expnr     = Checking the number of experiments 
%          varargin{2} = filename  = path of jjh5 file
%          varargin{3} = procpar   = general data inside the jjh5 file 
%
%   Point to the fid directory that contains the raw data.
%   The imported data will be returned in the structure variandata
%   containing the following members:
%               at: acquisition time (in seconds)
%               DELTA: diffusion time
%               delta: diffusion encoding time
%               dosyconstant: gamma.^2*delta^2*DELTAprime
%               FID: Free induction decays
%               filename: original file name and path
%               gamma: magnetogyric ratio of the nucleus
%               Gzlvl: gradient strengths
%               lp: first-order phase
%               ngrad: number of gradient levels
%               np: number of complex data points per gradient level
%               sfrq: spectrometer frequency (im MHz)
%               rp: zero-order phase
%               sp: start of spectrum (in ppm)
%               sp(n e.g 2,3,4): start of spectrum in n(nd) indirect dimension (in ppm)
%               sw: spectral width (in ppm)
%
%   See also: GNAT, dosy_mn, score_mn, decra_mn, mcr_mn, varianimport,
%             brukerimport, jeolimport, peakpick_mn, dosyplot_mn,
%             dosyresidual, dosyplot_gui, scoreplot_mn, decraplot_mn,
%             mcrplot_mn
%
%   This is a part of the GNAT
%   Copyright 2023  <Mathias Nilsson>

%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.

%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.

%   You should have received a copy of the GNU General Public License along
%   with this program; if not, write to the Free Software Foundation, Inc.,
%   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

%   Dr. Mathias Nilsson
%   School of Chemistry, University of Manchester,
%   Oxford Road, Manchester M13 9PL, UK
%   Telephone: +44 (0) 161 306 4465
%   Fax: +44 (0)161 275 4598
%   mathias.nilsson@manchester.ac.uk

%% Initialisation
% Extracting the information present in the jjh5 file
if nargin>3 % for arrays saved in one single file (same vendor)
    expnr = varargin{1};
    jasondata.filename = path;
    procpar = h5info(jasondata.filename); 
    clear varargin
elseif ~isnumeric(path) % for arrays saved in multiple file (same vendor)
    jasondata.filename=path;
    procpar = h5info(jasondata.filename);      
else % for single spectrum 
    [file, path]=uigetfile('*.jjh5','Choose the JASON header file (*.jjh5)');
    jasondata.filename=[path file];
    jasondata.filepath=path;
    if isnumeric(jasondata.filepath)
        return
    end
    procpar = h5info(jasondata.filename);    
end

% Filtering information useful for GNAT about the acquisition
% ('/JasonDocument/NMR/NMRData/n_experiment')
% if exist('expnr','var') % for arrays in one file
%     procpar = procpar.Groups.Groups(2).Groups.Groups(expnr);
% else % for a single spectrum
%     procpar = procpar.Groups.Groups(2).Groups.Groups;   %'/JasonDocument/NMR/NMRData/0'%
%     expnr=1;   
% end

% Filtering information useful for GNAT about the acquisition
% ('/JasonDocument/NMR/NMRData/n_experiment') 
% rotine for a single spectrum
try
    expnr = 1;
    procpar = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1)]);
catch ME
    % Get last segment of the error identifier.
    idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
    if strcmp(idSegLast,'unableToFind')
        logtext=fprintf('No dimension were found in experiment %d \n',expnr-1);
        jasondata.logfile{end +1}=logtext;
    end
end

% Set some default parameters
jasondata.procpar = procpar;
jasondata.rp=0;
jasondata.lp=0;
jasondata.sp=0;
jasondata.sp1=[];
jasondata.ni=[];
jasondata.logfile={'jasonimport'};

% Check the type of data saved inside JASON file selected (At the moment there is no differentiation between thse methods)
if DataType==0 %raw data
    % Checking if inside JASON the imaginary component is saved 
    temp = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints']);
    sz = size(temp.Datasets,1);
    % Extracting the real part of the spectra
    real = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints/0']);
    if sz == 2 % real and imaginary data available
        % Extracting the imaginary part of the spectra
        img = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints/1']); 
%    else % just the real data
        % To obtaing the imaginary part, we're going to use the Hilbert transformation 
        % see also [2] Marple, S. L. “Computing the Discrete-Time Analytic Signal via FFT.” 
        % IEEE® Transactions on Signal Processing. Vol. 47, 1999, pp. 2600–2603.
%        img = imag(hilbert(real));
    end   
    
elseif DataType==1 %processed data    
    % Checking if inside JASON the imaginary component is saved 
    temp = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints']);
    sz = size(temp.Datasets,1);
    % Extracting the real part of the spectra
    real = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints/0']);
    if sz == 2 % real and imaginary data available
        % Extracting the imaginary part of the spectra
        img = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints/1']); 
    else % just the real data
        % To obtaing the imaginary part, we're going to use the Hilbert transformation 
        % see also [2] Marple, S. L. “Computing the Discrete-Time Analytic Signal via FFT.” 
        % IEEE® Transactions on Signal Processing. Vol. 47, 1999, pp. 2600–2603.
        img = imag(hilbert(real));
    end   

elseif DataType==2 %raw data for a large array
    % Checking if inside JASON the imaginary component is saved 
    temp = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints']);
    sz = size(temp.Datasets,1);
    % Extracting the real part of the spectra
    real = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints/0']);
    if sz == 2 % real and imaginary data available
        % Extracting the imaginary part of the spectra
        img = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/DataPoints/1']); 
    else % just the real data
        % To obtaing the imaginary part, we're going to use the Hilbert transformation 
        % see also [2] Marple, S. L. “Computing the Discrete-Time Analytic Signal via FFT.” 
        % IEEE® Transactions on Signal Processing. Vol. 47, 1999, pp. 2600–2603.
        img = imag(hilbert(real));
    end   

elseif DataType==3 %processed data for a large array
    % Checking if inside JASON the imaginary component is saved 
    temp = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints']);
    sz = size(temp.Datasets,1);
    % Extracting the real part of the spectra
    real = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints/0']);
    if sz == 2 % real and imaginary data available
        % Extracting the imaginary part of the spectra
        img = h5read(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/DataPoints/1']); 
    else % just the real data
        % To obtaing the imaginary part, we're going to use the Hilbert transformation 
        % see also [2] Marple, S. L. “Computing the Discrete-Time Analytic Signal via FFT.” 
        % IEEE® Transactions on Signal Processing. Vol. 47, 1999, pp. 2600–2603.
        img = imag(hilbert(real));
    end 
else
    error('Unknown DataType')
end

% Extracting from .jjh5 the DOSY folder if it exists.
if DataType==0 %raw data
    try
        p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo/DosyParameters']);
        % The DosyParameters folder exists
        DosyParameters = p.Attributes;
    catch ME
        % Get last segment of the error identifier.
        idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
        if strcmp(idSegLast,'unableToFind')
            logtext=fprintf('No DOSY parameters were found in experiment %d \n',expnr-1);
            jasondata.logfile{end +1}=logtext;
        end
    end
elseif DataType==1 %processed data   
    try
        p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/SpecInfo/DosyParameters']);
        % The DosyParameters folder exists
        DosyParameters = p.Attributes;
    catch ME
        % Get last segment of the error identifier.
        idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
        if strcmp(idSegLast,'unableToFind')
            logtext=fprintf('No DOSY parameters were found in experiment %d \n',expnr-1);
            jasondata.logfile{end +1}=logtext;
        end
    end
end

% Extracting lists
try
    p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo/lists']);
    % Extracting list elements
    for i = 1:size(p.Attributes,1)
        lists{1,i} = p.Attributes(i).Name;
        lists{2,i} = p.Attributes(i).Value;
    end 
catch ME
    % Get last segment of the error identifier.
    idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
    if strcmp(idSegLast,'unableToFind')
        logtext=fprintf('No lists were found in experiment %d \n',expnr-1);
        jasondata.logfile{end +1}=logtext;
    end
end

% Checking the data dimension
if isfield(procpar.Attributes,'Name')
    p = find(contains({procpar.Attributes.Name}, 'nDim'));
    DataDim = procpar.Attributes(p).Value;
else
    errordlg( {'Can not find the dimension information'},'File error')
    uiwait;
    jasondata.nDim_error=1;
    return
end

%% Read in acquisition parameters
if DataType==0 %raw data
    p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo']);
    SpecInfo = p.Attributes;
elseif DataType==1 %processed data   
    p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/SpecInfo']);
    SpecInfo = p.Attributes;
end

if DataDim>=1 % (I am only focusing on 1D parameters at the moment)
    r = find(matches({SpecInfo.Name}, {'PulseProgram','SW','SpectrometerFrequencies','appliedPh0'}));
    jasondata.pulprog = SpecInfo(r(1)).Value;
    logtext=['The pulse programme is: ' jasondata.pulprog];
    disp(logtext)
    jasondata.logfile{end +1}=logtext;
    sw = SpecInfo(r(2)).Value;
    jasondata.sfrq = SpecInfo(r(3)).Value(1); %(in MHz)   
    jasondata.sw=sw(1)/jasondata.sfrq; %(in ppm)
    jasondata.rp=SpecInfo(r(4)).Value(1); 
    %---------------------------------------------------------------------%
    if DataType == 0 || DataType == 2
        p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData']);
        RawData = p.Attributes; r = find(matches({RawData.Name}, {'Length'}));
        jasondata.np = double(RawData(r).Value(1));
    elseif DataType == 1 || DataType == 3
        r = find(matches({procpar.Attributes.Name}, 'Length'));
        jasondata.np=double(procpar.Attributes(r).Value(1));
    end
    r = find(matches({SpecInfo.Name}, {'SpectrumRef'}));
    jasondata.at=jasondata.np/(sw(1));
    jasondata.x_offset=(SpecInfo(r).Value(1))/jasondata.sfrq; % (in ppm)    
    jasondata.sp=jasondata.x_offset-jasondata.sw/2;
end

%% Read Processing parameters
% Checking the value used in the trasition_ratio (clipping) for data
% acquired in a JEOL spectrometer
% Administrator_Manual_3.2.2_Characteristics_of_Digital_Filter
try
    p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo/OriginalParameters/parameters']); 
    % The DosyParameters folder exists
    OriginalParameters = p.Attributes; r = find(matches({OriginalParameters.Name}, {'TRANSITION_RATIO'}));
    jasondata.processing.tr = OriginalParameters(r).Value(1);
catch ME
    % Get last segment of the error identifier.
    idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
    if strcmp(idSegLast,'unableToFind')
        logtext=fprintf('No clipping was used experiment %d \n',expnr-1);
        jasondata.logfile{end +1}=logtext;
    end
    jasondata.processing.tr = 0;
end


%% Sort out parameters in GNAT format
if DataDim==1
    logtext='1D data';
    jasondata.arraydim=1;
    jasondata.ngrad=1;
    jasondata.Gzlvl='non existing';
    jasondata.DELTA='non existing';
    jasondata.delta='non existing';
    jasondata.dosyconstant='non existing';   
elseif DataDim==2
    logtext='2D data';
    jasondata.arraydim=2;
    jasondata.ngrad=1;
    jasondata.Gzlvl='non existing';
    jasondata.DELTA='non existing';
    jasondata.delta='non existing';
    jasondata.dosyconstant='non existing';  
%     sw1 = specinfo(p(2)).Value(2); %(in Hz)
%     jasondata.sw1=sw1/jasondata.sfrq; %(in ppm)
elseif DataDim==3 && DataType~=3 %higher order experiments, for PARAFAC
    logtext='3D data';
%     sw1 = specinfo(p(2)).Value(3); %(in Hz)
%     jasondata.sw1=sw1/jasondata.sfrq; %(in ppm)
elseif DataDim==4
    logtext='4D data';
%     sw1 = specinfo(p(2)).Value(4); %(in Hz)
%     jasondata.sw1=sw1/jasondata.sfrq; %(in ppm)
else
    error('Unknown data dimension')
end
disp(logtext)
jasondata.logfile{end +1}=logtext;

% Extraction of the nucleis present in the Specinfo variable
p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo/Nucleides']); 
nucleides = p.Groups;

i=0;
while i<=8 
    i=i+1;
    temp=nucleides(i).Attributes(2).Value;
    if isempty(temp) == 1
        break
    else
        nucl(i)=temp;
    end
end

switch char(nucl(1))
    case 'H'
        jasondata.gamma=267524618.573;
    case 'C'
        jasondata.gamma=67283000;
    case 'N' % create condition for 14N
        jasondata.gamma=19338000;
%     case 'N' % create condition for 15N
%         jasondata.gamma=-27126000;
    case 'O'
        jasondata.gamma=-36281000;
    case 'F'
        jasondata.gamma=251815000;
    otherwise
        logtext='unknown nucleus - defaulting to proton';
        disp(logtext)
        jasondata.logfile{end +1}=logtext;
        jasondata.gamma=267524618.573;
end

%% Allocating experimental parameters

% This is a temporary solution for variables not available in
% DosyParameters. (GRAD_SHAPE in JEOL and GPNAM in Bruker)
p = find(matches({SpecInfo.Name}, {'OrigFileFormat.str'}));
FileFormat = SpecInfo(p).Value;
% if isequal(FileFormat,'JCAMP-DX') || isequal(FileFormat,'JEOL Delta')
%     parameter = procpar.Groups(6).Groups(2).Groups(3).Groups(4).Attributes; 
% elseif isequal(FileFormat,'TopSpin')
%     parameter = procpar.Groups(6).Groups(2).Groups(2).Groups(2).Attributes;
% end
jasondata.FileFormat = FileFormat;

% For this part, the variables are extracted from DosyParameters folder
if exist([jasondata.filename 'GNATimport'],'file') == 2
    logtext='Using GNATimport file to determine import parameters';
    disp(logtext)
    jasondata.logfile{end +1}=logtext;
    fileid=fopen([jasondata.filename  'GNATimport'],'rt'); %#ok<NASGU>
else
    %Using default import options
    logtext=['cannot open file: ' [jasondata.filename  'GNATimport']];
    disp(logtext)
    jasondata.logfile{end +1}=logtext;
    logtext='Using default import (normal for 1D, DOSY and Relaxation data';
    disp(logtext)
    jasondata.logfile{end +1}=logtext;
    if DataDim==1
        % Do nothing
    elseif DataDim == 2 %likely a difusion or relaxation experiment
        logtext='2D experiment: trying diffusion and relaxation type';
        disp(logtext)
        jasondata.logfile{end +1}=logtext;
        % Default result for GNAT
        jasondata.Gzlvl='non existing';
        jasondata.DELTA='non existing';
        jasondata.delta='non existing';
        jasondata.dosyconstant='non existing';
        jasondata.ngrad=1;
        % Reading Diffusion experiment
        jasondata.arraydim=size(lists{2, 1},1);
        p = find(matches({SpecInfo.Name},'SpectrumTypeExt'));
        if SpecInfo(p).Value(2) == 6        
            logtext='Diffusion experiment';
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
            jasondata.Gzlvl=(cell2mat(lists(2,1))*0.001)'; % conversion from G/cm to T/m
            jasondata.ngrad=length(jasondata.Gzlvl);

            % set the default as 'SINE'
            jasondata.gpnam='SINE';
            % temporary solution for diffusion
            if sum(matches({OriginalParameters.Name}, 'GPNAM')) == 1 % Bruker 
                p = find(matches({OriginalParameters.Name}, 'GPNAM'));
                jasondata.gpnam=cell2str(OriginalParameters(p).Value(2));
            elseif sum(matches({OriginalParameters.Name}, 'GRAD_SHAPE')) == 1 % JEOL
                p = find(matches({OriginalParameters.Name}, 'GRAD_SHAPE'));
                jasondata.gpnam=OriginalParameters(p).Value;
            else
                logtext='DOSY gradient shape missing. I will set it to default (SINE)';
                disp(logtext)
                jasondata.logfile{end +1}=logtext;
            end
            logtext=(['DOSY gradient shape is: ' jasondata.gpnam]);
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
            logtext='Warning! - GNAT assumes that the difflist is corrected for the shape of the gradient';
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
            
            % Extracting variables to the Stejskal-Tanner Equation
            p = find(matches({DosyParameters.Name}, {'InterGradientDelay','DiffusionTime_nominal','GradientPulseDuration','OneShotAlpha'}));
            jasondata.tau=DosyParameters(p(1)).Value(1);
            jasondata.DELTA=DosyParameters(p(2)).Value(2);
            jasondata.delta=DosyParameters(p(3)).Value(1);
            jasondata.alpha=DosyParameters(p(4)).Value(1);

            % Set the ST equation values according to the gradient shape
            logtext=('Gradient shape will be used for calculation of the attenuation function');
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
            if strcmpi(jasondata.gpnam,"SINE") || strcmpi(jasondata.gpnam,"<SINE>")
                jasondata.dosyconstant=jasondata.gamma.^2*jasondata.delta.^2*...
                    (jasondata.DELTA-(5-3*jasondata.alpha.^2)*(jasondata.delta/16)-(1-jasondata.alpha.^2)*(jasondata.tau/2));
            elseif strcmpi(jasondata.gpnam,"SMSQ") || strcmpi(jasondata.gpnam,"<SMSQ10.100>") || strcmpi(jasondata.gpnam,"SQUARE")
                jasondata.dosyconstant=jasondata.gamma.^2*jasondata.delta.^2*...
                    (jasondata.DELTA-jasondata.delta*((3367*pi.^2-207)*jasondata.alpha.^2+(6344*pi.^2-207))/(19440*pi.^2) -...
                    (jasondata.tau/2)*(1-jasondata.alpha.^2));
            elseif strcmpi(jasondata.gpnam,"RECT") || strcmpi(jasondata.gpnam,"<RECT>")
                jasondata.dosyconstant=jasondata.gamma.^2*jasondata.delta.^2*...
                    (jasondata.DELTA-(2-jasondata.alpha.^2)*(jasondata.delta/6)-(1-jasondata.alpha.^2)*(jasondata.tau/2));
            end
        end
    elseif DataDim == 3 && DataType~=3 %higher order experiments, for PARAFAC
        logtext='3D Data. Probably for PARAFAC. I will try to sort experimental parameters'; disp(logtext)
        jasondata.logfile{end +1}=logtext;
        jasondata.arraydim=size(lists{2, 2},1).*size(lists{2, 1},1);
        jasondata.ngrad=size(lists{2, 2},1);
        jasondata.Gzlvl='non existing';
        jasondata.DELTA='non existing';
        jasondata.delta='non existing';
        jasondata.dosyconstant='non existing';
        if 1 == 2 %NUS file
        % Do nothing for now
        elseif 4 == 2 %Diffusion experiment
        % Do nothing for now
        elseif 3 == 2 %T2 experiment
        % Do nothing for now
        elseif 2 == 2 %T1 experiment
            logtext='T1 experiment';
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
            TD3= lists{2, 1};
            TD2= lists{2, 2};
            list3=lists{2, 1};
            list3(isnan(list3))=0;
            list2=lists{2, 2};
            list2(isnan(list2))=0;
            if nnz(list3)>nnz(list2)
                jasondata.list=list3;
            elseif nnz(list3)<nnz(list2)
                jasondata.list=list2;
            elseif nnz(list3)==nnz(list2)
                if (length(list3)-nnz(list3))==0
                    jasondata.list=list3;
                else
                    jasondata.list=list2;
                end
            end
%             jasondata.ngrad=jasondata.list;
            logtext='using imported list directly for delay values';
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
        else
            logtext='Any list was found';
            disp(logtext)
            jasondata.logfile{end +1}=logtext;
        end
    else
        logtext='No recognizable variable with increment values exist: importing empty arrays';
        disp(logtext)
        jasondata.logfile{end +1}=logtext;
    end
end
        
%% Stracting the Spectra
if DataType==0 %raw data
    compfid=complex(real,img);
    jasondata.FID=compfid;
    % Checking the presence of the Group Delay
    if sum(matches({SpecInfo.Name},'GroupDelay')) >= 1
        p = find(contains({SpecInfo.Name}, {'GroupDelay'}));
        jasondata.GroupDelay = SpecInfo(p(1)).Value;
        jasondata.lp = -2.0 * 3.14159265358979323846 * jasondata.GroupDelay;
        jasondata.lrfid = jasondata.GroupDelay;
        jasondata.rp=1.5157*-1 - jasondata.lp;
    else
        jasondata.lrfid = 0;
    end

    try
        p = h5info(jasondata.filename,['/JasonDocument/NMR/NMRData/',num2str(expnr-1),'/RawData/SpecInfo/OriginalParameters/parameters']);
        % The DosyParameters folder exists
        OriginalParameters = p.Attributes; r = find(matches({OriginalParameters.Name}, {'TRANSITION_RATIO'}));
        jasondata.processing.tr = OriginalParameters(r).Value(1);
    catch ME
        % Get last segment of the error identifier.
        idSegLast = regexp(ME.identifier,'(?<=:)\w+$','match');
        if strcmp(idSegLast,'unableToFind')
            logtext=fprintf('No clipping was used experiment %d \n',expnr-1);
            jasondata.logfile{end +1}=logtext;
        end
        jasondata.processing.tr = 0;
    end
    
    % Vendor correction for Bruker data
    % Temp. correction. The RawData from Bruker seems to come from JASON in the
    % frequency domain. I am ussing 'ifft' to acquire the FID.
    if sum(matches({jasondata.FileFormat},'TopSpin Processed')) >= 1 % For processed data from Bruker imported in JASON
        SPECTRA=complex(real,img);
        temp=fftshift(SPECTRA,1);
        jasondata.FID=(ifft(temp));
    elseif sum(matches({jasondata.FileFormat},'TopSpin')) >= 1 % For raw data from Bruker imported in JASON
        compfid=complex(img,real); % Why are the complex/real points inverted from Bruker raw file?
        jasondata.FID=compfid;
    end

    % Reshaping data for GNAT format
    jasondata.FID=reshape(jasondata.FID,jasondata.np,jasondata.arraydim);
elseif DataType==1 %processed data   
    SPECTRA=complex(real,img);
    temp=fftshift(SPECTRA,1);
    jasondata.FID=(ifft(temp));
    jasondata.lrfid = 0;
end

%% Checking if clipping the data is necessary from spectra imported from JASON/DELTA
% if jasondata.processing.tr ~= 0
%     % Clipping data and inverse FT it
%     clip = 1 - jasondata.processing.tr;
%     % FT
%     SPECTRA=flipud((fftshift(fft(jasondata.FID,jasondata.np),1)));
%     SPECTRA = clipping(SPECTRA, clip);
%     temp=flipud(fftshift(SPECTRA,1));
%     jasondata.FID=(ifft(temp));
% %     jasondata.FID=ifft(ifftshift(SPECTRA));
% 
%     % Correccting some parameters with this new data size
%     jasondata.np=size(SPECTRA,1);
%     jasondata.fn=jasondata.np;
% 
% end

end
