% Theretical LORETA:
% 1- Referencia Promedio
% 2- Uso de la Matriz de Peso

function [Jt,lambda,reg_param,Gl]=InvTeo(Lcs,Kes,Volt,LambdaMax);
[Ne,Ng3]=size(Kes);
wn = wiiv(Kes,1);
spwn=spdiags(wn,0,Ng3,Ng3);

temp=((spwn*Lcs')*(Lcs*spwn))\Kes';
Nl=100;
reg_param=linspace(1e-8,LambdaMax,Nl);
for i=1:Nl
 disp(i)
 temp1=Kes*temp+(reg_param(i).^2).*eye(Ne);
 temp2=temp*pinv(temp1);
 P=(eye(Ne)-Kes*temp2);
 Gl(i)=Ne.*(P*Volt)'*(P*Volt)./((trace(P)).^2);
end
%semilogx(lambdas,Gl)
[vgl,im]=min(Gl); lambda=reg_param(im);
temp1=Kes*temp+(lambda.^2).*eye(Ne);
temp2=temp*pinv(temp1);
Jt=temp2*Volt;
