%
% Reading Tiff3D Image
% 
function dImg = readTiff3D(sFileName)

qoffset = getTiff3DParameters(sprintf('%s.t3c',sFileName),'qoffset=');
qscale  = getTiff3DParameters(sprintf('%s.t3c',sFileName),'qscale=');
qmode   = getTiff3DParameters(sprintf('%s.t3c',sFileName),'qmode=',1);

dRaw = double(imread(sprintf('%s.range.tif',sFileName)));
min(dRaw(:));
max(dRaw(:));

[h w] = size(dRaw);
dImg = zeros(h,w);

if strcmp('direct',qmode)
    disp('QMode = direct');
    for r=1:h
        for c=1:w
            dImg(r,c) = ((2^16)-dRaw(r,c));
        end;
    end;
elseif strcmp('linear',qmode)
    disp('QMode = linear');
    for r=1:h
        for c=1:w
            dImg(r,c) = (((2^16)-dRaw(r,c)) * (qscale/(2^16)) + qoffset);
        end;
    end;
else
    disp('QMode not implemented!');
end;

%
% Reading Tiff3D Parameters
% 
function coefficients = getTiff3DParameters(varargin)

fname = varargin{1};
sName = varargin{2};
isString = 0;
if nargin == 3
    isString = 1;
end;
fid = fopen(fname, 'r');
if fid ~= -1
    a = fread(fid, 1);
    i = 0;
    j = 0;
    while a ~= feof(fid)
        i = i+1;
        a = fread(fid,1);
        if (a==10) % Line feed
            j = j + 1;
            txt{j} = zeile;
            zeile = '';
            i = 0;
        else
            if a~= feof(fid)
                zeile(i) = char(a);
            end;
        end;
    end;
    fclose(fid);

    % search coeff
    [r c] = size(txt);
    for i=1:c
        pos = findstr(txt{i},sName);
        if pos==1
            txt{i} = strrep(txt{i},sName,' ');
            if isString == 0
                coeff = str2num(txt{i});
            else
                coeff = strtrim(txt{i});
            end;
        end;
    end;

    try
        coefficients = coeff;
    catch
        disp(sprintf('[getTiff3DParameters] No [%s]-Parameters found! Parameter = 0!',sName));
        coefficients = 0;
    end;
else
    disp('[getTiff3DParameters] File not found! Parameter = 0!');
    coefficients = 0;
end;
        