function subGUI4IFP(version,nr,basicfsz)

scrsz = get(0,'ScreenSize');
fig = figure(nr);
pause(.1);
set(fig,'Position',[1/6*scrsz(3:4) 4/5*scrsz(3) 1/2*scrsz(4)]);
set(fig,'Name',['FACPACK (Computation of inner and outer polytopes, version ',num2str(version,'%2.2f'), ')'],...
    'NumberTitle','off','MenuBar','none','Toolbar','none','color','white','Visible','off');

if ispc
%     basicfsz = 5;
    basichi = 0.05;
else
%     basicfsz = 6.5;
    basichi = 0.05;
end
basicfsz = basicfsz*scrsz(4)/1080;

Styles = {'bitstream charter';'clean';'Courier';'courier 10 pitch';'frank ruehl';'Helvetica';'Helvetica-Narrow';'itc bookman';'urw bookman l'};
sty = Styles{6};
bgc = 0.95*ones(3,1);
% lcs = [0 0 1;0 0.5 0;1 0 0;0 0.5 0.5;0.5 0 0.5;0.5 0.5 0];
lcs = [0 0.4470 0.7410; 0.8500 0.3250 0.0980; 0.9290 0.6940 0.1250; 0.4940 0.1840 0.5560; 0.4660 0.6740 0.1880; 0.3010 0.7450 0.9330];
LCS = [0.85 0.9 1; 0.995 0.8250 0.75; 1 0.9 0.75; 0.9 0.6 1; 0.7 1 0.5; 0.7 0.9 1];

% The title names
titles(1) = uicontrol('Style','text','String','U-space','HorizontalAlignment','center','Fontsize',3*basicfsz,'BackgroundColor','w',...
    'Units','normalized','FontName',sty,'Position',[0.27, 0.89, 0.3, basichi]);

titles(2) = uicontrol('Style','text','String','V-space','HorizontalAlignment','center','Fontsize',3*basicfsz,'BackgroundColor','w',...
    'Units','normalized','FontName',sty,'Position',[0.66, 0.89, 0.3, basichi]);

options(1) = uicontrol('Style','text','String','Noise level:','HorizontalAlignment','center','Fontsize',2*basicfsz,'BackgroundColor','w',...
    'Units','normalized','FontName',sty,'Position',[0.01, 0.52, 0.09, basichi]);

options(2) = uicontrol('Style','edit','String',' 0.02','HorizontalAlignment','right','Fontsize',2*basicfsz,...
    'Units','normalized','FontName',sty,'Position',[0.13, 0.52, 0.09, basichi]);

% The axes for the data, the NFM, the AFS and the transformed AFS
AxesU = axes('Fontsize',2*basicfsz,'Units','normalized','FontName',sty,'Position',[0.25, 0.1, 0.33, 0.75]);
plot(AxesU,1,0,'w');

AxesV = axes('Fontsize',2*basicfsz,'Units','normalized','FontName',sty,'Position',[0.65, 0.1, 0.33, 0.75]);
plot(AxesV,1,0,'w');


% The buttons with all UserData in emptybutton
emptybutton = uicontrol('Style','pushbutton','Position',[0.02, 0.8, 0.2, basichi],'Visible','off','Callback',{@emptybutton_CB});


Button(3) = uicontrol('Style','pushbutton','UserData',0,'String','Save Results','HorizontalAlignment','center','Fontsize',2*basicfsz,...
    'Units','normalized','FontName',sty,'Position',[0.02, 0.4, 0.2, basichi],'Enable','off',...
    'Callback', {@buttonsave, emptybutton});

Button(2) = uicontrol('Style','pushbutton','UserData',0,'String','Compute polytopes','HorizontalAlignment','center','Fontsize',2*basicfsz,...
    'Units','normalized','FontName',sty,'Position',[0.02, 0.46, 0.2, basichi],'Enable','off',...
    'Callback', {@buttonIFP, emptybutton, Button, options, AxesU, AxesV, lcs});

% The Radio-buttons for two or three component systems
Radiogroup(1) = uibuttongroup('visible','on','Position',[0.02, 0.69, .2, .1],'BackgroundColor',bgc);
    
ufou = uicontrol('Style','radiobutton','String',' 4 components','Units','normalized','Position',[0.01, 0.15, 0.98, 0.25],...
    'Fontsize',2*basicfsz,'FontName',sty,'parent',Radiogroup(1),'HandleVisibility','off','Value',0,'BackgroundColor',bgc);

uthr = uicontrol('Style','radiobutton','String',' 3 components','Units','normalized','Position',[0.01, 0.6, 0.98, 0.25],...
    'Fontsize',2*basicfsz,'FontName',sty,'parent',Radiogroup(1),'HandleVisibility','off','Value',0,'BackgroundColor',bgc);

set(ufou,'Value',0);
set(uthr,'Value',0);
set(Radiogroup(1),'SelectionChangeFcn', {@buttonselect34, emptybutton, Button, AxesU, AxesV, ufou, uthr});

Radiogroup(2) = uibuttongroup('visible','on','Position',[0.02, 0.58, .2, .1],'BackgroundColor',bgc);
    
unoi = uicontrol('Style','radiobutton','String',' with noise','Units','normalized','Position',[0.01, 0.15, 0.98, 0.25],...
    'Fontsize',2*basicfsz,'FontName',sty,'parent',Radiogroup(2),'HandleVisibility','off','Value',0,'BackgroundColor',bgc);

umod = uicontrol('Style','radiobutton','String',' without noise','Units','normalized','Position',[0.01, 0.6, 0.98, 0.25],...
    'Fontsize',2*basicfsz,'FontName',sty,'parent',Radiogroup(2),'HandleVisibility','off','Value',0,'BackgroundColor',bgc);

set(umod,'Value',0);
set(unoi,'Value',0);
set(Radiogroup(2),'SelectionChangeFcn', {@buttonselectnoise, emptybutton, Button, AxesU, AxesV, umod, unoi});

set(Button(2),'Callback', {@buttonIFP, emptybutton, Button, options, AxesU, AxesV, lcs});

Button(1) = uicontrol('Style','pushbutton','UserData',0,'String','Load','HorizontalAlignment','center','Fontsize',2*basicfsz,...
    'Units','normalized','FontName',sty,'Position',get(emptybutton,'Position'),...
    'TooltipString', sprintf('Load mat-file containing data matrix "D" (spectra  x channels)\nand channels-vector "x".'),...
    'Callback',{@buttonload, emptybutton, Button, AxesU, AxesV, ufou, uthr, umod, unoi});

set(gcf,'WindowButtonDownFcn', {@fcnbd, fig, emptybutton, Button, AxesU, AxesV})

set(fig,'Visible','on');

function emptybutton_CB(hObject, eventdata)
data.ismatrix = 0;
data.s = [];
data.noise = [];
set(hObject,'UserData',data);

function buttonIFP(hObject, eventdata, Empty_Button, Buttons, options, AxesU, AxesV, lcs)
data = get(Empty_Button,'UserData');

if data.noise == 0
    if data.s == 3
        [FPS, IPS, FPC, IPC] = fpips3(data.U, data.S, data.V);
    elseif data.s == 4
        [FPS, IPS, FPC, IPC] = fpips4(data.U, data.S, data.V);
    end
elseif data.noise == 1
    if data.s == 3
        [FPC, FPS, essU, essV] = fpess4noise(data.V, data.U*data.S, 3, 1.E-5, -str2num(get(options(2),'String')), 1000);
        FPC = FPC([1:end 1],:);
        FPS = FPS([1:end 1],:);
        IPS = [];
        for i=1:size(FPC,1)-1
            if min(FPC(i,:) == [0 0])<1 && min(FPC(i+1,:) == [0 0])<1
                IPS(end+1,:) = (FPC(i:i+1,:)\[-1;-1])';
            end
        end
        if size(IPS,1)>1
            K = convhull(IPS(:,1),IPS(:,2));
            IPS = IPS(K,:);
        end
        
        IPC = [];
        for i=1:size(FPS,1)-1
            if min(FPS(i,:) == [0 0])<1 && min(FPS(i+1,:) == [0 0])<1
                IPC(end+1,:) = (FPS(i:i+1,:)\[-1;-1])';
            end
        end
        if size(IPC,1)>1
            K = convhull(IPC(:,1),IPC(:,2));
            IPC = IPC(K,:);
        end
    elseif data.s == 4
        [FPC, FPS, essU, essV] = fpess4noise(data.V, data.U*data.S, 4, 1.E-4, -str2num(get(options(2),'String')), 25000);
        
        kfpc = convhull(FPC);
        kfps = convhull(FPS);
        
        IPC = [];
        for i=1:size(kfps,1)
            IPC(end+1,:) = (FPS(kfps(i,:),:)\[-1;-1;-1])';
        end
        
        IPS = [];
        for i=1:size(kfpc,1)
            IPS(end+1,:) = (FPC(kfpc(i,:),:)\[-1;-1;-1])';
        end
    end
end

data.FPS = FPS;
data.FPC = FPC;
data.IPS = IPS;
data.IPC = IPC;

onoffButton(Buttons,3,[]);
if data.s == 3
    plotIFP3(FPS, IPS, FPC, IPC, lcs, AxesU, AxesV)
elseif data.s == 4
    plotIFP4(FPS, IPS, FPC, IPC, lcs, AxesU, AxesV)
end

set(Empty_Button,'UserData',data);

function [FPS, IPS, FPC, IPC] = fpips3(U, S, V)
a = diag(1./U(:,1)/S(1,1))*U(:,2:3)*S(2:3,2:3);
b = diag(1./V(:,1))*V(:,2:3);

cips = convhull(a);
cipc = convhull(b);

IPS = a(cips,:);
IPC = b(cipc,:);

FPS = [];
m = size(IPC,1);
for i=1:m-1
    X = [IPC(i,:); IPC(i+1,:)];
    FPS(end+1,:) = X\[-1;-1];
end
FPS(end+1,:) = FPS(1,:);

FPC = [];
m = size(IPS,1);
for i=1:m-1
    X = [IPS(i,:); IPS(i+1,:)];
    FPC(end+1,:) = X\[-1;-1];
end
FPC(end+1,:) = FPC(1,:);

function [FPS, IPS, FPC, IPC] = fpips4(U, S, V)
a = diag(1./U(:,1)/S(1,1))*U(:,2:4)*S(2:4,2:4);
b = diag(1./V(:,1))*V(:,2:4);

kips = convhull(a);
kipc = convhull(b);
IPS = a(kips,:);
IPC = b(kipc,:);

FPS = [];
m = size(kipc,1);
for i=1:m
    X = b(kipc(i,:),:);
    FPS(end+1,:) = X\[-1;-1;-1];
end

FPC = [];
m = size(kips,1);
for i=1:m
    X = a(kips(i,:),:);
    FPC(end+1,:) = X\[-1;-1;-1];
end


function plotIFP3(FPS, IPS, FPC, IPC, lcs, AxesU, AxesV)
plot(AxesV,FPS(:,1), FPS(:,2),'color',lcs(1,:), 'linewidth', 1)
hold(AxesV,'on')
if size(IPS,1)>1
    xls = [min(min(FPS(:,1)),min(IPS(:,1))) max(max(FPS(:,1)),max(IPS(:,1)))];
    yls = [min(min(FPS(:,2)),min(IPS(:,2))) max(max(FPS(:,2)),max(IPS(:,2)))];
    plot(AxesV,IPS(:,1), IPS(:,2),'color',lcs(2,:), 'linewidth', 1)
    l = legend(AxesV,'Outer Polygon','Inner Polygon');
else
    xls = [min(FPS(:,1)) max(FPS(:,1))];
    yls = [min(FPS(:,2)) max(FPS(:,2))];
    l = legend(AxesV,'Outer Polygon');
end
hold(AxesV,'off')
set(AxesV,'xlim',1.05*xls,'ylim',1.05*yls,'Fontsize',15)
l = legend(AxesV,'Outer Polygon','Inner Polygon');
set(l,'Fontsize',15);

plot(AxesU,FPC(:,1), FPC(:,2),'color',lcs(1,:), 'linewidth', 1)
hold(AxesU,'on')
if size(IPC,1)>1
    xlc = [min(min(FPC(:,1)),min(IPC(:,1))) max(max(FPC(:,1)),max(IPC(:,1)))];
    ylc = [min(min(FPC(:,2)),min(IPC(:,2))) max(max(FPC(:,2)),max(IPC(:,2)))];
    plot(AxesU,IPC(:,1), IPC(:,2),'color',lcs(2,:), 'linewidth', 1)
    l = legend(AxesU,'Outer Polygon','Inner Polygon');
else
    xlc = [min(FPC(:,1)) max(FPC(:,1))];
    ylc = [min(FPC(:,2)) max(FPC(:,2))];
    l = legend(AxesU,'Outer Polygon');
end
hold(AxesU,'off')
set(AxesU,'xlim',1.05*xlc,'ylim',1.05*ylc,'Fontsize',15)
set(l,'Fontsize',15);


function plotIFP4(FPS, IPS, FPC, IPC, lcs, AxesU, AxesV)
xls = [min(FPS(:,1)) max(FPS(:,1))];
yls = [min(FPS(:,2)) max(FPS(:,2))];
zls = [min(FPS(:,3)) max(FPS(:,3))];

kips = convhull(IPS);
kipc = convhull(IPC);

kfpc = convhull(FPC);
kfps = convhull(FPS);

trisurf(kfps, FPS(:,1), FPS(:,2), FPS(:,3), 'facecolor', lcs(1,:), 'facealpha',0.2,'Parent',AxesV);
hold(AxesV,'on');
trisurf(kips, IPS(:,1), IPS(:,2), IPS(:,3), 'facecolor', lcs(2,:), 'facealpha',0.7,'Parent',AxesV);
hold(AxesV,'off');
l = legend(AxesV,'Outer Polytope','Inner Polytope');
set(AxesV,'xlim',1.05*xls,'ylim',1.05*yls,'zlim',1.05*zls,'Fontsize',15)

xlc = [min(FPC(:,1)) max(FPC(:,1))];
ylc = [min(FPC(:,2)) max(FPC(:,2))];
zlc = [min(FPC(:,3)) max(FPC(:,3))];
trisurf(kfpc, FPC(:,1), FPC(:,2), FPC(:,3), 'facecolor', lcs(1,:), 'facealpha',0.2,'Parent',AxesU);
hold(AxesU,'on');
trisurf(kipc, IPC(:,1), IPC(:,2), IPC(:,3), 'facecolor', lcs(2,:), 'facealpha',0.7,'Parent',AxesU);
hold(AxesU,'off');
l = legend(AxesU,'Outer Polytope','Inner Polytope');
set(AxesU,'xlim',1.05*xlc,'ylim',1.05*ylc,'zlim',1.05*zlc,'Fontsize',15)


function buttonload(hObject, eventdata, Empty_Button, Buttons, AxesU, AxesV, ufou, uthr, umod, unoi)
data = get(Empty_Button,'UserData');
data.ismatrix = 0;    
set(ufou,'Value',0);
set(uthr,'Value',0);
set(umod,'Value',0);
set(unoi,'Value',0);
onoffButton(Buttons,[],2:3);

if ispc
    dlm = '\';
else
    dlm = '/';
end

if isfield(data,'PathName') == 0
    actpwd = pwd;
    if strcmp(actpwd(end-9:end), 'subfcnsAFS') == 1
        data.PathName = actpwd(1:end-10);
    else
        data.PathName = [pwd, dlm];
    end
end

actpwd = pwd;
cd(data.PathName);
[FileName,PathName,FilterIndex] = uigetfile('*.mat','Select .mat file including the data Matrix D');
cd(actpwd);

if FilterIndex == 0
    set(hObject,'UserData',data);
    
    plot(AxesU,1,0,'w');
    plot(AxesV,1,0,'w');
    set(Empty_Button,'UserData',data);
    return
end
data.FileName = FileName;
data.PathName = PathName;

load([PathName FileName]);
if ~exist('D')
    set(Empty_Button,'UserData',data);
    return
else
    k = size(D,1);
    n = size(D,2);
    if min(k,n) < 2
        onoffButton(Buttons,[],2:3);
        set(Empty_Button,'UserData',data);
        return
    end
    
    if exist('t')
        data.t = t;
    elseif (~exist('t')) && (exist('T')) && (max(size(T)) == k) && (min(size(T)) == 1)
        data.t = T;
    elseif (~exist('t')) || (max(size(t)) ~= k) || (min(size(t)) ~= 1)
        data.t = 0:k-1;
    end
    
    if exist('x')
        data.x = x;
    elseif (~exist('x')) && (exist('X')) && (max(size(X)) == n) && (min(size(X)) == 1)
        data.x = X;
    elseif (~exist('x')) || (max(size(x)) ~= n) || (min(size(x)) ~= 1)
        data.x = 0:n-1;
    end
    
    [U,S,V] = svds(D,4);
    for i=1:size(U,2)
        if -min(V(:,i)) > max(V(:,i))
            U(:,i) = -U(:,i);
            V(:,i) = -V(:,i);
        end
    end
    
    data.U = U;
    data.S = S;
    data.V = V;
    data.D = D;
    data.ismatrix = 1;
    
    onoffButton(Buttons,[],2:3);
end

plot(AxesU,1,0,'w');
plot(AxesV,0,0,'w');

set(Empty_Button,'UserData',data);


function buttonselect34(hObject, eventdata, Empty_Button, Buttons, AxesU, AxesV, ufou, uthr)
data = get(Empty_Button,'UserData');

if get(ufou,'Value') == 1
    data.s = 4;
elseif get(uthr,'Value') == 1
    data.s = 3;
end

plot(AxesU,1,0,'w');
plot(AxesV,0,0,'w');

if (isfield(data,'ismatrix') == 1) && (data.ismatrix == 1) && (isfield(data,'noise') == 1) && (data.noise == 0 || data.noise == 1)
    onoffButton(Buttons,2,3);
end
set(Empty_Button,'UserData',data);

function buttonselectnoise(hObject, eventdata, Empty_Button, Buttons, AxesU, AxesV, umod, unoi)
data = get(Empty_Button,'UserData');

if get(unoi,'Value') == 1
    data.noise = 1;
elseif get(umod,'Value') == 1
    data.noise = 0;
end

plot(AxesU,1,0,'w');
plot(AxesV,0,0,'w');

if (isfield(data,'ismatrix') == 1) && (data.ismatrix == 1) && (isfield(data,'s') == 1) && (data.s == 3 || data.s == 4)
    onoffButton(Buttons,2,3);
end
set(Empty_Button,'UserData',data);

function fcnbd(hObject, eventdata, parentfig, Empty_Button, Buttons, AxesU, AxesV)
data = get(Empty_Button,'UserData');
SelTyp = get(gcbf, 'SelectionType');

if strcmp(SelTyp,'alt') == 1
    pt = get(hObject, 'CurrentPoint');
    sz = get(hObject, 'Position');
    x = pt(1,1:2)./sz(1,3:4);
    
    posU = get(AxesU, 'Position');
    posV = get(AxesV, 'Position');
    
    if (posU(1) < x(1)) && (x(1) < posU(1)+posU(3)) && (posU(2) < x(2)) && (x(2) < posU(2)+posU(4))
        tmpc = figure;
        copyobj(AxesU,tmpc);
        tmpa = get(tmpc,'CurrentAxes');
        set(tmpa,'position',[0.15 0.15 0.75 0.75]);
        title(tmpa, 'U-space');
        xlabel(tmpa, '$T_{1,2}$','interpreter','latex');
        ylabel(tmpa, '$T_{1,3}$','interpreter','latex');
        
    elseif (posV(1) < x(1)) && (x(1) < posV(1)+posV(3)) && (posV(2) < x(2)) && (x(2) < posV(2)+posV(4))
        tmpc = figure;
        copyobj(AxesV,tmpc);
        tmpa = get(tmpc,'CurrentAxes');
        set(tmpa,'position',[0.15 0.15 0.75 0.75]);
        title(tmpa, 'V-space');
        xlabel(tmpa, '$(T^{-1})_{1,2}$','interpreter','latex');
        ylabel(tmpa, '$(T^{-1})_{1,3}$','interpreter','latex');
        
    end
end

function buttonsave(hObject, eventdata, Empty_Button)
data = get(Empty_Button,'UserData');
if isfield(data,'FPS')*isfield(data,'FPC')*isfield(data,'IPS')*isfield(data,'IPC') == 0
    return;
end
U = data.U; 
S = data.S;
V = data.V;
D = data.D;
if isfield(data,'x')
    x = data.x;
else
    x = 1:size(data.D,2);
end
if isfield(data,'t')
    t = data.t;
else
    t = 1:size(data.D,1);
end
FPS = data.FPS;
FPC = data.FPC;
IPS = data.IPS;
IPC = data.IPC;

uisave({'U','S','V','D','x','t','FPS','FPC','IPS','IPC'},[data.PathName,'FPIP_',data.FileName]);
