function y=odezva(a,x)

%% Definice odezvy
if ~exist('a','var')
    a=[1 2 5 8 10 9.5 9 8 7 6 5 4 3 2 1 0]; a=a/sum(a);
    a=[ 1 -1]; 
%     a=[1 -1 1 -1 1 -1 1 -1 1 -1]; 
%     a=randn(1,50)/sqrt(50);
end

%% Definice signalu
if ~exist('x','var')
%     x=-0.5+sign(sin(linspace(0,16*pi,500)))';
    x=-0.5+(sin(linspace(0,16*pi,500)))';
end
close all;

%% Graf
f=figure;
set(f,'units','centimeters');
s=2*[20 10.5];
set(f,'position',[1.5 1.2 s]);
set(f,'papersize',s);
set(f,'defaultAxesFontSize',12)
N=length(x);
t=(1:N)';

%% Programek
y=filter(a,1,[x;x]);
y=y(length(y)/2+1:end);
subplot(2,2,1)
plot(t,x,'linewidth',2 );
ylim([-2.1 2.1]);
title('Prenasena data')
legend('puvodni signal','poskozeny signal')
xlabel('Cas, arb. jedn.')
ylabel('Amplituda signalu')
waitforbuttonpress;

subplot(2,2,3);
b=zeros(size(a));
tt=0:length(b);
b(1)=1; plot(tt,[0 b],'linewidth',2,'marker','+');
hold on;
plot(tt,[0 a],'linewidth',2,'marker','+')
title('Odezvova funkce');
legend('impuls','odezva')
waitforbuttonpress;

subplot(2,2,1)
hold on
plot(t,y,'linewidth',2 );
legend('puvodni signal','poskozeny signal')
waitforbuttonpress;

subplot(2,2,4)
a2=zeros(size(x));
a2(1:length(a))=a;
A=fft(a2);
yyaxis left
plot(t,abs(A),'linewidth',2);
xlabel('''Cislo'' vlastniho vektoru')
ylabel('Velikost vlastniho cisla')
yyaxis right
plot(t,angle(A),'linewidth',2)
ylabel('Komplex. faze vl. cisla')
legend('Velikost vl. cisel (spektrum)','faze');
title('Spektrum odezvove funkce');
waitforbuttonpress;

subplot(2,2,2)
plot(t,y,'r','linewidth',2);
ylim([-2.1 2.1]);
legend('poskozeny signal')
xlabel('Cas, arb. jedn.')
ylabel('Amplituda signalu')
waitforbuttonpress;

subplot(2,2,2)
if ~sum(A==0)
    X=fft(y);
    X=X./A;
    x2=ifft(X);
    hold on;
    plot(t,x2,'g','linewidth',2)
    legend('poskozeny signal','rekonstruovany signal')
    title('Rekonstrukce pomoci inverzni odezvove funkce')
else
    defekt=sum(A==0);
    I=(A==0);
    A(I)=Inf;
    X=fft(y);
    X=X./A;
    x2=ifft(X);
    hold on;
    plot(t,x2,'g','linewidth',2)
    legend('poskozeny signal','rekonstruovany signal')
    title(['Singularni odezvova fun. Defekt = ' num2str(defekt) '. Pokus o rekonstrukci'])
end

