% Lagdecomp is a function that returns the Laguerre gains based on the input 
% signal and the parameters
% A shapping is done in the input waveform assuming that this signal is the
% signal from the segment that collected charge.
%

function [Gains,InputSignal_hat] = lagdecomp(InputSignal)

%filter parameters
T=.1; p = .5
K = sqrt((1-p^2)*T);
DL=47;
n = [0 K];               %find the outputs of the laguerre polynomial
d = [1 -1*p];
u = dimpulse(n,d,DL); 
nt = [-p 1];
dt = [1 -p];

[a, b] = size(InputSignal');
%shapper for the signal that collects charge
Y=ones(a-4,b)-InputSignal(:,a+2-DL:a)';
Y=[zeros(1,b);Y];
I=size(Y);
%creates Y_hat
y_hat=zeros(I);

%Creates the Laguere base with par waveforms and the size set by DL
par=10
for i=1:par-1
 u = [u dlsim(nt,dt,u(:,i))]; 
end

%calculates  the inver os this matrix
invutuut=inv(u'*u)*u';

for i=1:I(1,2)
  %t are the Laguere vector of weights
  t(:,i)=invutuut*Y(:,i);
  %temporal rep of the function when going back from Laguere decomposition
  y_hat(:,i)=u*t(:,i);
end

%assign output signals
Gains = t;
InputSignal_hat =  y_hat;