function [mestrenova]=mestrenova_import(inpath)

% For the import of MestreNova JCAMP files

% Get the number of FIDS in the JCAMP file 
tmp_par=GetParameters(inpath,-1);
numfids = str2double(tmp_par.BLOCKS);



%numfids=2
%return 
%Iterate to get all the FIDS
 h_wait= waitbar(0,['Importing ' num2str(numfids) ' spectra. Patience may be needed as JCAMP import can be slow']);
for k=1:numfids

    h_wait= waitbar(k/numfids);
    mestrenova.par=GetParameters(inpath,k);

    if k==1
        np=numel(mestrenova.par.FID);
        SPEC=zeros(numfids,np);
    end
    SPEC(k,:)=mestrenova.par.FID;
   

end
 delete(h_wait)
% we can only deal with spectra aquiired withe the same parameters 
% below, so we'll take tkem from the last paramater set.
mestrenova.sfrq=str2double(mestrenova.par.OBSERVE_FREQUENCY);
mestrenova.sp=str2double(mestrenova.par.LASTX)/mestrenova.sfrq;
mestrenova.sw=(str2double(mestrenova.par.FIRSTX) - str2double(mestrenova.par.LASTX))/mestrenova.sfrq;
mestrenova.np=numel(SPEC(1,:))/2;
mestrenova.FID=zeros(mestrenova.np,numfids);
%Lets get the fids in the right way.
for k=1:numfids
    tmp=ifft(fftshift(SPEC(k,:)));
    mestrenova.FID(:,k)=tmp(1:mestrenova.np);
    
end

mestrenova.nucleus=mestrenova.par.OBSERVE_NUCLEUS(2:end);
%mestrenova.FID= mestrenova.FID';
%end

end


%% UTILITY functions
function OutParams=GetParameters(FilePath,search_mode)

%if search_mode is -1 we only search for the number of blocks and then exit.
%otherwise search_mode is the number FID in the array to import.

file=fopen(FilePath);
k=1;
while ~feof(file)

   parmline=fgetl(file);

 if exist('procpar','var') && isfield(procpar,'BLOCK_ID')
            fidpass_test = str2double(procpar.BLOCK_ID);
 end



    if search_mode==-1
        if exist('procpar','var') && isfield(procpar,'BLOCKS')
             OutParams=procpar;
                return
        end
    else
        if exist('procpar','var') && isfield(procpar,'END')
            fidnr_test = str2double(procpar.BLOCK_ID);
            if fidnr_test==search_mode
                OutParams=procpar;
                return
            else
                procpar=[];
                k=1;
            end
        end
    end

    % 
    % if exist('procpar','var')
    %     bbb=procpar
    % end


    if isempty(parmline)
        continue;
    elseif strcmp(parmline(1:2),'##')
        if contains(parmline,'/')
            continue;
        end
        if parmline(3)=='.'
            %continue;
            parmend=find(parmline=='=');
            if any(isspace(parmline(4:parmend-1)))
                % replacing spaces as they are not allwed in Matlab structure elements
                tmp_line=parmline(4:parmend-1);
                parmline(4:parmend-1)=strrep(tmp_line,' ','_');
                %continue;;
            end

                parmstart=find(parmline=='.');
                parmstart=parmstart(1);

                procpar.(parmline((parmstart+1):(parmend-1)))=parmline((parmend+2):end);

            
        end
        if parmline(3)=='$'
            parmend=find(parmline=='=');
             if any(isspace(parmline(3:parmend-1)))
                continue;
            end
            procpar.(parmline(4:parmend-1))=parmline((parmend+2):end);

        elseif parmline(3)~='.'
            parmend=find(parmline=='=');
            if any(isspace(parmline(3:parmend-1)))
                continue;
            end
         
            % replacing dashes as they are not allwed in Matlab structure elements
            tmp_line=parmline(3:parmend-1);
            parmline(3:parmend-1)=strrep(tmp_line,'-','_');

            procpar.(parmline(3:parmend-1))=parmline((parmend+2):end);


        end

    elseif strcmp(parmline(1:2),'$$')
%Ignore
        % if isempty(find(parmline=='='))==0
        %     parmend=find(parmline=='=');
        %     procpar.(parmline(3:(parmend-1)))=parmline((parmend+2):end);
        % end
    elseif (isstrprop(parmline(2),'digit')==1 || isstrprop(parmline(1),'digit')==1) && fidpass_test~=search_mode 

            continue
    elseif isstrprop(parmline(2),'digit')==1 || isstrprop(parmline(1),'digit')==1 
        %%
%disp('FID data')
        % This is propably the FID so I will save

        % digit 1 check works for new versions but not older
        % versions allow either to enter the loop
       

        fields_n=numel(fieldnames(procpar));
        fields=fieldnames(procpar);

        if strcmpi(fields{fields_n},'XYDATA')==1 || strcmpi(fields{fields_n},'FID')==1
%parmline
            if ~any(isletter(parmline)) % if line only contains values
                % disp(parmline)
                line=split(parmline(2:end));
                procpar.FID(k,:)=str2double(line);
                k=k+1;

            elseif any(isletter(parmline))

                % codes for decompression of JCAMP files
                SQZ = 'ihgfedcba@ABCDEFGHI';
                DIF = 'rqponmlkj%JKLMNOPQR';
                DUP = 'STUVWXYZs';

                values = regexp(parmline,'[+-]*[a-s_A-Z_%@]?\d*\.?\d*([Ee][+-]\d+)?','match'); %split at letter

                xval = sscanf(values{1},'%f'); %get first x value

                for i=2:length(values)
                    mode=1;
                    num=values{i};
                    %% SORT OUT the SQZ charachters
                    if contains(SQZ,num(1))==1

                        dig = find(SQZ==num(1))-10;

                        % replace letter with digit
                        num = sscanf([sprintf('%d',dig) num(2:end)],'%f');
                        y(k)=num;
                        k=k+1;

                    elseif contains(DIF,num(1))==1

                        digDIF = find(DIF==num(1))-10;

                        % replace letter with digit
                        difValue = sscanf([sprintf('%d',digDIF) num(2:end)],'%f');

                        y(k)=y(k-1)+difValue;
                        k = k+1;
                        mode = 2;

                    elseif contains(DUP,num(1))==1

                        dupDig = find(DUP==num(1));

                        if length(num)==1
                            dupValue = dupDig;
                        else
                            dupValue = sscanf([sprintf('%d',dupDig) num(2:end)],'%f');
                        end

                        %         y(k)=num;
                        %         %k=k+1;

                        for n = 1:dupValue-1
                            if mode==1
                                y(k) = y(k-1);
                            else
                                y(k) = y(k-1)+difValue;
                            end
                            k = k+1;
                        end

                    end


                    procpar.FID=y(:,:);
                end
                if (mode==2)
                    k = k-1; % rewind one value for the checkpoint
                end
                procpar.FID=y(:,:)';

            end
        end
    end


end
OutParams=procpar;
fclose(file);
end
