close all
clear variables

%Domain 2
Data2.inix = 0.5;
Data2.endx = 1;
Data2.nelem = 50;
%Physical
Data2.kappa = 1;
Data2.source = 1;

%Domain 1
Data1.inix = 0;
Data1.endx = 0.5;
Data1.nelem = 50;
%Physical
Data1.kappa = 1;
Data1.source = 1;



%SUBDOMAIN 2
%Boundary conditions
%Dirichlet
Data2.FixLeft = 1;          %0, do not fix it, 1: fix it
Data2.LeftValue = 0;
Data2.FixRight =0;
Data2.RightValue= 0;
%Neumann
Data2.FixFluxesLeft = 0;
Data2.LeftFluxes = 0;
Data2.FixFluxesRight = 0;
Data2.RightFluxes = 25;

%SUBDOMAIN 1
%Boundary conditions
%Dirichlet
Data1.FixLeft = 1;          %0, do not fix it, 1: fix it
Data1.LeftValue = 0;
Data1.FixRight =0;
Data1.RightValue= 0;
%Neumann
Data1.FixFluxesLeft = 0;
Data1.LeftFluxes = 0;
Data1.FixFluxesRight = 1;
Data1.RightFluxes = 25;

w=0.1;
u1initial=0; u2initial=0; iter=1; uinitial=0;
tol=10e-6;
HeatProblem1.Solution.uRight=0;
HeatProblem2.Solution.uLeft=0;
error=1;
while error > tol
    u1RBefore=HeatProblem1.Solution.uRight;
    
    %SUBDOMAIN 1
    % %Initialize
    HeatProblem1 = HP_Initialize(Data1);
    %Build problem
    HeatProblem1 = HP_Build(HeatProblem1);
    %System solution
    HeatProblem1 = HP_Solve(HeatProblem1);
    
    u1RAfter = HeatProblem1.Solution.uRight; %Sol at the interface
    
    %Aitkin relaxation scheme
    if iter > 2
        w = (u1initial-u2initial) / (u1initial-u2initial + HeatProblem1.Solution.uRight - uinitial);
    end
    Data2.LeftValue = u2initial + w*(HeatProblem1.Solution.uRight - u2initial);
    u1initial = u2initial;
    u2initial = Data2.LeftValue;
    uinitial = HeatProblem1.Solution.uRight;
    
    %Subdomain 2
    
    u2LBefore=HeatProblem2.Solution.uLeft; %Previous sol at the interface (left)
    % %Initialize
    HeatProblem2 = HP_Initialize(Data2);
    % %Build problem
    HeatProblem2 = HP_Build(HeatProblem2);
    % %System solution
    HeatProblem2 = HP_Solve(HeatProblem2);
    
    u2LAfter=HeatProblem2.Solution.uLeft; %Current sol at the interface (left)
    
    %Update data for Subdomain 1
    Data1.RightFluxes = -HeatProblem2.Solution.FluxesLeft;
    
    
    error(iter,1) = abs(u2LBefore-u2LAfter);
    iter = iter + 1;
end


%Solve and plot
HP_Plot(HeatProblem1,1);
HP_Plot(HeatProblem2,1);

%Plot convergence rate
figure
plot(log(error));
xlabel('iterations')
ylabel('log(error)')