% detect slice aquisition sequence for Siemens Allegra 3T Head Scanner
%
% Just for teaching purposes! Use at own risk! 
% Licence: Public Domain
%
fprintf('\n!!!This only works for feet -> head direction!!! \n')
fprintf('based on https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=ind03&L=spm&D=0&P=6446897\n')
%
if isempty(files)
    try
        [files, sts] = spm_select(inf,'*','Select Dicom Files');
    catch
        error('Error with spm_select. Did you set the path to spm8?')
    end
        if sts == 0 | size(files,1) == 0
        error('No files selected')
    end
end
for n=1:size(files,1)
    if iscell(files)
        file = files{n,:};
    else
        file = strtrim(files(n,:));
    end
    
    fid = fopen(file);
    tline = fgetl(fid);
    sliceno = 0;
    sliceorder = '';
    sequenz = '';
    while ischar(tline)
        if strfind(tline,'sSliceArray.lSize')
            pos = strfind(tline,'=');
            sliceno = str2num(strtrim(tline(pos+1:end)));
        elseif strfind(tline,'sSliceArray.ucMode')
            pos = strfind(tline,'=');
            sliceorder = strtrim(tline(pos+1:end));
        elseif strfind(tline,'tProtocolName')
            pos = strfind(tline,'=');
            sequenz = strtrim(tline(pos+1:end));
        end
        tline = fgetl(fid);
    end
    fprintf('\nfile %s :\n',file)
    fprintf('sequence type: %s\n',sequenz)
    if strcmpi(sliceorder,'0x1')
        %case '0x1' % ascending
        fprintf('slices = 1 : %d \n',sliceno)
    elseif strcmpi(sliceorder,'0x2')
        %case '0x2' % descending
        fprintf('slices = %d : -1 : 1 \n',sliceno)
    elseif strcmpi(sliceorder,'0x4')
        %case '0x4' % interleaved
        if mod(sliceno,2)
            %odd
            fprintf('slices = [ 1 : 2 : %d, 2 : 2 : %d ] \n',sliceno, sliceno-1)
        else
            % even
            fprintf('slices = [ 2 : 2 : %d, 1 : 2 : %d ] \n',sliceno, sliceno-1)
        end
        
    end
    try
        info = dicominfo(file);
        
        fprintf('TR = %f\n',info.RepetitionTime)
    catch
    end
    
    fclose(fid);
    
end
