function [EBSD_e_map, EBSD_r_map] = gtEBSDLoadMapEulerCSVFile(filename, axes_perm)
% function [EBSD_e_map, EBSD_r_map] = gtEBSDLoadMapEulerCSVFile(filename, axes_perm)
%   Axes permutation allows to easily deal with different reference
%   systems, like for instance:
%       DCT Axes <-> EBSD Axes ([x y z] <-> [x'y'z'])
%           x     =     -y'
%           y     =      z'
%           z     =     -x'
%   Translates to: axes_perm = [-2 3 -1]
%
%   NOTE: Only the Rodrigues vector map has the axes changed!
%

    c = tic();
    fprintf('Reading from file: "%s"..', filename);

    fid = fopen(filename);
    sizes = fscanf(fid, 'Width,%d\nHeight,%d\nX Position,Y Position,Eul 1,Eul 2,Eul 3\n')';
    input = fscanf(fid, '%d,%d,%f,%f,%f');
    fclose(fid);

    fprintf('\b\b, Done in %f seconds.\n', toc(c));
    c = tic();
    fprintf('Converting to Euler and Rodriguez maps..');

    xx = input(1:5:end)+1;
    yy = input(2:5:end)+1;
    ea1 = input(3:5:end);
    ea2 = input(4:5:end);
    ea3 = input(5:5:end);

    sizes = sizes([2 1]);
    EBSD_e_map = zeros([sizes 3], 'single');
    ii = sub2ind([sizes, 3], yy, xx, 1 * ones(size(xx)));
    EBSD_e_map(ii) = ea1;
    ii = sub2ind([sizes, 3], yy, xx, 2 * ones(size(xx)));
    EBSD_e_map(ii) = ea2;
    ii = sub2ind([sizes, 3], yy, xx, 3 * ones(size(xx)));
    EBSD_e_map(ii) = ea3;

    EBSD_e_map = EBSD_e_map * 180 / pi;

    dmvol_EBSD_e_map = permute(EBSD_e_map, [1 2 4 3]);
    [gvdm_EBSD_e_map, size_dmvol_EBSD_map] = gtDefDmvol2Gvdm(dmvol_EBSD_e_map);
    gvdm_EBSD_r_map = gtMathsEuler2Rod(gvdm_EBSD_e_map);
    dmvol_EBSD_r_map = gtDefGvdm2Dmvol(gvdm_EBSD_r_map, size_dmvol_EBSD_map);
    EBSD_r_map = reshape(dmvol_EBSD_r_map, [sizes 3]);

    EBSD_r_map = EBSD_r_map(:, :, abs(axes_perm));
    negative = axes_perm < 0;
    EBSD_r_map(:, :, negative) = - EBSD_r_map(:, :, negative);

    fprintf('\b\b, Done in %f seconds.\n', toc(c));
end
