function outp=fitdecayosc(xin,yin)
%% Fit the oscillation data to a damped oscillation to extract parameters about the oscilation
% Please trim your data so that the first point is approximatley the first
% point of a sine curve.

%make the first x value to be zero

x=xin(:)-xin(1);
y=yin(:);

[amp_guess,Ind]=max(abs(y-mean(y)));   
pks=getoscpks(x,y-mean(y),amp_guess/2);
fac=1;
if length(pks)<2 || isempty(pks);
    pkm=getoscpks(x,-(y-mean(y)),amp_guess/2);
    pks=[pks;pkm];
    fac=2;
end

if size(pks,1)<2 || isempty(pks);
%    pkm=getoscpks(x,-(y-mean(y)),amp_guess/2);
%    pks=[pks;pkm];
    clear pks;
    fac=2;
	
	h=msgbox({'Please pick peaks manually.'},'Auto peak detection failed','modal');
    uiwait(h)
    plot(x,y)
    title({'Left click on the locations of peaks and valleys.','Press ENTER when you are done.'},'FontSize',20)
	pks=ginput;
end

pks=sortrows(pks);
p=polyfit(pks(:,1),log(pks(:,2)),1);
decay_guess=-1/p(1);
freq_guess=1/fac/abs(mean(diff(pks(:,1))));

ftk=fittype('decayosc(x,amp,decayt,freq,phs,vshift)');
ft=fit(x,y,ftk,'StartPoint',[amp_guess,decay_guess,freq_guess, 0, mean(y)],'Lower',[0.5*amp_guess,0,0,-pi,-5*abs(mean(y))],'Upper',[Inf,Inf,Inf,pi,5*abs(mean(y))]);
close all;
plot(xin,yin);
hold on,plot(x+xin(1),decayosc(x,ft.amp,ft.decayt,ft.freq,ft.phs,ft.vshift),'r-','Linewidth',2)
outp=ft;
end
