function [CENTR,ORIENT,i]=CentrOrientGabson(directory,directory2,directory3,crop,end1,end2,from,answer)
%Function generates two mat files with CENTR and ORIENT
%witch are used to calculate MSD and angle of orientation
%For the calculation of centre of fiber and its orientation function uses
%gapsoned figures (bw figures corected by filling gaps with line)
%Additionally after function saves pictures with elipsoid and trajectory

% Look for images in directory
% BW images from result_gap
obrazek=dir([directory,end1]);
%Image raw to save 
obrazek3=dir([directory3,end2]);
%Creation of empty tables
 
CENTR=[];ORIENT=[];

for i=from:length(obrazek);
    %BW
    nazwa=obrazek(i).name;
    %RAW
    nazwa3=obrazek3(i).name;
    % Open image i
    pic=imread([directory,'\',nazwa]);
    pic3=imread([directory3,'\',nazwa3]);
    disp(sprintf('Progress: %d / %d',i,length(obrazek)));
    % Green part of image
    pic3=pic3(:,:,2);
    % Crop of image
    pic3 = imcrop(pic3,crop);
    BW=pic(:,:,1);
    BW = (BW==255);
    STATS = regionprops(BW, 'Centroid');
    STATS2 = regionprops(BW, 'Orientation');
    centroids = cat(1, STATS.Centroid);
    if isempty(centroids)
        disp('Warning, no fiber.')
    end
    CENTR = vertcat(CENTR,centroids);
    orientation = cat(1, STATS2.Orientation);
    ORIENT = vertcat(ORIENT,orientation);
    
    if answer == 1
        % Creation of vectors to produce elipsoid
        phi = linspace(0,2*pi,50);
        cosphi = cos(phi);
        sinphi = sin(phi);
        % Selection of fiber properties
        s = regionprops(BW, 'Orientation', 'MajorAxisLength', 'MinorAxisLength', 'Eccentricity', 'Centroid');
        % Selection of fiber centroid,  calculation of fiber orientation and
        % axis length
        xbar = s.Centroid(1);
        ybar = s.Centroid(2);
        a = s.MajorAxisLength/2;
        b = s.MinorAxisLength/2;
        theta = pi*s.Orientation/180;
        % Matrix of rotation
        R = [ cos(theta)   sin(theta)
             -sin(theta)   cos(theta)];
        % Creation of rotated elipsoid 
        xy = [a*cosphi; b*sinphi];
        xy = R*xy;
        x = xy(1,:) + xbar;
        y = xy(2,:) + ybar;

        % Save figure with elipsoid representation and path
        %iptsetpref('ImshowBorder','tight');
        h = figure('visible','off');
        imshow(pic3);
        %hold on;
        %plot(x,y,'r','LineWidth',0.2);
        hold on;
        plot(CENTR(:,1),CENTR(:,2),'b','LineWidth',0.2);

        filename = [directory2,'/',nazwa(1:end-3),'jpg'];
        saveas(h,filename);
        set(gcf,'PaperPosition',[0 0 10 10]);
        print('-djpeg','-r1200',filename);
        hold off;
    else
        %disp('Only CENTR and ORIENT tables');
    end
end

%SAVE DATA
filename_CENTR = [directory2,'/','CENTR.mat'];
filename_ORIENT = [directory2,'/','ORIENT.mat'];
save(filename_CENTR,'CENTR');
save(filename_ORIENT,'ORIENT');