function [x,fx, phasespline]=phaseapprox(varargin)
%approximate phase data by smoothing spline with parameter splinrparam

%% Костыль, чтобы работало не только со структорой на входе, но и с двумя массивами (x, y)

switch nargin
case 2;
phasedata = varargin(1);
phasedata = [phasedata{:}];
splineparam = varargin(2);
splineparam = [splineparam{:}];
case 3;
r = varargin(1);
r = [r{:}];
v = varargin(2);
v = [v{:}];
phasedata(1, max(size(r))) = struct('r', '', 'v', '');
for i = 1:max(size(r))
phasedata(i).r = r(i);
phasedata(i).v = v(i);
end
splineparam = varargin(3);
splineparam = [splineparam{:}];
clear('r');
clear('v');
end
%%

global APPROXPOINTSNUMBER;
APPROXPOINTSNUMBER=100;%100; %number of approximation points
%APPROXPOINTSNUMBER=length(phasedata);

%approximation
xx=linspace(phasedata(1).r,phasedata(length(phasedata)).r,APPROXPOINTSNUMBER);

%exact spline
%phasespline=csape([phasedata.r], [phasedata.v], 'variational');

%smoothing spline
%functionsplineparam=0.7;%0.15;
precision=ones(1,length([phasedata.r]));
precision(1)=1E5;
precision(length(precision))=1E5;
phasespline=csaps([phasedata.r],[phasedata.v],splineparam,[],precision);

fxx=fnval(phasespline,xx);

if length(xx)==length(phasedata)
xx=[phasedata.r];
fxx=[phasedata.v];
end;
x = xx;
fx = fxx;
%
% x_max = xx(fxx == max(fxx));
% x(1:APPROXPOINTSNUMBER/2 + 1) = linspace(xx(1), x_max, APPROXPOINTSNUMBER/2 + 1);
% x(end) = [];
% fx((1:APPROXPOINTSNUMBER/2)) = fnval(phasespline,x(1:APPROXPOINTSNUMBER/2));
% for i = APPROXPOINTSNUMBER/2 + 1:APPROXPOINTSNUMBER-1
% fx(i) = fx(APPROXPOINTSNUMBER/2 - (i - APPROXPOINTSNUMBER/2)+1);
% fun = @(x) fnval(phasespline, x) - fx(i);
% x(i) = fzero(fun, [x_max, xx(end)]);
% end
% fx(APPROXPOINTSNUMBER) = 0;
% x(APPROXPOINTSNUMBER) = xx(end);

%plotting
% figure;
% hold on;
% plot([phasedata.r], [phasedata.v], 'ro');
% plot(x,fx,'bx-');
% plot([phasedata.r], [phasedata.v], 'ko');
% plot(x,fx,'k-');
% title('Initial phase and spline approximation');
% grid on;
% hold off;
end