source: aedes_readfid.m @ 113

Last change on this file since 113 was 113, checked in by tjniskan, 9 years ago
  • Iterating...

M aedes_readfid.m
M aedes_revision.m

File size: 57.2 KB
RevLine 
[80]1function [DATA,msg_out] = aedes_readfid(filename,varargin)
2% AEDES_READFID - Read VNMR (Varian) FID-files
[2]3%   
4%
5% Synopsis:
[80]6%        [DATA,msg]=aedes_readfid(filename,'PropertyName1',value1,'PropertyName2',value2,...)
7%        [DATA,msg]=aedes_readfid(filename,'header')
8%        [DATA,msg]=aedes_readfid(filename,output_filename)
[2]9%
10% Description:
11%        The function reads VNMR (Varian) FID-file and return a structure
12%        DATA with fields DataFormat, HDR, FTDATA, KSPACE, PROCPAR, and
13%        PHASETABLE. The fields of the DATA structure are constructed as
14%        follows:
15%       
16%        DATA
17%          |-> DataFormat         (string identifier for data format 'vnmr')
18%          |-> HDR
19%                |-> FileHeader   (data file header)
20%                |-> BlockHeaders (data block headers, not stored by default)
21%                |-> fname        (file name)
22%                |-> fpath        (file path)
[80]23%                |-> Param        (parameter values used by AEDES_READFID to read the data)
[2]24%          |-> FTDATA             (real fourier transformed image data)
25%          |-> KSPACE             (complex k-space, empty by default)
26%          |-> PROCPAR            (parameters from procpar file)
27%          |-> PHASETABLE         (phasetable)
28%
29%        The DATA structure is returned as empty (without HDR, FTDATA,
30%        KSPACE, and PROCPAR fields) if an error has occurred during
31%        reading. The error message is returned in the second output
[80]32%        argument msg. If AEDES_READFID is called with only one output argument
[2]33%        (i.e. without MSG), the error message is echoed to the workspace.
34%       
35%        The first input argument is either a string containing full path to
36%        the FID-file or the header structure HDR. Only the data file header
37%        can be read by giving a string 'header' as the second input
38%        argument.
39%
40%        By default the k-space is not returned, i.e. the field KSPACE is
41%        empty. The returned data can be adjusted by using the 'return'
42%        property and values 1, 2, or 3 (see below for more information).
43%
[80]44%        The supported property-value pairs in AEDES_READFID (property strings
[2]45%        are not case sensitive):
46%
47%        Property:        Value:                Description:
48%        *********        ******                ************
49%        'Return'      :  [ {1} | 2 | 3 | 4 ]   % 1=return only ftdata (default)
50%                                               % 2=return only k-space
51%                                               % 3=return both ftdata & kspace
52%                                               % 4=return raw kspace
53%
[21]54%        'FastRead'    :  [{'off'} | 'on' ]     % Enables an experimental
55%                                               % method for very fast reading
56%                                               % of fid-files. This not as
57%                                               % robust as the older
58%                                               % method and can consume a lot
[22]59%                                               % of memory.
[21]60%
[2]61%        'OutputFile'  :  filename              % Writes the slices into
62%                                               % NIfTI-format files
63%                                               % using the given filename.
64%
65%        'DCcorrection':  [ {'off'} | 'on' ]    % 'on'=use DC correction
66%                                               % 'off'=don't use DC correction
67%                                               % (default)
68%
69%        'Procpar'     :  (procpar-structure)   % Input procpar
70%                                               % structure. If this
71%                                               % property is not set the
72%                                               % procpar structure
73%                                               % will be read using
[80]74%                                               % AEDES_READPROCPAR
[2]75%
76%        'ZeroPadding' :  ['off'|'on'|{'auto'}] % 'off' = force
77%                                               % zeropadding off
78%                                               % 'on' = force
79%                                               % zeropadding on (force
80%                                               % images to be square)
81%                                               % 'auto' = autoselect
82%                                               % using relative FOV
83%                                               % dimensions (default)
84%
85%        'PhaseTable'  : (custom phase table)   % User-specified
86%                                               % line order for
87%                                               % k-space. The phase table
88%                                               % is obtained from the file
89%                                               % specified in
90%                                               % procpar.petable if
91%                                               % necessary.
92%
93%        'sorting'      : [ 'off' | {'on'} ]    % 'off' =disable k-space
94%                                               % sorting, i.e. ignore the
95%                                               % phase table and/or arrays.
96%                                               % 'on' =sort k-space using
97%                                               % phase table and/or array
98%                                               % information if necessary
99%                                               % (default)
100%
101%        'wbar'        : [ {'on'} | 'off' ]     % 'on'  = show waitbar
102%                                               % 'off' = don't show waitbar
103%
104%        'FlipKspace'  : [ {'off'} | 'LR' |
105%                             'UD' | 'LRUD' ]   % 'off' = don't flip (default)
106%                                               % 'LR' = left/right
107%                                               % 'UD' = up/down
108%                                               % 'LRUD' = left/right and
109%                                               % up/down
110%
111%        'FlipInd'     : [ {'all'} | 'alt' |
112%                          (custom vector)  ]   % 'all' = flip all slices
113%                                               % (default)
114%                                               % 'alt' = flip every
115%                                               % second slice
116%                                               % (custom vector) = A
117%                                               % custom vector containing
118%                                               % indices to the flipped slices
119%
[36]120%        'Precision'   : ['single'|{'double'}]  % Precision of the
121%                                               % outputted data.
122%                                               % 'single' = 32-bit float
123%                                               % 'double' = 64-bit float
124%
[75]125%        'OrientImages': [ {'on'} | 'off' ]     % Orient FTDATA after
126%                                               % reading the data using
127%                                               % PROCPAR.orient property.
[67]128%
129%        'RemoveEPIphaseIm' : ['on'|{'off'}]    % Remove the phase image
130%                                               % from EPI data. This
131%                                               % option only affects EPI
132%                                               % images.
133%
[2]134% Examples:
[80]135%        [DATA,msg]=aedes_readfid(filename)             % Read image data from 'filename'
136%        [DATA,msg]=aedes_readfid(filename,'header')    % Read only data file header
[2]137%
[80]138%        [DATA,msg]=aedes_readfid(filename,'return',1)  % Return only image data (default)
139%        [DATA,msg]=aedes_readfid(filename,'return',2)  % Return only k-space
140%        [DATA,msg]=aedes_readfid(filename,'return',3)  % Return both image data and k-space
[2]141%       
142%        % Read first data file header and then image data and k-space
[80]143%        [DATA,msg]=aedes_readfid(filename,'header')
144%        [DATA,msg]=aedes_readfid(DATA.HDR,'return',3)
[2]145%
146%        % Read VNMR-data with default options and save slices in NIfTI
147%        % format
[80]148%        DATA=aedes_readfid('example.fid','saved_slices.nii');
[2]149%
150%        % If you want to use non-default options and also write
151%        % NIfTI-files, use the property/value formalism, for example
[80]152%        DATA=aedes_readfid('example.fid','ZeroPadding','off',...
[2]153%                     'OutputFile','saved_slices.nii');
154%
155% See also:
[80]156%        AEDES_READFIDPREFS, AEDES_READPROCPAR, AEDES_READPHASETABLE,
157%        AEDES_DATA_READ, AEDES_WRITE_NIFTI, AEDES
[2]158
[37]159% This function is a part of Aedes - A graphical tool for analyzing
[36]160% medical images
[2]161%
[36]162% Copyright (C) 2006 Juha-Pekka Niskanen <Juha-Pekka.Niskanen@uku.fi>
163%
[45]164% Department of Physics, Department of Neurobiology
[39]165% University of Kuopio, FINLAND
[36]166%
167% This program may be used under the terms of the GNU General Public
168% License version 2.0 as published by the Free Software Foundation
169% and appearing in the file LICENSE.TXT included in the packaging of
170% this program.
171%
172% This program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
173% WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
[2]174
175
[36]176
177
[2]178if nargout==2
179  Dat.ShowErrors = false;
180  msg_out='';
181else
182  Dat.ShowErrors = true;
183end
184
[35]185%% ---------------------
186% Defaults
187Dat.ReturnKSpace  = false;
188Dat.ReturnFTData  = true;
189Dat.DCcorrection  = false;
190Dat.ZeroPadding = 2;
191Dat.Sorting = true;
192Dat.UsePhaseTable = true;
[77]193Dat.FastDataRead = true;
194Dat.precision = 'single';
[2]195
[67]196
[2]197%% Other defaults
198Dat.ShowWaitbar   = true;
199procpar=[];
200Dat.phasetable=[];
201Dat.FlipKspace = 0;
202Dat.FlipInd = 'all';
203Dat.OutputFile = false;
204Dat.ReturnRawKspace = false;
[67]205Dat.ReorientEPI = false;
206Dat.RemoveEPIphaseIm = false;
[75]207Dat.OrientImages = true;
[2]208
209%% -------------------------------------------------------------------
210
211
212%% Set data format label
213DATA.DataFormat = 'vnmr';
214
215%% Parse input arguments
216if nargin==0 || isempty(filename)
217 
218  %% Get default directory
219  try
[37]220    defaultdir = getpref('Aedes','GetDataFileDir');
[2]221  catch
222    defaultdir = [pwd,filesep];
223  end
224 
225  %% If no input arguments are given, ask for a file
226  [f_name, f_path, f_index] = uigetfile( ...
227       {'fid;FID','Varian FID-files (fid)'; ...
228        '*.*', 'All Files (*.*)'}, ...
229        'Select VNMR (Varian) FID file',defaultdir);
[22]230  if ( all(f_name==0) || all(f_path==0) ) % Cancel is pressed
[2]231    DATA=[];
232    msg_out='Canceled';
233    return
234  end
235  ReadHdr = true;
236  ReadData = true;
237  filename=[f_path,f_name];
238 
239  %% Set default directory to preferences
[37]240  setpref('Aedes','GetDataFileDir',f_path)
[2]241 
242end
243
244if nargin==1
245  if isstruct(filename)
246    hdr = filename;
247    filename = [hdr.fpath,hdr.fname];
248    ReadHdr = false;
249    ReadData = true;
250% $$$     ReturnKSpace = false;
251% $$$     ReturnFTData = true;
252   
253  elseif ischar(filename)
254    ReadHdr = true;
255    ReadData = true;
256% $$$     ReturnKSpace = false;
257% $$$     ReturnFTData = true;
258  end
259elseif nargin==2
260  if strcmpi(varargin{1},'header')
261    ReadHdr = true;
262    ReadData = false;
263% $$$     ReturnKSpace = false;
264  elseif ischar(varargin{1})
265    ReadHdr = true;
266    ReadData = true;
267    Dat.OutputFile = varargin{1};
268  else
269    if ~Dat.ShowErrors
270      DATA=[];
271      msg_out=sprintf('Invalid second input argument "%s".',varargin{1});
272      return
273    else
274      error('Invalid second input argument "%s".',varargin{1})
275    end
276  end
277else
278  if isstruct(filename)
279    hdr = filename;
280    filename = [hdr.fpath,hdr.fname];
281    ReadHdr = false;
282    ReadData = true;
283  elseif isempty(filename)
284    [f_name, f_path, f_index] = uigetfile( ...
285        {'fid;FID','Varian FID-files (fid)'; ...
286         '*.*', 'All Files (*.*)'}, ...
287        'Select VNMR (Varian) FID file');
[22]288    if ( all(f_name==0) || all(f_path==0) ) % Cancel is pressed
[2]289      DATA=[];
290      msg_out='Canceled';
291      return
292    end
293    ReadHdr = true;
294    ReadData = true;
295    filename=[f_path,f_name];
296  else
297    ReadHdr = true;
298    ReadData = true;
299  end
300 
301  for ii=1:2:length(varargin)
302    switch lower(varargin{ii})
303     case 'return'
304      if length(varargin)<2
305        DATA=[];
306        if ~Dat.ShowErrors
307          msg_out='"Return" value not specified!';
308        else
309          error('"Return" value not specified!')
310        end
311        return
312      else
313        if varargin{ii+1}==1
314          Dat.ReturnKSpace = false;
315          Dat.ReturnFTData = true;
316        elseif varargin{ii+1}==2
317          Dat.ReturnKSpace = true;
318          Dat.ReturnFTData = false;
319        elseif varargin{ii+1}==3
320          Dat.ReturnKSpace = true;
321          Dat.ReturnFTData = true;
322                elseif varargin{ii+1}==4
323                  Dat.ReturnRawKspace = true;
324                  Dat.ReturnKSpace = true;
325          Dat.ReturnFTData = false;
326        end
327      end
328     
329     case {'dc','dccorrection','dccorr'}
330      if strcmpi(varargin{ii+1},'on')
331        Dat.DCcorrection = true;
332      else
333        Dat.DCcorrection = false;
334      end
335     
336     case 'procpar'
337      procpar=varargin{ii+1};
338     
339     case 'zeropadding'
[38]340      if ischar(varargin{ii+1})
[2]341        if strcmpi(varargin{ii+1},'on')
342          Dat.ZeroPadding = 1; % on
343        elseif strcmpi(varargin{ii+1},'off')
344          Dat.ZeroPadding = 0; % off
345        else
346          Dat.ZeroPadding = 2; % auto
347        end
348      else
349        % Undocumented
350        Dat.ZeroPadding = 3; % Custom
351        Dat.CustomZeroPadding = varargin{ii+1};
352      end
353     
354     case 'phasetable'
355      Dat.phasetable = varargin{ii+1};
356     
357     case 'sorting'
[22]358          if strcmpi(varargin{ii+1},'on')
[2]359        Dat.UsePhaseTable = true;
360        Dat.Sorting = true;
361      else
362        Dat.UsePhaseTable = false;
363        Dat.Sorting = false;
[21]364          end
365     
366         case 'fastread'
367           if strcmpi(varargin{ii+1},'on')
[22]368                 Dat.FastDataRead = true;
369           else
370                 Dat.FastDataRead = false;
371           end
[21]372           
[2]373     case 'wbar'
374      if strcmpi(varargin{ii+1},'on')
375        Dat.ShowWaitbar = 1;
376      else
377        Dat.ShowWaitbar = 0;
[36]378          end
379         
380         case 'precision'
381           if strcmpi(varargin{ii+1},'single')
382                 Dat.precision = 'single';
383           end
384               
385          case 'flipkspace'
[2]386       
387        flipkspace = varargin{ii+1};
388        if strcmpi(flipkspace,'off')
389          Dat.FlipKspace=0;
390        elseif strcmpi(flipkspace,'LR')
391          Dat.FlipKspace=1;
392        elseif strcmpi(flipkspace,'UD')
393          Dat.FlipKspace=2;
394        elseif strcmpi(flipkspace,'LRUD')
395          Dat.FlipKspace=3;
396        else
397          DATA=[];
398          if ~Dat.ShowErrors
[22]399            msg_out = 'Bad value for property FlipKspace!';
[2]400          else
401            error('Bad value for property FlipKspace!')
402          end
403          return
404        end
405       
406      case 'flipind'
407        Dat.FlipInd = varargin{ii+1};
408       
409      case 'outputfile'
410        Dat.OutputFile = varargin{ii+1};
411       
[67]412      case 'reorientepi'
413        if strcmpi(varargin{ii+1},'on')
414          Dat.ReorientEPI = true;
415        end
416       
417      case 'removeepiphaseim'
418        if strcmpi(varargin{ii+1},'on')
419          Dat.RemoveEPIphaseIm = true;
420        end
[75]421      case 'orientimages'
422        if strcmpi(varargin{ii+1},'off')
423          Dat.OrientImages = false;
424        end
[2]425     otherwise
426      DATA=[];
427      if ~Dat.ShowErrors
428        msg_out = ['Unknown property "' varargin{ii} '"'];
429      else
430        error(['Unknown property "' varargin{ii} '"'])
431      end
432      return
433    end
434  end
435end
436
437% Parse filename
438[fpath,fname,fext]=fileparts(filename);
439if ~strcmpi(fname,'fid')
440  if isempty(fname)
441    fpath = [fpath,filesep];
442  else
[53]443        if isempty(fpath)
444          fpath = [pwd,filesep,fname,fext,filesep];
445        else
446          fpath = [fpath,filesep,fname,fext,filesep];
447        end
[2]448  end
449  fname = 'fid';
450else
451  fpath = [fpath,filesep];
452end
453
454%% Read procpar if not given as input argument
455if isempty(procpar) || nargin~=2
[80]456  [procpar,proc_msg]=aedes_readprocpar([fpath,'procpar']);
[2]457  if isempty(procpar)
458    DATA=[];
459    if ~Dat.ShowErrors
460      msg_out=proc_msg;
461    else
462      error(proc_msg)
463    end
464    return
465  end
466end
467
468%% Read phasetable if necessary
469if isfield(procpar,'petable') && isempty(Dat.phasetable) && ...
[71]470    ~isempty(procpar.petable{1}) && ~strcmpi(procpar.petable{1},'n') && ...
471    Dat.Sorting
[2]472  % Look in preferences for tablib-directory
473  try
[37]474    tabpath = getpref('Aedes','TabLibDir');
[2]475  catch
[37]476    % If the table path was not found in preferences, try to use aedes
[2]477    % directory
[37]478    tmp_path = which('aedes');
[2]479    if ~isempty(tmp_path)
[37]480      aedes_path=fileparts(tmp_path);
481      tabpath = [aedes_path,filesep,'tablib',filesep];
[2]482    else
483      % If all else fails, look in the current directory
484      tabpath = [pwd,filesep,'tablib',filesep];
485    end
486  end
[80]487  [phasetable,msg] = aedes_readphasetable([tabpath,procpar.petable{1}]);
[2]488 
[71]489  % If petable cannot be found, check if it is in procpar...
490  if isempty(phasetable) && isfield(procpar,'pe_table')
491    phasetable = {'t1',procpar.pe_table(:)};
492  end
493 
[82]494  % If the sequence is a fast spin echo, try to construct the phasetable
495  if isempty(phasetable) && isfield(procpar,'petable') && ...
496      strncmpi(procpar.petable{1},'fse',3)
497    phasetable = {'t1',l_CreateFsemsPhaseTable(procpar)};
498  end
499 
[2]500  %% Abort and throw error if phasetable cannot be read and the FID-file
501  % has not been sorted
502  if isempty(phasetable) && ~isfield(procpar,'flash_converted')
503    DATA=[];
504    if ~Dat.ShowErrors
505      msg_out={['Could not find the required phase table "' ...
506                procpar.petable{1} '" in the following folders'],...
507               ['"' tabpath '".']};
508    else
509      error('Could not find the required phase table "%s" in %s',...
510            procpar.petable{1},tabpath)
511    end
512    return
[22]513  elseif ( isempty(phasetable) && isfield(procpar,'flash_converted') ) || ...
[2]514      ~Dat.UsePhaseTable
515    %% If the FID-file has been sorted, the reading can continue but
516    % throw a warning.
[80]517    fprintf(1,'Warning: aedes_readfid: Could not find phasetable "%s" in "%s"!\n',procpar.petable{1},tabpath)
[2]518    Dat.phasetable=[];
519  else
520    Dat.phasetable = phasetable{1,2};
521  end
522end
523
524% Convert phasetable indices to MATLAB indices
525if ~isempty(Dat.phasetable)
526  Dat.phasetable=Dat.phasetable+(-min(min(Dat.phasetable))+1);
527else
528  Dat.UsePhaseTable = false;
529end
530
531%% Open FID-file
532[file_fid,msg]=fopen([fpath,fname],'r','ieee-be');
533if file_fid < 0
534  DATA=[];
535  if ~Dat.ShowErrors
536    msg_out=['Could not open file "' filename '" for reading.'];
537  else
538    error('Could not open file "%s" for reading.',filename)
539  end
540  return
541end
542
543% Read only header
544if ReadHdr && ~ReadData
545  [hdr,msg_out]=l_ReadDataFileHeader(file_fid);
546  if ~isempty(msg_out)
547    DATA=[];
548    fclose(file_fid);
549    if Dat.ShowErrors
550      error(msg_out)
551    end
552    return
553  else
554    DATA.HDR.FileHeader = hdr.FileHeader;
555    DATA.FTDATA=[];
556    DATA.KSPACE=[];
557    DATA.PROCPAR=[];
558    DATA.PHASETABLE=[];
559  end
560elseif ~ReadHdr && ReadData % Header structure given as input argument
561                            % Read only data.
562  [hdr,data,kspace,msg_out]=l_ReadBlockData(file_fid,hdr,Dat,procpar);
563  if ~isempty(msg_out)
564    DATA=[];
565    fclose(file_fid);
566    if Dat.ShowErrors
567      error(msg_out)
568    end
569    return
570  else
571    DATA.HDR.FileHeader=hdr.FileHeader;
572    DATA.HDR.BlockHeaders = hdr.BlockHeaders;
573    DATA.FTDATA=data;
574    DATA.KSPACE=kspace;
575    DATA.PROCPAR=procpar;
576    DATA.PHASETABLE=Dat.phasetable;
577  end
578elseif ReadHdr && ReadData  % Read headers and data
579  [hdr,msg_out]=l_ReadDataFileHeader(file_fid);
580  [hdr,data,kspace,msg_out]=l_ReadBlockData(file_fid,hdr,Dat,procpar);
581  if ~isempty(msg_out)
582    DATA=[];
583    fclose(file_fid);
584    if Dat.ShowErrors
585      error(msg_out)
586    end
587    return
588  else
589    DATA.HDR.FileHeader=hdr.FileHeader;
590    DATA.HDR.BlockHeaders = hdr.BlockHeaders;
591    DATA.FTDATA=data;
592    DATA.KSPACE=kspace;
593    DATA.PROCPAR=procpar;
594    DATA.PHASETABLE=Dat.phasetable;
595  end
596end
597
598% Set file name and path to the HDR structure
599DATA.HDR.fname=fname;
600DATA.HDR.fpath=fpath;
601
602% Set parameter values
603DATA.HDR.Param.ReturnKSpace = Dat.ReturnKSpace;
604DATA.HDR.Param.ReturnFTData = Dat.ReturnFTData;
605if Dat.ZeroPadding==0
606  DATA.HDR.Param.ZeroPadding = 'off';
607elseif Dat.ZeroPadding==1
608  DATA.HDR.Param.ZeroPadding = 'on';
609else
610  DATA.HDR.Param.ZeroPadding = 'auto';
611end
612if ~Dat.DCcorrection
613  DATA.HDR.Param.DCcorrection = 'off';
614else
615  DATA.HDR.Param.DCcorrection = 'on';
616end
617if Dat.Sorting==0
618  DATA.HDR.Param.Sorting = 'off';
619else
620  DATA.HDR.Param.Sorting = 'on';
621end
622if Dat.FlipKspace==0
623  DATA.HDR.Param.FlipKspace = 'off';
624elseif Dat.FlipKspace==1
625  DATA.HDR.Param.FlipKspace = 'LR';
626elseif Dat.FlipKspace==2
627  DATA.HDR.Param.FlipKspace = 'UD';
628elseif Dat.FlipKspace==3
629  DATA.HDR.Param.FlipKspace = 'LRUD';
630end
631DATA.HDR.Param.FlipInd = Dat.FlipInd;
632
633
634% Close file
635fclose(file_fid);
636
637%% Write slices to NIfTI files
638if ischar(Dat.OutputFile)
639  if isempty(Dat.OutputFile)
640    [fp,fn,fe]=fileparts(DATA.HDR.fpath(1:end-1));
641    fprefix=fn;
642    niipath = [pwd,filesep];
643  else
644    [fp,fn,fe]=fileparts(Dat.OutputFile);
645    if strcmpi(fe,'.nii')
646      fprefix=fn;
647    else
648      fprefix=[fn,fe];
649    end
650    if isempty(fp)
651      niipath = [pwd,filesep];
652    else
653      niipath = [fp,filesep];
654    end
655  end
656 
657  % Create file names
658  filenames={};
659  for ii=1:size(DATA.FTDATA,3)
660    filenames{ii}=sprintf('%s%03d%s',[fprefix,'_'],ii,'.nii');
661  end
662  nFiles = length(filenames);
663   
[80]664  h=aedes_wbar(0,sprintf('Saving slice 1/%d in NIfTI format...',nFiles));
[2]665  for ii=1:nFiles
[80]666    aedes_wbar(ii/nFiles,h,sprintf('Saving slice %d/%d in NIfTI format...',ii, ...
[2]667                             nFiles))
[80]668    [done,msg]=aedes_write_nifti(DATA.FTDATA(:,:,ii),...
[2]669                           [niipath,filenames{ii}],'DataType','single',...
670                           'FileType',2);
671  end
672  delete(h)
673 
674  if ~done
675    warning('Error occurred while writing NIfTI-files. Could not write file(s)!')
676  end
677 
678end
679return
680
681%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
682% Read Data File (Main) Header
683%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
684function [hdr,msg_out]=l_ReadDataFileHeader(file_fid)
685
686msg_out='';
687%% Read Data File Header
688try
689  FH.nblocks = fread(file_fid,1,'long');   % Number of blocks in file
690  FH.ntraces = fread(file_fid,1,'long');   % Number of traces per block
691  FH.np = fread(file_fid,1,'long');        % Number of elements per trace
692  FH.ebytes = fread(file_fid,1,'long');    % Number of bytes per element
693  FH.tbytes = fread(file_fid,1,'long');    % Number of bytes per trace
694  FH.bbytes = fread(file_fid,1,'long');    % Number of bytes per block
695  FH.vers_id = fread(file_fid,1,'short');  % Software version, file_id status bits
696  FH.status = fread(file_fid,1,'short');   % Status of whole file
697  FH.nbheaders = fread(file_fid,1,'long'); % Number of block headers per block
698 
699  hdr.FileHeader = FH;
700 
701  %% Parse status bits
702  hdr.FileHeader.status=[];
703  tmp_str = {'S_DATA',...          % 0 = no data, 1 = data
704             'S_SPEC',...          % 0 = FID, 1 = spectrum
705             'S_32',...            % 0 = 16 bit, 1 = 32 bit integer
706             'S_FLOAT',...         % 0 = integer, 1 = floating point
707             'S_COMPLEX',...       % 0 = real, 1 = complex
708             'S_HYPERCOMPLEX',...  % 1 = hypercomplex
709             '',...                % Unused bit
710             'S_ACQPAR',...        % 0 = not Acqpar, 1 = Acqpar
711             'S_SECND',...         % 0 = first FT, 1 = second FT
712             'S_TRANSF',...        % 0 = regular, 1 = transposed
713             '',...                % Unused bit
714             'S_NP',...            % 1 = np dimension is active
715             'S_NF',...            % 1 = nf dimension is active
716             'S_NI',...            % 1 = ni dimension is active
717             'S_NI2',...           % 1 = ni2 dimension is active
718             ''...                 % Unused bit
719            };
720  status_bits = fliplr(double(dec2bin(FH.status,16))==49);
721  for ii=1:length(tmp_str)
722    if ~isempty(tmp_str{ii})
723      hdr.FileHeader.status.(tmp_str{ii}) = status_bits(ii);
724    end
725  end
726catch
727  hdr=[];
728  msg_out=['Error occurred while reading file header from "' filename '".'];
729  return
730end
731
732
733%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
734% Read Block Headers and Data
735%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
736function [hdr,data,kspace,msg_out]=l_ReadBlockData(file_fid,hdr,Dat,procpar)
737
738hdr.BlockHeaders = [];
739%hdr.HypercmplxBHeaders = [];
740data=[];
741kspace=[];
742count = [];
743msg_out='';
744
745if isfield(procpar,'seqcon')
[103]746  procpar.seqcon=procpar.seqcon{1};
[2]747else
[103]748  procpar.seqcon='nnnnn';
[2]749end
750
751%% Determine acquisition type from seqcon parameter
[103]752if all(procpar.seqcon=='n')          % 1D spectroscopy
753  Dat.AcqType=1;
754elseif all(procpar.seqcon(4:5)=='n') % 2D imaging
755  Dat.AcqType=2;
756elseif procpar.seqcon(5)=='n'        % 3D imaging
757  Dat.AcqType=3;
[2]758else                         % 4D imaging
[103]759  Dat.AcqType=4;
[2]760end
761
762%% Double-check that AcqType is not 1D spectral
763if isfield(procpar,'nv') && procpar.nv==0
[103]764  Dat.AcqType=1;
[2]765end
766
767%% Use some heuristical approach to "triple-check" that the data is not
768%  1D spectral
769if ~isempty(strfind(procpar.seqfil{1},'STEAM')) || ...
770      ~isempty(strfind(procpar.seqfil{1},'steam')) || ...
771      ~isempty(strfind(procpar.seqfil{1},'LASER')) || ...
772      ~isempty(strfind(procpar.seqfil{1},'laser')) || ...
773      ~isempty(strfind(procpar.seqfil{1},'PRESS')) || ...
774      ~isempty(strfind(procpar.seqfil{1},'press')) || ...
775      ~isempty(strfind(procpar.seqfil{1},'1PULSE')) || ...
776      ~isempty(strfind(procpar.seqfil{1},'1pulse')) || ...
777      ~isempty(strfind(procpar.seqfil{1},'2PULSE')) || ...
778      ~isempty(strfind(procpar.seqfil{1},'2pulse'))
[103]779  Dat.AcqType=1;
[2]780end
781
782UsePhaseTable=Dat.UsePhaseTable;
783
784
785%% If the data has been converted with flashc, the seqcon parameter needs
786% to be changed
787if isfield(procpar,'flash_converted')
788  if isfield(procpar,'ni') && procpar.ni>1
[103]789    procpar.seqcon(3)='s';
790  elseif ((procpar.seqcon(2)=='c') && (procpar.seqcon(3)=='c'))
791    procpar.seqcon(2)='s';
[2]792  end
793  UsePhaseTable=false; % Do not try to order data if flashc has been run
794end
795
796%% Set number of transients
797if ~isfield(procpar,'nt')
798  nt=1;
799else
800  nt=procpar.nt;
801end
802
803%% Determine if the arrayed acquisition was used
[53]804if isfield(procpar,'array') && ~isempty(procpar.array{1})
[2]805 
[60]806  if length(procpar.array)==1 && ~iscell(procpar.array{1}) && ...
807      strcmp(procpar.array{1},'pad') && all(procpar.pad==0)
808    % Skip the array parsing if the array is a dummy "pad"-array...
[103]809    Dat.isAcqArrayed = false;
810    Dat.ArrayLength = 1;
[58]811  else
[103]812    Dat.isAcqArrayed = true;
813    Dat.ArrayLength = [];
[60]814   
815    % Determine array length
816    for ii=1:length(procpar.array)
817      if iscell(procpar.array{ii})
[103]818        Dat.ArrayLength(ii) = length(procpar.(procpar.array{ii}{1}));
[60]819      else
[103]820        Dat.ArrayLength(ii) = length(procpar.(procpar.array{ii}));
[60]821      end
822    end
[103]823    Dat.ArrayLength = prod(Dat.ArrayLength);
[2]824  end
825else
[103]826  Dat.isAcqArrayed = false;
827  Dat.ArrayLength = 1;
[2]828end
829
830%% Determine if the data is EPI data
[71]831if ( isfield(procpar,'readres') && isfield(procpar,'phaseres') ) || ...
832    ( isfield(procpar,'apptype') && strcmp(procpar.apptype{1},'imEPI') )
[2]833  Dat.isEPIdata = true;
834else
835  Dat.isEPIdata = false;
836end
837
838BlockHeadStatusLabels = {'S_DATA',...       % 0 = no data, 1 = data
839                    'S_SPEC',...          % 0 = FID, 1 = spectrum
840                    'S_32',...            % 0 = 16 bit, 1 = 32 bit integer
841                    'S_FLOAT',...         % 0 = integer, 1 = floating point
842                    'S_COMPLEX',...       % 0 = real, 1 = complex
843                    'S_HYPERCOMPLEX',...  % 1 = hypercomplex
844                    '',...                % Unused bit
845                    'MORE_BLOCKS',...     % 0 = absent, 1 = present
846                    'NP_CMPLX',...        % 0 = real, 1 = complex
847                    'NF_CMPLX',...        % 0 = real, 1 = complex
848                    'NI_CMPLX',...        % 0 = real, 1 = complex
849                    'NI2_CMPLX',...       % 0 = real, 1 = complex
850                    '',...                % Unused bit
851                    '',...                % Unused bit
852                    '',...                % Unuesd bit
853                    ''...                 % Unused bit
854                   };
855
856BlockHeadModeLabels = {'NP_PHMODE',...   % 1 = ph mode
857                    'NP_AVMODE',...    % 1 = av mode
858                    'NP_PWRMODE',...   % 1 = pwr mode
859                    '',...             % Unused bit
860                    'NF_PHMODE',...    % 1 = ph mode
861                    'NF_AVMODE',...    % 1 = av mode
862                    'NF_PWRMODE',...   % 1 = pwr mode
863                    '',...             % Unused bit
864                    'NI_PHMODE',...    % 1 = ph mode
865                    'NI_AVMODE',...    % 1 = av mode
866                    'NI_PWRMODE',...   % 1 = pwr mode
867                    '',...             % Unused bit
868                    'NI2_PHMODE',...   % 1 = ph mode
869                    'NI2_AVMODE',...   % 1 = av mode
870                    'NI2_PWRMODE',...  % 1 = pwr mode
871                    ''...              % Unused bit
872                   };
873
874
875% The nbheaders -field is not correct in some cases. Thus, this field
876% cannot be trusted and the real nbheaders has to be calculated from the
877% byte counts.
878tmp_bytes=hdr.FileHeader.bbytes-hdr.FileHeader.tbytes*hdr.FileHeader.ntraces;
879header_bytes=28;
880if rem(tmp_bytes,header_bytes)~=0
881  msg_out = 'Block header byte count does not match with file header';
882  return
883else
884  nbheaders = tmp_bytes/28;
885end
[37]886%nbheaders = hdr.FileHeader.nbheaders;
[2]887
888%% Allocate space for k-space
[84]889% kspace=zeros(hdr.FileHeader.np/2,...
890%              hdr.FileHeader.ntraces,hdr.FileHeader.nblocks);
[2]891
[84]892if ~Dat.FastDataRead
[103]893  if any(Dat.AcqType==[1 2])
894    switch procpar.seqcon(2:3)
[84]895      case {'cc','sc'}
896        kspace = zeros(hdr.FileHeader.np/2,...
897          hdr.FileHeader.ntraces,...
898          hdr.FileHeader.nblocks,Dat.precision);
899      otherwise
900        kspace = zeros(hdr.FileHeader.np/2,...
901          hdr.FileHeader.nblocks,...
902          hdr.FileHeader.ntraces,Dat.precision);
903    end
904  else
[2]905    kspace = zeros(hdr.FileHeader.np/2,...
[84]906      hdr.FileHeader.ntraces,...
907      hdr.FileHeader.nblocks,Dat.precision);
[2]908  end
909else
[113]910  %kspace = [];
911   kspace = zeros(hdr.FileHeader.np/2*hdr.FileHeader.ntraces,...
912     hdr.FileHeader.nblocks,Dat.precision);
[2]913end
914
[21]915%% - The older robust (but also slower) way for reading the data.
916%% When the blocksize is relatively small, this is also quite fast.
917if ~Dat.FastDataRead
[2]918
[21]919  % Initialize waitbar
920  if Dat.ShowWaitbar
[80]921        wb_h = aedes_wbar(0/hdr.FileHeader.nblocks,...
[103]922          {['Reading ',num2str(Dat.AcqType),'D VNMR data (seqcon: "' procpar.seqcon '")'],...
[21]923          ['(Processing data block ' ...
924          num2str(0) '/' num2str(hdr.FileHeader.nblocks) ')']});
925  end
[2]926
[21]927  %% Read data and block headers
928  for ii=1:hdr.FileHeader.nblocks
929        %% Update waitbar
930        if Dat.ShowWaitbar
[80]931          aedes_wbar(ii/hdr.FileHeader.nblocks,...
[21]932                wb_h,...
[103]933                {['Reading ',num2str(Dat.AcqType),'D VNMR data (seqcon: "' procpar.seqcon '")'],...
[21]934                ['(Processing data block ' ...
935                num2str(ii) '/' num2str(hdr.FileHeader.nblocks) ')']})
936        end
[2]937
[21]938        %% Read block header and hypercomplex header
939        for kk=1:nbheaders
940          %% Read block header
941          if kk==1
942                hdr.BlockHeaders.scale = fread(file_fid,1,'short');  % Scaling factor
943                tmp_status = fread(file_fid,1,'short'); % Status of data in block
944                hdr.BlockHeaders.status = [];
945                hdr.BlockHeaders.index = fread(file_fid,1,'short');  % Block index
946                tmp_mode = fread(file_fid,1,'short');   % Mode of data in block
947                hdr.BlockHeaders.mode = [];
948                hdr.BlockHeaders.ctcount = fread(file_fid,1,'long'); % ct value for FID
949                hdr.BlockHeaders.lpval = fread(file_fid,1,'float');  % f2 (2D-f1) left phase in phasefile
950                hdr.BlockHeaders.rpval = fread(file_fid,1,'float');  % f2 (2D-f1) right phase in phasefile
951                hdr.BlockHeaders.lvl = fread(file_fid,1,'float');    % level drift correction
952                hdr.BlockHeaders.tlt = fread(file_fid,1,'float');    % tilt drift correction
953
954                %% Parse status and mode bits
955                status_bits = fliplr(double(dec2bin(tmp_status,16))==49);
956                mode_bits = fliplr(double(dec2bin(tmp_mode,16))==49);
957                for tt=1:length(BlockHeadStatusLabels)
958                  if ~isempty(BlockHeadStatusLabels{tt})
959                        hdr.BlockHeaders.status.(BlockHeadStatusLabels{tt}) = status_bits(tt);
960                  end
961                  if ~isempty(BlockHeadModeLabels{tt})
962                        hdr.BlockHeaders.mode.(BlockHeadModeLabels{tt}) = mode_bits(tt);
963                  end
964                end
965
966
967          else %% Read hypercomplex header
968                fread(file_fid,1,'short'); % Spare
969                hdr.BlockHeaders.HCHstatus = fread(file_fid,1,'short');
970                fread(file_fid,1,'short'); % Spare
971                fread(file_fid,1,'short'); % Spare
972                fread(file_fid,1,'long'); % Spare
973                hdr.BlockHeaders.HCHlpval1 = fread(file_fid,1,'float');
974                hdr.BlockHeaders.HCHrpval1 = fread(file_fid,1,'float');
975                fread(file_fid,1,'float'); % Spare
976                fread(file_fid,1,'float'); % Spare
977          end
978        end
[37]979       
980        %% Check block index to be sure about the data type
981        if hdr.BlockHeaders.index~=ii
982          fprintf(1,'Warning: Index mismatch in "%s" block %d\n',fopen(file_fid),ii);
983         
984          % Use information from the file header instead of the BlockHeader if
985          % there is a mismatch in blockheader index...
986          useFileHeader = true;
987        else
988          useFileHeader = false;
989        end
990       
[21]991        %% Determine data precision
[37]992        if useFileHeader
993          if hdr.FileHeader.status.S_FLOAT==1
994                prec_str = ['single=>',Dat.precision];
995          elseif hdr.FileHeader.status.S_32==1 ...
996                  && hdr.FileHeader.status.S_FLOAT==0
997                prec_str = ['int32=>',Dat.precision];
998          elseif hdr.FileHeader.status.S_32==0 ...
999                  && hdr.FileHeader.status.S_FLOAT==0
1000                prec_str = ['int16=>',Dat.precision];
1001          end
1002         
1003        else
1004          if hdr.BlockHeaders.status.S_FLOAT==1
1005                prec_str = ['single=>',Dat.precision];
1006          elseif hdr.BlockHeaders.status.S_32==1 ...
1007                  && hdr.BlockHeaders.status.S_FLOAT==0
1008                prec_str = ['int32=>',Dat.precision];
1009          elseif hdr.BlockHeaders.status.S_32==0 ...
1010                  && hdr.BlockHeaders.status.S_FLOAT==0
1011                prec_str = ['int16=>',Dat.precision];
1012          end
[21]1013        end
1014
1015        % Read k-space
1016        tmp=fread(file_fid,...
1017          [hdr.FileHeader.np,hdr.FileHeader.ntraces],...
1018          prec_str);
1019
1020
1021        % Store complex block and perform DC correction
1022        if ~Dat.DCcorrection || ( nt(1)>1 )
1023          complex_block = complex(tmp(1:2:end,:),tmp(2:2:end,:));
1024        else
1025          complex_block = complex(tmp(1:2:end,:)-hdr.BlockHeaders.lvl,...
1026                tmp(2:2:end,:)-hdr.BlockHeaders.tlt);
1027        end
1028
1029
1030        %% Store and order k-space values
[103]1031        if any(Dat.AcqType==[1 2])
1032          switch procpar.seqcon(2:3)
[21]1033                case {'cc','sc'}
1034                  kspace(:,:,ii) = complex_block;
1035                otherwise
1036                  kspace(:,ii,:) = complex_block;
1037          end
1038        else
1039          kspace(:,:,ii) = complex_block;
1040        end
1041
1042        % Do not save blockheaders by default. When reading data files with a lot of
1043        % blocks (e.g. over 1000) the processing of the DATA structure can be
1044        % slowed down considerably. If you for some reason want to save also the
1045        % block headers in the DATA structure comment out the code line below.
[84]1046        hdr.BlockHeaders = [];
[21]1047  end % for ii=1:hdr.
1048
[2]1049  if Dat.ShowWaitbar
[21]1050        delete(wb_h)
1051  end
[2]1052 
[21]1053else
[22]1054  %% -------------------------------------------------------------------
[21]1055  %% Fast Method for reading data. This may fail with some datas and can
1056  %% also require a relatively large amount of memory. This
1057  %% method should be used for EPI datas that contain a large number
1058  %% of block headers...
1059 
[112]1060  % Check the size of the FID-file
1061  d=dir(fopen(file_fid));
1062  file_sz = d.bytes/1024/1024; % File size in MB
[113]1063  if file_sz<500
1064    nBlocks = 1;
1065  else
1066    nBlocks = ceil(file_sz/500); % Read data in 500 MB blocks
1067  end
[112]1068 
[21]1069  % Initialize waitbar
1070  if Dat.ShowWaitbar
[103]1071        wb_h = aedes_calc_wait(['Reading ',num2str(Dat.AcqType),...
1072          'D VNMR data (seqcon: "' procpar.seqcon '")']);
[2]1073  end
1074 
[22]1075  % The first block header is read and it is assumed that the values in
1076  % the other block headers don't change. 
1077  hdr.BlockHeaders.scale = fread(file_fid,1,'short');  % Scaling factor
1078  tmp_status = fread(file_fid,1,'short'); % Status of data in block
1079  hdr.BlockHeaders.status = [];
1080  hdr.BlockHeaders.index = fread(file_fid,1,'short');  % Block index
1081  tmp_mode = fread(file_fid,1,'short');   % Mode of data in block
1082  hdr.BlockHeaders.mode = [];
1083  hdr.BlockHeaders.ctcount = fread(file_fid,1,'long'); % ct value for FID
1084  hdr.BlockHeaders.lpval = fread(file_fid,1,'float');  % f2 (2D-f1) left phase in phasefile
1085  hdr.BlockHeaders.rpval = fread(file_fid,1,'float');  % f2 (2D-f1) right phase in phasefile
1086  hdr.BlockHeaders.lvl = fread(file_fid,1,'float');    % level drift correction
1087  hdr.BlockHeaders.tlt = fread(file_fid,1,'float');    % tilt drift correction
1088 
1089  %% Parse status and mode bits
1090  status_bits = fliplr(double(dec2bin(tmp_status,16))==49);
1091  mode_bits = fliplr(double(dec2bin(tmp_mode,16))==49);
1092  for tt=1:length(BlockHeadStatusLabels)
[78]1093    if ~isempty(BlockHeadStatusLabels{tt})
1094      hdr.BlockHeaders.status.(BlockHeadStatusLabels{tt}) = status_bits(tt);
1095    end
1096    if ~isempty(BlockHeadModeLabels{tt})
1097      hdr.BlockHeaders.mode.(BlockHeadModeLabels{tt}) = mode_bits(tt);
1098    end
[22]1099  end
1100 
1101  %% Determine data precision
1102  if hdr.BlockHeaders.status.S_FLOAT==1
[78]1103    prec_str = ['single=>',Dat.precision];
1104    prec = 4; % Precision in bytes
[22]1105  elseif hdr.BlockHeaders.status.S_32==1 ...
[78]1106      && hdr.BlockHeaders.status.S_FLOAT==0
1107    prec_str = ['int32=>',Dat.precision];
1108    prec = 4;
[22]1109  elseif hdr.BlockHeaders.status.S_32==0 ...
[78]1110      && hdr.BlockHeaders.status.S_FLOAT==0
1111    prec_str = ['int16=>',Dat.precision];
1112    prec = 2;
[2]1113  end
1114 
[22]1115  % Seek the file back to the beginning of the first block header
1116  fseek(file_fid,-28,0);
1117 
[21]1118  % Determine the number of values that will result from block header(s)
1119  nVals = (nbheaders*28)/prec;
[2]1120 
[113]1121  count = 1;
1122  nbh = floor(nbheaders/nBlocks);
1123  szh = nVals+hdr.FileHeader.np*hdr.FileHeader.ntraces;
1124  for ii=1:nBlocks
1125   
1126    % Read the whole data including block headers etc...
1127    if ii==nBlocks
1128      tmp = fread(file_fid,inf,prec_str);
1129    else
1130      tmp = fread(file_fid,nbh*szh,prec_str);
1131    end
1132    tmp=reshape(tmp,nVals+hdr.FileHeader.np*hdr.FileHeader.ntraces,[]);
1133    tmp(1:nVals,:)=[];
1134   
1135    if ii==nBlocks
1136      inds = ((nBlocks-1)*nbh+1):size(kspace,2);
1137    else
1138      inds = ((nBlocks-1)*nbh+1):nBlocks*nbh;
1139    end
1140   
1141    % Do DC-correction if necessary
1142    if ~Dat.DCcorrection || ( nt(1)>1 )
1143      kspace(:,inds)=complex(tmp(1:2:end,:,:),tmp(2:2:end,:,:));
1144    else
1145      kspace(:,inds)=complex(tmp(1:2:end,:,:)-hdr.BlockHeaders.lvl,...
1146        tmp(2:2:end,:,:)-hdr.BlockHeaders.tlt);
1147    end
1148  end
1149  clear tmp
[112]1150 
[113]1151  % Transform to 3D matrix
1152  kspace = reshape(kspace,hdr.FileHeader.np/2,...
1153    hdr.FileHeader.ntraces,hdr.FileHeader.nblocks);
1154
[2]1155 
[113]1156%   % Read the whole data including block headers etc...
1157%   kspace = fread(file_fid,inf,prec_str);
1158%   kspace=reshape(kspace,nVals+hdr.FileHeader.np*hdr.FileHeader.ntraces,[]);
1159%   
1160%   % Remove block headers from the data
1161%   kspace(1:nVals,:)=[];
1162%   %kspace=kspace(nVals+1:end,:);
1163%   
1164%   % Transform to complex values
1165%   kspace = reshape(kspace,hdr.FileHeader.np,...
1166%       hdr.FileHeader.ntraces,hdr.FileHeader.nblocks);
1167%   
1168%   % Do DC-correction if necessary
1169%   if ~Dat.DCcorrection || ( nt(1)>1 )
1170%     kspace=complex(kspace(1:2:end,:,:),kspace(2:2:end,:,:));
1171%   else
1172%     kspace=complex(kspace(1:2:end,:,:)-hdr.BlockHeaders.lvl,...
1173%       kspace(2:2:end,:,:)-hdr.BlockHeaders.tlt);
1174%   end
[2]1175 
1176  %% Store and order k-space values
[103]1177  if any(Dat.AcqType==[1 2])
1178    switch procpar.seqcon(2:3)
[78]1179      case {'cc','sc'}
1180        %kspace(:,:,ii) = complex_block;
1181      otherwise
1182        %kspace(:,ii,:) = complex_block;
1183        kspace = permute(kspace,[1 3 2]);
1184    end
[2]1185  else
[78]1186    %kspace(:,:,ii) = complex_block;
[2]1187  end
1188 
[21]1189  if Dat.ShowWaitbar
1190        delete(wb_h)
1191  end
1192 
1193end
[2]1194
1195% Remove singleton dimensions from kspace
1196kspace = squeeze(kspace);
1197
1198% Check if raw kspace should be returned
1199if Dat.ReturnRawKspace
1200  %% Delete waitbar
[36]1201  if Dat.ShowWaitbar && ishandle(wb_h)
1202        delete(wb_h)
1203  end
[2]1204  return
1205end
1206
[35]1207%% Support for RASER sequence ---------------------------
1208if isfield(procpar,'teType')
1209 
1210  if strcmpi(procpar.sing_sh,'y') && strcmpi(procpar.teType,'c')
1211       
[71]1212    % Separate reference scans from the data
1213    if isfield(procpar,'refscan') && strcmp(procpar.refscan,'y')
1214      kspace=permute(reshape(kspace,procpar.np/2,procpar.ne/2,2,[]),[1 2 4 3]);
1215      noise = kspace(:,:,:,1);
1216      kspace = kspace(:,:,:,2);
1217      % DC-correction
1218      dc_level = squeeze(mean(mean(noise)));
1219      for ii=1:size(kspace,3)
1220        kspace(:,:,ii)=kspace(:,:,ii)-dc_level(ii);
1221      end
1222    end
1223   
1224    if strcmpi(procpar.readType,'s')
1225      sw = procpar.sw;
1226      dwell = cumsum(ones(1,size(kspace,1))*(1/sw));
1227    else
1228      error('This feature has not been implemented yet!!!')
1229    end
1230    dwell = dwell*1000;
1231    %kspace = permute(kspace,[2 1 3]);
1232   
1233   
1234   
1235    % Phase correction
1236    dims = size(kspace);
1237    nI = size(kspace,3);
1238    nv = size(kspace,4);
1239    ne = size(kspace,2);
1240    np = size(kspace,1);
1241    g = 42.58;
1242    G = procpar.gvox2;
1243    Ds = procpar.vox2/100;
1244    pos2 = procpar.pos2/10;
1245    fudge = 0;
1246    fudge2 = 1;
[83]1247   
[71]1248    tt_dwell=repmat(dwell(:),1,ne);
1249    tt_ne = repmat((1:ne),length(dwell),1);
1250    tt_np = repmat((1:np)',1,ne);
1251   
1252    i=sqrt(-1);
1253    phi = (-2.*pi.*g.*G.*Ds.*tt_dwell.*(tt_ne./ne - 1/2 - pos2/Ds))+fudge.*tt_np;
1254    phi = repmat(phi,[1,1,size(kspace,3)]);
1255    kspace = abs(kspace).*exp(i*(angle(kspace)+phi));
1256   
1257    % Flip every other column
1258    sz(1)=size(kspace,1);
1259    sz(2)=size(kspace,2);
1260    sz(3)=size(kspace,3);
1261    sz(4)=size(kspace,4);
1262    kspace=reshape(kspace,sz(1),prod(sz(2:4)));
1263    kspace(:,1:2:end) = flipud(kspace(:,1:2:end));
1264    kspace = reshape(kspace,sz);
1265   
1266    %kspace = reshape(permute(kspace,[2 1 3]),sz(2),[],1);
1267    %kspace(:,1:2:end) = flipud(kspace(:,1:2:end));
1268    %kspace=permute(reshape(kspace,sz(2),[],sz(3)),[2 1 3]);
1269   
[35]1270  else
[71]1271    data = [];
1272    error('RASER sequence of this type has not been implemeted yet!')
[35]1273  end
1274 
1275  % Reshape into 4D matrix
1276  kspace = reshape(kspace,size(kspace,1),size(kspace,2),[],size(kspace,3));
1277 
[67]1278  % Reorient if requested
[75]1279  if Dat.OrientImages
[67]1280    kspace = flipdim(kspace,2);
1281  end
1282 
[36]1283  data = abs(fftshift(fft(fftshift(fft(kspace,[],3),3),[],1),1));
[35]1284 
1285  % Delete kspace if not returned
1286  if ~Dat.ReturnKSpace
[71]1287    kspace=[];
[35]1288  end
1289 
1290  return
1291 
1292end
1293
[103]1294%% Support for fat/water measurements ----------------------
1295if isfield(procpar,'seqfil') && strcmpi(procpar.seqfil,'ge3d_csi2')
1296 
1297  % Split kspace into fat and water (in 4th dimesion)
1298  kspace=reshape(permute(reshape(kspace,256,2,[]),[1 3 4 2]),256,128,[],2);
1299 
1300  % Fourier transform data
1301  if any(Dat.ZeroPadding==[1 2])
1302    data_sz = [procpar.np/2,procpar.nf,procpar.nv2,2];
1303    data = zeros(data_sz,class(kspace));
1304    data(:,:,:,1) = abs(fftshift(fftn(kspace(:,:,:,1),data_sz(1:3))));
1305    data(:,:,:,2) = abs(fftshift(fftn(kspace(:,:,:,2),data_sz(1:3))));
1306  else
1307    data = zeros(size(kspace),class(kspace));
1308    data(:,:,:,1) = abs(fftshift(fftn(kspace(:,:,:,1))));
1309    data(:,:,:,2) = abs(fftshift(fftn(kspace(:,:,:,2))));
1310  end
1311 
1312  % Delete kspace if not returned
1313  if ~Dat.ReturnKSpace
1314    kspace=[];
1315  end
1316 
1317  return
1318end
[35]1319
[103]1320% Check the number of receivers (PI stuff)
[109]1321if isfield(procpar,'rcvrs') && ~isempty(procpar.rcvrs) && ...
1322    length(procpar.rcvrs{1})>1
[103]1323  % Multiple receivers used
[104]1324  if isfield(procpar,'apptype') && strcmp(procpar.apptype{1},'imEPI')
1325    % Store multiple receiver data in EPI measurements in 5th dimension
1326    % and calculate sum-of-squares image
1327    nRcv = length(find(procpar.rcvrs{1}=='y'));
[107]1328    nVols = size(kspace,3)/nRcv-1;
[108]1329    data = zeros(procpar.nv,procpar.np/2,procpar.ns,nVols+1,'single');
[109]1330    kssz=size(kspace);
1331    blksz = 500; % Process EPI data in 500 volume blocks
1332    nBlocks = ceil((size(kspace,3)/nRcv)/blksz);
1333    lnum = length(num2str(nBlocks));
[107]1334    lnumstr = num2str(lnum);
1335    bsl = lnum*2+1;
[109]1336    fprintf(1,'Processing data in blocks of %d volumes\n',blksz)
1337    fprintf(1,['Processing block...%0',lnumstr,'d/%0',lnumstr,'d'],1,nBlocks);
1338    for ii=1:nBlocks
[112]1339      fprintf(1,repmat('\b',1,bsl));
[113]1340      fprintf(1,['%0',lnumstr,'d/%0',lnumstr,'d'],ii,nBlocks);
[111]1341      tmp_data = [];
[109]1342      for kk=1:nRcv
1343        inds = [kk ((ii-1)*blksz*nRcv+kk):nRcv:min((nRcv*ii*blksz),kssz(3))];
1344        if ii==1
1345          % For first block, phase image is in inds twice
1346          inds = inds(2:end);
1347        end
[112]1348        tmp_kspace = l_ReconstructKspace(kspace(:,:,inds),procpar,Dat);
1349        tmp_data(:,:,:,:,kk) = fftshift(fftshift(fft(fft(tmp_kspace,[],1),[],2),1),2);
[106]1350      end
[109]1351      if ii==1
[113]1352        data(:,:,:,1:size(tmp_data,4)) = sqrt(sum(tmp_data.*conj(tmp_data),5));
[109]1353      elseif ii==nBlocks
[112]1354        data(:,:,:,((ii-1)*blksz+1):(nVols+1)) = sqrt(sum(tmp_data(:,:,:,2:end,:).*conj(tmp_data(:,:,:,2:end,:)),5));
[106]1355      else
[111]1356        data(:,:,:,((ii-1)*blksz+1):(ii*blksz)) = sqrt(sum(tmp_data(:,:,:,2:end,:).*conj(tmp_data(:,:,:,2:end,:)),5));
[106]1357      end
[103]1358    end
[107]1359    fprintf(1,'\n')
[104]1360   
[109]1361%     for kk=1:(size(kspace,3)/nRcv-1)
1362%       for ii=1:nRcv
1363%         tmp_kspace = l_ReconstructKspace(kspace(:,:,[ii kk*nRcv+ii]),procpar,Dat);
1364%         tmp_data(:,:,:,:,ii) = fftshift(fftshift(fft(fft(tmp_kspace,[],1),[],2),1),2);
1365%         
1366%         %tmp_kspace = l_ReconstructKspace(kspace(:,:,ii:nRcv:end),procpar,Dat);
1367%         %kspace2(:,:,:,:,ii)=tmp_kspace;
1368%       end
1369%       if kk==1
1370%         data = sqrt(mean(tmp_data.*conj(tmp_data),5));
1371%       else
1372%         data(:,:,:,kk+1) = sqrt(mean(tmp_data(:,:,:,2,:).*conj(tmp_data(:,:,:,2,:)),5));
1373%       end
1374%       fprintf(1,repmat('\b',1,bsl));
1375%       fprintf(1,['%0',lnumstr,'d/%0',lnumstr,'d'],kk,nVols);
1376%     end
1377%     fprintf(1,'\n')
1378%     %kspace = kspace2;
1379%     %data = fftshift(fftshift(fft(fft(kspace,[],1),[],2),1),2);
1380%     %data = sqrt(mean(data.*conj(data),5));
1381%     %kspace2=[];
1382   
[105]1383    % Remove reference image if requested
1384    if Dat.isEPIdata && Dat.RemoveEPIphaseIm
1385      data = data(:,:,:,2:end);
1386    end
1387   
[104]1388    if Dat.OrientImages && ~isempty(procpar) && ...
1389        isfield(procpar,'orient') && any(Dat.AcqType==[2 3 4])
1390      orient = procpar.orient{1};
1391      if any(strcmpi(orient,{'xyz','trans90','cor90','sag90'}))
1392        data = flipdim(aedes_rot3d(data,1,3),2);
1393      elseif strcmpi(orient,'oblique')
1394        data = flipdim(flipdim(data,1),2);
1395      else
1396        data = flipdim(flipdim(data,1),2);
1397      end
1398    end
1399   
1400  else
1401    nRcv = length(find(procpar.rcvrs{1}=='y'));
1402    data = [];
1403    kspace2 = [];
1404    for ii=1:nRcv
1405      tmp_kspace = l_ReconstructKspace(kspace(:,:,ii),procpar,Dat);
1406      kspace2(:,:,:,ii)=tmp_kspace;
1407      if Dat.ReturnFTData
1408        tmp_data = l_CalculateFFT(tmp_kspace,procpar,Dat);
1409        data(:,:,:,ii) = tmp_data;
1410      end
1411    end
1412    kspace = kspace2;
1413    kspace2=[];
[103]1414  end
1415else
1416  % Only one receiver
1417  kspace = l_ReconstructKspace(kspace,procpar,Dat);
1418  data = l_CalculateFFT(kspace,procpar,Dat);
1419end
1420
1421% Delete kspace if not returned
1422if ~Dat.ReturnKSpace
1423  kspace=[];
1424end
1425
1426%===============================================
1427% Reconstruct kspace for different sequences
1428%===============================================
1429function kspace=l_ReconstructKspace(kspace,procpar,Dat)
1430
1431
[2]1432%% Flip images for certain measurements
1433if Dat.FlipKspace~=0
1434  if ischar(Dat.FlipInd)
1435    if strcmpi(Dat.FlipInd,'all')
1436      flipind = 1:size(kspace,3);
1437    elseif strcmpi(Dat.FlipInd,'alt')
1438      flipind = 2:2:size(kspace,3);
1439    end
1440  else
1441    flipind = Dat.FlipInd;
1442  end
1443 
1444  for ii=flipind
1445    if Dat.FlipKspace==1
1446      kspace(:,:,ii)=fliplr(kspace(:,:,ii));
1447    elseif Dat.FlipKspace==2
1448      kspace(:,:,ii)=flipud(kspace(:,:,ii));
1449    else
1450      kspace(:,:,ii)=flipud(fliplr(kspace(:,:,ii)));
1451    end
1452  end
1453end
1454
1455% Handle arrayed and RARE sequences
[103]1456if Dat.isAcqArrayed && Dat.AcqType~=1 && Dat.Sorting && ~Dat.isEPIdata
1457  %if ~strcmpi(procpar.seqcon(2:3),'cc') && ( isempty(Dat.phasetable) | ...
[2]1458  %        isfield(procpar,'flash_converted') )
[103]1459  if (( isempty(Dat.phasetable) && ~strcmpi(procpar.seqcon(2:3),'sc') ) && ...
1460      ~(strcmpi(procpar.seqcon(2:3),'cc') && Dat.ArrayLength==size(kspace,3))) || ...
[81]1461      isfield(procpar,'flash_converted')
[2]1462                                 
1463    % Sort uncompressed arrayed data
[103]1464    ks_order = 1:procpar.nv*Dat.ArrayLength;
[2]1465    tmp = 0:procpar.nv:(procpar.ne-1)*procpar.nv;
[103]1466    tmp=repmat(tmp,procpar.nv*Dat.ArrayLength,1);
1467    ks_order = reshape(ks_order,Dat.ArrayLength,procpar.nv).';
[2]1468    ks_order = ks_order(:);
1469    ks_order = repmat(ks_order,1,procpar.ne);
1470    ks_order = ks_order+tmp;
1471    ks_order = ks_order.';
1472   
1473    if procpar.ns==1
1474      kspace=kspace(:,ks_order);
1475    else
1476      kspace = kspace(:,ks_order,:);
1477    end
1478   
1479    % Reshape into 3D matrix
[103]1480    kspace=reshape(kspace,[size(kspace,1) procpar.nv Dat.ArrayLength* ...
[2]1481                        procpar.ns]);
1482  else
1483    %% Sort RARE type data
[81]1484    if UsePhaseTable && ~isempty(Dat.phasetable)
[93]1485      %Dat.phasetable = Dat.phasetable';
[103]1486      if Dat.isAcqArrayed && Dat.ArrayLength>1 && strcmpi(procpar.seqcon(2:3),'cs')
1487        kspace = permute(reshape(reshape(kspace,size(kspace,1),[]),size(kspace,1),Dat.ArrayLength,[]),[1 3 2]);
[95]1488      else
1489        Dat.phasetable = Dat.phasetable.';
[93]1490      end
[2]1491      kspace(:,Dat.phasetable(:),:) = kspace;
1492    end
1493  end
1494elseif Dat.isEPIdata
[71]1495  %% Support for EPI-measurements
[2]1496 
[28]1497 
[71]1498  % EPI data is measured with old VNMR
1499  if isfield(procpar,'readres') && isfield(procpar,'phaseres')
1500   
1501    % Number of slices
1502    tmp_ns=length(procpar.pss);
1503   
1504    if isfield(procpar,'navecho') && strcmpi(procpar.navecho{1},'y')
1505      tmp_nv = procpar.nv-procpar.nseg;
1506    else
1507      tmp_nv = procpar.nv;
1508    end
1509    kspace = reshape(kspace,[size(kspace,1) ...
1510      size(kspace,2)/tmp_nv tmp_nv]);
1511    kspace = permute(kspace,[1 3 2]);
1512   
1513    % Reshape to 4D matrix
1514    kspace = reshape(kspace,[size(kspace,1) size(kspace,2) ...
1515      tmp_ns size(kspace,3)/tmp_ns]);
1516   
1517   
1518  elseif isfield(procpar,'apptype') && strcmp(procpar.apptype{1},'imEPI')
1519    % If EPI data is measured with new VNMRj system
1520   
1521    % Number of slices
1522    ns = length(procpar.pss);
1523   
1524    % Reshape kspace to 4D matrix
[99]1525    if isfield(procpar,'fract_ky') && procpar.fract_ky~=procpar.nv/2
1526      kspace = reshape(kspace,procpar.np/2,procpar.nv/2+procpar.fract_ky,...
1527        ns,[]);
1528      kspace(procpar.np/2,procpar.nv,1)=0;
1529    else
1530      kspace = reshape(kspace,procpar.np/2,procpar.nv,...
1531        ns,[]);
1532    end
[71]1533   
1534    % Flip even kspace lines
[84]1535    if ~Dat.FastDataRead
1536      for tt=2:2:size(kspace,2)
1537        kspace(:,tt,:,:) = flipdim(kspace(:,tt,:,:),1);
1538      end
1539    else
1540      kspace(:,2:2:end,:,:) = flipdim(kspace(:,2:2:end,:,:),1);
1541    end
[71]1542   
[84]1543   
[71]1544    % Sort centric measurements
1545    if isfield(procpar,'ky_order') && strcmpi(procpar.ky_order,'c')
1546      kspace(:,Dat.phasetable(:),:,:)=kspace;
1547    end
1548    %kspace = flipdim(kspace,1);
1549   
1550    % Get the reference image(s)
1551    ref_im = kspace(:,:,:,1);
1552   
1553    % Do phase correction.
1554    phase_e = exp(-sqrt(-1)*angle(fft(ref_im,[],1)));
1555    for kk=2:size(kspace,4)
1556      kspace(:,:,:,kk) = ifft(fft(kspace(:,:,:,kk),[],1).*phase_e,[],1);
1557    end
[38]1558  end
[2]1559 
1560else
1561  % This section contains various "chewing gum and ironwire" type
1562  % patches that hopefully work...
1563 
[103]1564  if strcmp(procpar.seqcon,'nncnn')
[82]1565    kspace = permute(kspace,[1 3 2]);
[103]1566  elseif strcmp(procpar.seqcon,'nccnn') && length(size(kspace))==2 && ...
1567      procpar.ns>=1 && Dat.AcqType~=1
[2]1568    if ~isempty(Dat.phasetable)
[82]1569      kssz = size(kspace);
1570      phsz = size(Dat.phasetable);
1571      kspace=permute(reshape(kspace,procpar.np/2,...
1572        phsz(2),...
1573        kssz(2)/phsz(2)),[1 3 2]);
1574      kspace = permute(reshape(kspace,...
1575        procpar.np/2,procpar.ns,kssz(2)/procpar.ns),[1 3 2]);
1576      if Dat.Sorting
1577        kspace(:,Dat.phasetable(:),:)=kspace;
1578      end
1579    else
1580      kspace = reshape(kspace,...
1581        [procpar.np/2 procpar.ns ...
1582        size(kspace,2)/procpar.ns]);
1583      kspace=permute(kspace,[1 3 2]);
1584    end
1585   
[103]1586  elseif strcmp(procpar.seqcon,'nscsn') && length(size(kspace))==3 && ...
1587          Dat.AcqType~=1
[23]1588        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1589        % Support for 3D fast spin-echo
1590        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1591        if ~isempty(Dat.phasetable)
1592          for ii=1:size(kspace,3)
1593                tmp = kspace(:,:,ii);
1594                kssz = size(tmp);
1595                phsz = size(Dat.phasetable);
1596                tmp=permute(reshape(tmp,procpar.np/2,...
1597                  phsz(2),...
1598                  kssz(2)/phsz(2)),[1 3 2]);
1599                tmp = permute(reshape(tmp,...
1600                  procpar.np/2,procpar.ns,kssz(2)/procpar.ns),[1 3 2]);
1601                if Dat.Sorting
1602                  tmp(:,Dat.phasetable(:),:)=tmp;
1603                end
1604                kspace(:,:,ii)=tmp;
1605          end
1606        end
1607       
1608       
[103]1609  elseif Dat.AcqType~=1 && isfield(procpar,'nv')
[2]1610    if length(size(kspace))==2 && ...
[21]1611              ( size(kspace,1)~=(procpar.np/2) || size(kspace,2)~=procpar.nv )
[2]1612      %% Reshape the kspace to the appropriate size
1613      kspace=reshape(kspace,[procpar.np/2 procpar.nv size(kspace,2)/ ...
1614                          procpar.nv]);
[89]1615    elseif length(size(kspace))==3
1616      kspace = reshape(kspace,procpar.np/2,procpar.nv,[]);
[94]1617      if Dat.Sorting && ~isempty(Dat.phasetable)
[89]1618        kspace(:,Dat.phasetable(:),:) = kspace;
1619      end
[2]1620    end
1621  end
1622 
1623 
1624  %%% Support for Teemu's ASE3D-data
[103]1625  %if strcmpi(procpar.seqcon,'ncccn')
[2]1626  %  %% Reshape the kspace to the appropriate size
1627  %  kspace=reshape(kspace,[procpar.np/2 procpar.nv size(kspace,2)/procpar.nv]);
1628  %end
1629end
1630
[71]1631
[103]1632
1633%=========================================
1634% Fourier Transform Data
1635%=========================================
1636function data=l_CalculateFFT(kspace,procpar,Dat)
1637data=[];
1638
[2]1639% Return image/spectral data --------------------------------
1640if Dat.ReturnFTData
1641  %% Fourier transform spectral data
[103]1642  if Dat.AcqType==1
[80]1643        wb_h = aedes_wbar(0,'Fourier transforming spectral data');
[22]1644    %data=zeros(size(kspace),'single');
1645        data=kspace;
[2]1646    sz=size(kspace,2)*size(kspace,3);
1647    count=1;
1648    for kk=1:size(kspace,3)
1649      for ii=1:size(kspace,2)
1650        %% Update waitbar
1651        if Dat.ShowWaitbar
[80]1652          aedes_wbar(count/sz,...
[2]1653               wb_h,...
1654               {'Fourier transforming spectral data',...
1655                ['(Processing spectrum ' num2str(count) '/' num2str(sz) ')']})
[22]1656                end
1657        data(:,ii,kk) = abs(fftshift(fft(data(:,ii,kk))));
[2]1658        count=count+1;
1659      end
1660    end
1661 
1662  %% Fourier transform image data
1663  else
1664   
1665    %% Zeropadding auto
1666    if Dat.ZeroPadding==2
1667     
[71]1668      if Dat.isEPIdata && isfield(procpar,'readres') && isfield(procpar,'phaseres')
[2]1669       
1670        %% Determine the image size for EPI data for procpar "readres"
1671        %% and "phaseres" fields
1672        data_sz = [procpar.readres procpar.phaseres];
[71]1673        if isequal(data_sz,[size(kspace,1),size(kspace,2)])
1674          DoZeroPadding=false;
1675        else
1676          DoZeroPadding=true;
1677        end
1678        data_sz = [procpar.readres ...
1679          procpar.phaseres size(kspace,3) size(kspace,4)];
[2]1680      else
1681       
[71]1682        %% Check if zeropadding is necessary.
[2]1683        ks_sz_sorted = sort([size(kspace,1),size(kspace,2)]);
1684        fov_sz_sorted = sort([procpar.lro,procpar.lpe]);
1685        sliceRelativeDim = ks_sz_sorted(2)/ks_sz_sorted(1);
1686        FOVrelativeDim = fov_sz_sorted(2)/fov_sz_sorted(1);
1687        if FOVrelativeDim~=sliceRelativeDim
1688          ind=find([size(kspace,1),size(kspace,2)]==ks_sz_sorted(1));
1689          data_sz = size(kspace);
1690          data_sz(ind) = round((fov_sz_sorted(1)/fov_sz_sorted(2))*ks_sz_sorted(2));
1691          DoZeroPadding=true;
1692        else
1693          data_sz = size(kspace);
1694          DoZeroPadding=false;
1695        end
1696      end
1697     
[71]1698      %% Force zeropadding on. Force images to be square.
[2]1699    elseif Dat.ZeroPadding==1
1700      ks_sz_max = max(size(kspace,1),size(kspace,2));
1701      data_sz = size(kspace);
1702      data_sz(1:2)=ks_sz_max;
1703      DoZeroPadding=true;
1704     
[71]1705      %% Force zeropadding off
[2]1706    else
1707      data_sz = size(kspace);
1708      DoZeroPadding=false;
1709    end
1710   
1711    %% Fourier transform 2D and EPI image data
[103]1712    if Dat.AcqType==2 || Dat.isEPIdata
[2]1713      sz=size(kspace,3);
[71]1714     
1715      if DoZeroPadding
1716        data=zeros(data_sz,class(kspace));
1717        data(1:size(kspace,1),1:size(kspace,2),:,:)=kspace;
1718      else
1719        data=kspace;
1720      end
[84]1721      if ~Dat.ReturnKSpace
1722        kspace = [];
1723      end
[71]1724      if Dat.ShowWaitbar
[80]1725        [wb_h,txh]=aedes_calc_wait('Fourier transforming image data...');
[71]1726      end
[84]1727     
[71]1728      %data=permute(fftshift(fftshift(abs(fft(permute(fft(data),[2 1 3 4]))),1),2),[2 1 3 4]);
[84]1729      if ~Dat.FastDataRead
1730        for tt=1:size(data,4)
1731          data(:,:,:,tt)=fftshift(fftshift(abs(fft(fft(data(:,:,:,tt),[],1),[],2)),1),2);
1732        end
1733      else
1734        data=fftshift(fftshift(abs(fft(fft(data,[],1),[],2)),1),2);
1735      end
[2]1736    else
1737      %% Fourier transform 3D image data
1738      if Dat.ShowWaitbar
[80]1739        [wb_h,txh]=aedes_calc_wait('Fourier transforming 3D image data...');
[2]1740      end
1741     
1742      if DoZeroPadding
[23]1743        % Check zeropadding in the 3rd dimension if zeropadding is set to
1744        % "auto"
[71]1745        if Dat.ZeroPadding==2
1746          if isfield(procpar,'lpe2') && isfield(procpar,'lpe')
[103]1747            data_sz(3) = max(1,round((procpar.lpe2/procpar.lpe)*data_sz(2)*Dat.ArrayLength));
[71]1748          end
1749        end
[38]1750        data=zeros(data_sz,class(kspace));
[2]1751        data = abs(fftshift(fftn(kspace,data_sz)));
1752      else
[38]1753        data=zeros(data_sz,class(kspace));
[71]1754        data = abs(fftshift(fftn(kspace)));
1755      end
[2]1756    end
1757   
[75]1758    % Remove reference image if requested
1759    if Dat.isEPIdata && Dat.RemoveEPIphaseIm
1760      data = data(:,:,:,2:end);
1761    end
1762   
[71]1763    % Reorient images and remove the reference image if requested
[75]1764    if Dat.OrientImages && ~isempty(procpar) && ...
[103]1765        isfield(procpar,'orient') && any(Dat.AcqType==[2 3 4])
[75]1766      orient = procpar.orient{1};
1767      if any(strcmpi(orient,{'xyz','trans90','cor90','sag90'}))
[80]1768        data = flipdim(aedes_rot3d(data,1,3),2);
[75]1769      elseif strcmpi(orient,'oblique')
1770        data = flipdim(flipdim(data,1),2);
[71]1771      else
[75]1772        data = flipdim(flipdim(data,1),2);
[71]1773      end
1774    end
1775   
[75]1776   
[71]1777   
[2]1778% $$$   %% Fourier transform 4D image data
[103]1779% $$$   elseif Dat.AcqType==4
[2]1780% $$$     data = abs(fftshift(fftshift(fft2(kspace),2),1));
1781  end
[103]1782 
1783  %% Delete waitbar
1784  if Dat.ShowWaitbar && ishandle(wb_h)
1785    delete(wb_h)
1786  end
[2]1787end
1788
1789
1790
[103]1791
1792
[81]1793%========================================================
1794% A function for creating phasetables for fse and fsems
1795%========================================================
1796function phasetable=l_CreateFsemsPhaseTable(procpar)
[2]1797
[81]1798phasetable = [];
1799if ~isfield(procpar,'etl') || ~isfield(procpar,'kzero')
1800  return
1801end
1802etl = procpar.etl;
1803kzero = procpar.kzero;
1804nv = procpar.nv;
[2]1805
[81]1806t = (-nv/2+1):(nv/2);
1807t = t(:);
1808tt = flipud(t);
1809tt = tt(:);
1810
[82]1811phasetable = [reshape(t(1:nv/2),[],etl);...
1812  flipud(reshape(tt(1:nv/2),[],etl))];
[81]1813phasetable = circshift(fliplr(phasetable),[0 kzero-1]);
1814
1815
[2]1816%% - EOF - %%
[82]1817return
Note: See TracBrowser for help on using the repository browser.

Powered by Trac 1.0.9.Copyright © Juha-Pekka Niskanen 2008