%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                           Write TIFF Output File                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% DESCRIPTION
% This script performs the following procedures
% 1.- Define the bits per sample to be used for the data.
% 2.- Define sample format and tags.
% 3.- Configure no compresion in the format.
% 4.- Write image to the specified path.

% Author: David Villacis
% Date: 26/10/2016
% Editor: Santeri Kaupinm?ki (06/01/2017)
% Institution: University of Helsinki - MODEMAT (EPN)
% Version: 1

function write_tif( img, img_file )
%WRITE_TIF Write 16bit TIFF image with no compression
%   Write double image matrix to TIFF 16bit file with no compression
%   WRITE_TIF(IMG,IMG_FILE)
%   Parameters:
%   - img: Image matrix to be stored.
%   - img_file: Filename and path where the image data will be stored

    img = uint16(img); % Convert data type
    BitsPerSample = 16;
    SampleFormat = 1;

    % Create a Tiff object
    t = Tiff(img_file,'w');

    tagstruct.ImageLength = size(img,1);
    tagstruct.ImageWidth = size(img,2);
    tagstruct.SamplesPerPixel = size(img,3);
    tagstruct.SampleFormat = SampleFormat;
    tagstruct.BitsPerSample = BitsPerSample;

    tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
    tagstruct.Compression = 1;
    tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
    tagstruct.Software = 'MATLAB';

    t.setTag(tagstruct);
    t.write(img);
    t.close()

end

