close all
clear variables

%Domain
DataL.inix = 0;
DataL.endx = 0.25;
DataL.nelem = 25;
%Physical
DataL.kappa = 1*1;
DataL.source = 1;
%Boundary conditions
%Dirichlet
DataL.FixLeft = 1; %0, do not fix it, 1: fix it
DataL.LeftValue = 0;
DataL.FixRight =0;
DataL.RightValue = 0.5;
%Neumann
DataL.FixFluxesLeft = 0;
DataL.LeftFluxes = 0;
DataL.FixFluxesRight = 1;
DataL.RightFluxes = 0;

%Domain2
DataR.inix = DataL.endx;
DataR.endx = 1;
DataR.nelem = 75;
%Physical
DataR.kappa = 1;
DataR.source = 1;
%Boundary conditions
%Dirichlet
DataR.FixLeft = 1; %0, do not fix it, 1: fix it
DataR.LeftValue = 0.25;
DataR.FixRight =1;
DataR.RightValue = 0;
%Neumann
DataR.FixFluxesLeft = 0;
DataR.LeftFluxes = 0;
DataR.FixFluxesRight = 0;
DataR.RightFluxes = 0;

% Dirichlet-Neumann
HeatProblemR = HP_Initialize(DataR);
HeatProblemL = HP_Initialize(DataL);
HeatProblemL.Solution.uRight = 0.5;
HeatProblemR.Solution.FluxesRight = 0;
u = 0.25;

while true
%Problem R
    DataR.LeftValue = HeatProblemL.Solution.uRight;
    Solution_old = HeatProblemL.Solution.uRight;
    
    HeatProblemR = HP_Initialize(DataR);
    HeatProblemR = HP_Build(HeatProblemR);
    HeatProblemR = HP_Solve(HeatProblemR);
    
%Problem L
    DataL.RightFluxes = -HeatProblemR.Solution.FluxesLeft;
    
    HeatProblemL = HP_Initialize(DataL);
    HeatProblemL = HP_Build(HeatProblemL);
    HeatProblemL = HP_Solve(HeatProblemL);
    u = [u, HeatProblemL.Solution.uRight];
if abs(HeatProblemL.Solution.uRight - Solution_old) < 1E-6
   break
end
if abs(HeatProblemL.Solution.uRight) > 1E10
    break
end


end
HP_Plot(HeatProblemL,1);
HP_Plot(HeatProblemR,1);

x = 1:length(u);

figure(2)
semilogy(x, abs(u-u(end)))
xlabel('Iteration')
ylabel('log(error)')
ylim([0, max(abs(u-u(end)))*1.2])

