% Generation of GM Orthogonolization Waveforms 
clear;clc;close all
iplot = 1;
stmat = [1 1 0;1 -1 0;-1 1 1;1 1 1];% This is the set of sm(t) signals on page 343 of Proakis
stmat = [2 -1 -1 -1;-2 1 1 0;1 -1 1 -1;1 -2 -2 2];
% stmat = [1 1 0 0;0 0 1 1;-1 -1 0 0;0 0 -1 -1];
% stmat = [1 1 1 1 1 1;0.5 0.5 0.5 -0.5 -0.5 -0.5;0.5 0.5 -0.5 -0.5 0.5 0.5;0 0 0 0 0 0];
%stmat = [1 1 1 1;0.5 0.5 -0.5 -0.5;0.5 -0.5 0.5 -0.5;0 0 0 0];
%stmat = [1 1 1 1 1 1 1 1;1 1 1 1 -1 -1 -1 -1;1 1 -1 -1 1 1 -1 -1;1 -1 1 -1 1 -1 1 -1];
Tn = length(stmat(1,:));M = length(stmat(:,1));
Ep1 = stmat(1,:)*stmat(1,:)';
Fit1 = stmat(1,:)/sqrt(Ep1);
c21 = stmat(2,:)*Fit1';d2t = stmat(2,:) - c21*Fit1;
Ep2 = d2t*d2t';Fit2 = d2t/sqrt(Ep2);
Fitmat = [Fit1;Fit2];
for n = 3:M
    cnis = 0;
for i = 1:n - 1
    cni = stmat(n,:)*Fitmat(i,:)';
    cnis = cnis + cni*Fitmat(i,:);
end
dnt = stmat(n,:) - cnis;dnt(abs(dnt) <= 1e-12) = 0;
Epn = dnt*dnt';Epn(abs(Epn) <= 1e-12) = 0;
Fitn = dnt/sqrt(Epn);Fitn(isnan(Fitn)) = 0;
Fitmat = [Fitmat;Fitn];
end
Fitmat  
%%% Tests
CorrMatofFi =  Fitmat*Fitmat'  %%% Testing that the energy in psi functions is unity and they are orthogonal 
smncoeffs = stmat*Fitmat';
stmat = smncoeffs*Fitmat;
%Fitmat = [1 0 0;0 1 0;0 0 1;0 0 0];
smncoeffs = stmat*Fitmat';
% slen = sqrt(sum(smncoeffs'.^2))
%%%% Plotting waveforms
if iplot == 1
rep1 = 10;stmatrep = [];Fitmatrep = [];
for irepr = 1:length(stmat(:,1))
starr = [];Fitarr = [];
    for irepc = 1:length(stmat(1,:))
    st = ones(1,rep1)*stmat(irepr,irepc);starr = [starr st];Fit = ones(1,rep1)*Fitmat(irepr,irepc);Fitarr = [Fitarr Fit];
    end
    stmatrep = [stmatrep;starr];Fitmatrep = [Fitmatrep;Fitarr];
end
totmat = [stmatrep;Fitmatrep];
figure(1);for ip = 1:length(totmat(:,1))-0
subplot(2,4,ip);plot((0:length(totmat(1,:)) - 1)/rep1,totmat(ip,:),'LineWidth',3);
axis ([0 (length(totmat(ip,:)) - 1)/rep1 min(totmat(ip,:))*0.9-0.3 max(totmat(ip,:))*1.2+0.1]);set(gca,'FontSize',16)
xlabel(' \itt \rm\bf( time )','FontSize',16,'FontWeight','bold');
ylabel([' \its\rm\bf_' num2str(ip) '^w ( \itt \rm\bf)'],'FontSize',16,'FontWeight','bold');
if ip > length(stmatrep(:,1));ylabel([' \it\psi\rm\bf_' num2str(ip-4) '^w ( \itt \rm\bf)'],'FontSize',16,'FontWeight','bold');end;end
%if ip > length(stmatrep(:,1));ylabel([' \it\psi\rm\bf_' num2str(ip-4) ' ( \itt \rm\bf)'],'FontSize',16,'FontWeight','bold');end;end
set(gcf,'Color',[1 1 1]);set(gca,'FontSize',16);end