function NLIN_OscillationsFigure

global TS;
if isempty(TS)
    TS.index=0;
end
global TSOsc; TSOsc.index=0;

% визначаємо поточну розподільчу здатність, встановивши одиниці в PIXELS
set(0,'Units','pixels');
SCREEN_SIZE=get(0,'ScreenSize');
% SCREEN_SIZE = [left bottom width height]
SCRHeight=SCREEN_SIZE(1,4);

hF = figure('Position',[10,SCRHeight-380,450,330],'Name','Аналіз коливань',...
    'NumberTitle', 'off','MenuBar','none','Tag','mainwin',...
    'DeleteFcn',@DeleteF_Callback);
handles.rootFigure=hF;
handles.ListBoxTS=uicontrol(hF, 'Style','listbox', 'Units','pixels',...
          'Position',[3,230,447,100], ...
          'String','', 'FontName','Times New Roman', ...
          'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal', ...
          'Tag', 'ListBoxTS', 'ListboxTop', 5, 'Callback', @ListBoxClick_Callback);
handles.BtnPlot = uicontrol('Style', 'pushbutton', ...
    'Position', [3 200 150 25],...
    'String', 'Взяти частину графіка',...
    'Callback', @BtnPlot_Callback);
% =============================================================================================================================
handles.mnFile=uimenu('Label','Файл','Tag','mnFile');
handles.mnOpen=uimenu(handles.mnFile,'Label','Зчитати дані...','Callback',@Open_Callback,...
    'Tag','mnOpen');
handles.mnSave=uimenu(handles.mnFile, 'Label', 'Зберегти...', 'Callback', @Save_Callback,...
    'Tag', 'mnSave');   
handles.mnExit=uimenu(handles.mnFile,'Label','Вихід','Callback','delete(gcf)','Tag','mnExit');
handles.mnPlot=uimenu('Label','Графік','Tag','mnFile');
handles.mnPlotGraph=uimenu(handles.mnPlot, 'Label', 'Будувати...', 'Callback', @PlotGraph_Callback,...
    'Tag', 'mnPlotGraph');
handles.mnAppendGraph=uimenu(handles.mnPlot,'Label', 'Додати...', 'Callback', @AppendGraph_Callback,...
    'Tag', 'mnAppendGraph');
handles.mnDO=uimenu('Label','Розрахувати параметри коливань...','Callback',@DO_Callback,...
    'Tag','mnDO');
handles.mnPrognoz=uimenu('Label','Прогнозування','Tag','mnPrognoz','Callback',@Prognoztime_Callback,...
    'Tag','mnPrognoz');
handles.mnGrid=uimenu('Label','Сітка','Tag','mnGrid');
handles.mnXGrid=uimenu(handles.mnGrid,'Label','X-сітка','Callback',@XGrid_Callback,'Tag','mnXGrid');
handles.mnYGrid=uimenu(handles.mnGrid,'Label','Y-сітка','Callback',@YGrid_Callback,'Tag','mnYGrid');
% =============================================================================================================================
% y0
uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,170,297,25], ...
          'String','Початкова амплітуда:', ...
          'FontName','Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.amplitudeEdit=uicontrol(hF, 'Style','edit', 'Tag','amplitudeEdit', ...
          'BackgroundColor',[1.0 1.0 1.0], 'Units','pixels', 'Position',[300,170,147,25], ...
          'String','', 'FontName','Courier New', ...
          'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');

% fi0
uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,145,297,25], ...
          'String','Початкова фаза:', ...
          'FontName', 'Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.phaseEdit=uicontrol(hF, 'Style','edit', 'Tag','phaseEdit', ...
          'BackgroundColor',[1.0 1.0 1.0], 'Units','pixels', 'Position',[300,145,147,25], 'String','', ...
          'FontName','Courier New','FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');

% w0
uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,120,297,25], ...
          'String','Кутова частота:', 'FontName','Times New Roman', ...
          'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.frequencyEdit=uicontrol(hF, 'Style','edit', 'Tag','frequencyEdit', 'BackgroundColor',[1.0 1.0 1.0], ...
          'Units','pixels', 'Position',[300,120,147,25], 'String','', ...
          'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');

% delta
uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,95,297,25], ...
          'String','Коефіцієнт затухання:', ...
          'FontName','Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.attenuationEdit=uicontrol(hF, 'Style','edit', 'Tag','attenuationEdit','BackgroundColor',[1.0 1.0 1.0], ...
          'Units','pixels', 'Position',[300,95,147,25], 'String','', ...
          'FontName','Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');

% T
handles.periodText=uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,70,297,25], ...
          'String','Період:', ...
          'FontName','Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.periodEdit=uicontrol(hF, 'Style','edit', 'Tag','periodEdit', ...
          'BackgroundColor',[1.0 1.0 1.0], 'Units','pixels', 'Position',[300,70,147,25], ...
          'String','', 'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');

% S
uicontrol(hF, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[3,45,297,25], ...
          'String','Сума квадратів невязок', ...
          'FontName','Times New Roman', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
handles.sumsqrEdit=uicontrol(hF, 'Style','edit', 'Tag','sumsqrEdit', ...
          'BackgroundColor',[1.0 1.0 1.0], 'Units','pixels', 'Position',[300,45,147,25], ...
          'String','', 'FontName','Courier New', ...
          'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'normal');
% =============================================================================================================================
handles.plotODPushbutton=uicontrol(hF, 'Style','pushbutton', 'Tag','plotODButton', ...
          'Units','pixels', 'Position',[30,10,160,25], 'String','Будувати DOA', ...
          'FontName','Times New Roman', 'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'bold', ...
          'Callback',@plotDOButton_Callback);
handles.plotrealODPushbutton=uicontrol(hF, 'Style','pushbutton', 'Tag','plotrealODButton', ...
          'Units','pixels', 'Position',[260,10,160,25], 'String','Будувати REAL+RDOA', ...
          'FontName','Times New Roman', 'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'bold', ...
          'Callback',@plotrealDOButton_Callback);
% =============================================================================================================================
handles.plotFigure=figure;
handles.A = axes('NextPlot','replacechildren','Tag','mainax','Position', [0.1 0.2 0.8 0.7]);
%cmnAxes=uicontextmenu('Tag','cmnAxes');
%cmnXGrid=uimenu(cmnAxes,'Label','X-сітка','Callback',@XGrid_Callback,'Tag','cmnXGrid');
%cmnYGrid=uimenu(cmnAxes,'Label','Y-сітка','Callback',@YGrid_Callback,'Tag','cmnYGrid');
%set(handles.A,'UIContextMenu',cmnAxes)
% =============================================================================================================================
global TSCut;
if ~isempty(TSCut)
    Y=TSCut.data{TSCut.currentIndex}.Y;
    [m,n]=size(Y);
    if m==1
        Y=Y';
        [m,n]=size(Y);
    end

    X=TSCut.data{TSCut.currentIndex}.X;
    [m,n]=size(X);
    if m==1
        X=X';
        [m,n]=size(X);
    end

%    X=[1:m];
%    X=X';
    
    global TSOsc;
    FName=['Ряд'];
    exmenuSaveTSOsc(X,Y,FName,0,0);
    
%    handles=guidata(gcbo);
    ListBoxTS=handles.ListBoxTS;
    STRINGS=get(ListBoxTS,'String');
    if (TSOsc.data{TSOsc.index}.prevIndex==0)
        STRINGS=appendString(STRINGS,[int2str(TSOsc.index) ' ('  FName ')' ]);
    else
        STRINGS=appendString(STRINGS,[int2str(TSOsc.index) ' ('  int2str(TSOsc.data{TSOsc.index}.prevIndex) ') : ' FName]);
    end
    set(ListBoxTS,'String',STRINGS);
end

guidata(hF,handles);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ФУНКЦІЇ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DeleteF_Callback(scr, evt)

global TSOsc;
clear TSOsc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Open_Callback(src,evt)
[FName,PName]=uigetfile('*.txt;*.dat;*.ts;*.asc;*.mat');

if ~isequal(FName,0)
    Name=strcat(PName,FName);
    
    A=load(Name);
    Y=A;
    [m,n]=size(Y);
    if m==1
        Y=Y';
        [m,n]=size(Y);
    end
    
    X=[1:m]; X=X';
    
    global TSOsc;
    exmenuSaveTSOsc(X,Y,FName,0,0);
    
    handles=guidata(gcbo);
    ListBoxTS=handles.ListBoxTS;
    STRINGS=get(ListBoxTS,'String');
    if (TSOsc.data{TSOsc.index}.prevIndex==0)
        STRINGS=appendString(STRINGS,[int2str(TSOsc.index) ' ('  FName ')' ]);
    else
        STRINGS=appendString(STRINGS,[int2str(TSOsc.index) ' ('  int2str(TSOsc.data{TSOsc.index}.prevIndex) ') : ' FName]);
    end
    set(ListBoxTS,'String',STRINGS);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Save_Callback(scr,evt)

global TSOsc;

[FName,PName]=uiputfile('*.txt');

[m,n]=size(FName);
if (n<4) || (~((FName(n-3)=='.') && (FName(n-2)=='t') && (FName(n-1)=='x') && (FName(n)=='t')))
    FNameX=[FName '.dt'];
    FNameY=[FName '.ts'];
end
 
handles=guidata(gcbo);
index=get(handles.ListBoxTS,'Value');
X=TSOsc.data{index}.X;
Y=TSOsc.data{index}.Y;

NAME = strcat(PName,FNameX);
save(NAME,'X','-ASCII');
NAME = strcat(PName,FNameY);
save(NAME,'Y','-ASCII');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ListBoxClick_Callback(scr,evt)

global TSOsc;
handles=guidata(gcbo);
index=get(handles.ListBoxTS,'Value');

if (TSOsc.data{index}.calculated==1)
    set(handles.amplitudeEdit,'String',num2str(TSOsc.data{index}.y0));
    set(handles.frequencyEdit,'String',num2str(TSOsc.data{index}.w0));
    set(handles.periodEdit,'String',num2str(TSOsc.data{index}.T));
    set(handles.phaseEdit,'String',num2str(TSOsc.data{index}.fi0));
    set(handles.attenuationEdit,'String',num2str(TSOsc.data{index}.delta));
    set(handles.sumsqrEdit,'String',num2str(TSOsc.data{index}.S));
else
    set(handles.amplitudeEdit,'String','');
    set(handles.frequencyEdit,'String','');
    set(handles.periodEdit,'String','');
    set(handles.phaseEdit,'String','');
    set(handles.attenuationEdit,'String','');
    set(handles.sumsqrEdit,'String','');
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function XGrid_Callback(src, evt)
   
handles=guidata(gcbo);
   
state=get(src,'Checked');
if isequal(state,'off')
    set(handles.mnXGrid,'Checked','on');
    set(get(handles.plotFigure,'Children'),'XGrid','on');
else
    set(handles.mnXGrid,'Checked','off');
    set(get(handles.plotFigure,'Children'),'XGrid','off');
end
figure(handles.rootFigure);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function YGrid_Callback(src, evt)
   
handles=guidata(gcbo);
  
state=get(src,'Checked');
if isequal(state,'off');
    set(handles.mnYGrid,'Checked','on');
    set(get(handles.plotFigure,'Children'),'YGrid','on');
else
    set(handles.mnYGrid,'Checked','off');
    set(get(handles.plotFigure,'Children'),'YGrid','off');
end
figure(handles.rootFigure);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PlotGraph_Callback(scr, evt)

global TSOsc;
handles=guidata(gcbo);

figure(handles.plotFigure)
legend off

cla
set(handles.A,'XScale','linear');
set(handles.A,'YScale','linear');
set(get(handles.A,'XLabel'),'String','');
set(get(handles.A,'YLabel'),'String','');
XLIM('auto');
YLIM('auto');
index=get(handles.ListBoxTS,'Value');
if (TSOsc.index == 0), return; end;
plot(TSOsc.data{index}.X,TSOsc.data{index}.Y);
title(TSOsc.data{index}.type);

figure(handles.rootFigure);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function AppendGraph_Callback(scr, evt)

global TSOsc;
handles=guidata(gcbo);

index=get(handles.ListBoxTS,'Value');

figure(handles.plotFigure);
hold on
if (TSOsc.index == 0), return; end;
plot(TSOsc.data{index}.X,TSOsc.data{index}.Y,'r');
hold off

figure(handles.rootFigure);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% обрахунок та вивід коефіцієнтів затухаючих коливань 
function DO_Callback(scr, evt)

global TSOsc;
handles = guidata(gcbo);

figure(handles.plotFigure);
legend off

figure(handles.rootFigure);
index=get(handles.ListBoxTS,'Value');
% Y=TSOsc.data{index}.Y;
[y0,w0,T,fi0,delta,S,YTrend,rezi,TT,YY,YY2]=w1(TSOsc.data{index}.Y);

index=get(handles.ListBoxTS,'Value');
TSOsc.data{index}.y0=y0;
set(handles.amplitudeEdit,'String',num2str(y0));
TSOsc.data{index}.w0=w0;
set(handles.frequencyEdit,'String',num2str(w0));
TSOsc.data{index}.T=T;
set(handles.periodEdit,'String',num2str(T));
TSOsc.data{index}.fi0=fi0;
set(handles.phaseEdit,'String',num2str(fi0));
TSOsc.data{index}.delta=delta;
set(handles.attenuationEdit,'String',num2str(delta));
TSOsc.data{index}.S=S;
set(handles.sumsqrEdit,'String',num2str(S));
TSOsc.data{index}.YTrend=YTrend;
TSOsc.data{index}.rezi=rezi;
TSOsc.data{index}.XX=TT;
TSOsc.data{index}.YY=YY;
TSOsc.data{index}.YY2=YY2;
TSOsc.data{index}.calculated=1;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotDOButton_Callback(scr, evt)

global TSOsc;
handles=guidata(gcbo);
index=get(handles.ListBoxTS,'Value');
DATA=TSOsc.data{index};

if (TSOsc.data{index}.calculated==0)
    msgbox('Спочатку обчисліть параметри!','Неправильна операція!');
    return;
end

figure(handles.plotFigure);
cla;

a1=plot(DATA.YY);
hold on
a2=plot(DATA.YY2,'r');
hold off
legend([a1,a2],'transform real data','transform approximate data');

clear handles index a1 a2;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function plotrealDOButton_Callback(scr, evt)

global TSOsc;
handles=guidata(gcbo);
index=get(handles.ListBoxTS,'Value');
DATA=TSOsc.data{index};

if (TSOsc.data{index}.calculated==0)
    msgbox('Спочатку обчисліть параметри!','Неправильна операція!');
    return;
end

YY2=DATA.YY2;
Y=DATA.Y;
[m1,n1]=size(Y);
[m2,n2]=size(YY2);
if m1<n2 
    t=[0:m1-1];
    TT=[min(t):0.001:max(t)];
    YY=spline(t,Y,TT);
end
YRes=YY2;
for i=1:n2
   YRes(i)=YY2(n2-i+1);
end
rezi=DATA.rezi;
p = polyfit(TT, YY, rezi);
y_temp = polyval(p, TT);
YRes=YRes+y_temp;

figure(handles.plotFigure);
cla
a1=plot(YY);
hold on
a2=plot(YRes,'r');
hold off
legend([a1,a2],'real data','approximate data');

clear handles3 YY2 m1 n1 m2 n2 t TT YY i rezi p y_temp YRes a1 a2;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function BtnPlot_Callback(scr, evt)

global TSOsc;
global index;
global flag; 

handles = guidata(gcbo);

LINES=get(handles.A,'Children');
[LINESm,LINESn]=size(LINES);
if LINESm>1
    for i=1:LINESm-1
        delete(LINES(i,1))
    end
end
X=get(LINES(LINESm,1),'XData');
Y=get(LINES(LINESm,1),'YData');

TEMP=get(handles.BtnPlot,'String');
set(handles.BtnPlot,'String','Виберіть 2 точки');
figure(handles.plotFigure);
[mouseX,mouseY]=ginput(2);
set(handles.BtnPlot,'String',TEMP);

[Xm,Xn]=size(X);
Min=abs(X(1,1)-mouseX(1,1));
indexMin1=1;
for i=2:Xn
    if abs(X(1,i)-mouseX(1,1))<Min
        Min=abs(X(1,i)-mouseX(1,1));
        indexMin1=i;
    end
end

Min=abs(X(1,1)-mouseX(2,1));
indexMin2=1;
for i=2:Xn
    if abs(X(1,i)-mouseX(2,1))<Min
        Min=abs(X(1,i)-mouseX(2,1));
        indexMin2=i;
    end
end

if indexMin1>indexMin2
    TEMP=indexMin1;
    indexMin1=indexMin2;
    indexMin2=TEMP;
end

cla
index=get(handles.ListBoxTS,'Value');
if (TSOsc.index == 0), return; end;
xt = TSOsc.data{index}.X; xt=xt(indexMin1:indexMin2);
yt = TSOsc.data{index}.Y; yt=yt(indexMin1:indexMin2);

a=plot(xt,yt);
flag=1;
[m,n]=size(a);
X=[1:m]; X=X';
    
exmenuSaveTSOsc(xt,yt,'part.txt',0,0);
ListBoxTS=handles.ListBoxTS;
STRINGS=get(ListBoxTS,'String');
if (TSOsc.data{TSOsc.index}.prevIndex==0)
   STRINGS=appendString(STRINGS,[int2str(TSOsc.index-1) 'part' ]);
else
   STRINGS=appendString(STRINGS,[int2str(TSOsc.index) ' ('  int2str(TSOsc.data{TSOsc.index}.prevIndex) ') : '  'part' int2str(flag)]);
end
set(ListBoxTS,'String',STRINGS);
set(ListBoxTS,'Value',TSOsc.index)
legend(a,'new data');
flag=flag+1;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Prognoztime_Callback(scr, evt)

global TSOsc;
handles = guidata(gcbo);
index=get(handles.ListBoxTS,'Value');
DATA=TSOsc.data{index};

if (TSOsc.data{index}.calculated==0)
    msgbox('Спочатку обчисліть параметри!','Неправильна операція!');
    return;
end

% беремо початкові ряди
X=DATA.X;
X=X-min(X);
Y=DATA.Y;

XX=max(X)+1:max(X)+2*floor(DATA.T);
XX=XX';
XX=[X; XX];
% обчислюємо нову початкову амплітуду, прогнозуючи вперед на 2 періоди
y0=DATA.y0*exp(-DATA.delta*2*DATA.T);
% будуємо модельний ряд
YY=y0*exp(-DATA.delta*XX).*sin(DATA.w0*XX+DATA.fi0);
%YY2=DATA.y0*exp(-DATA.delta*X).*sin(DATA.w0*X+DATA.fi0);
% розвертаємо модельний ряд
[m,n]=size(YY);
for i=1:floor(m/2)
    temp=YY(i);
    YY(i)=YY(m-i+1);
    YY(m-i+1)=temp;
end    
rezi=DATA.rezi;
p = polyfit(X,Y,rezi);
y_temp = polyval(p, XX);
YY=YY+y_temp;
% зміщуємо абсциси
X=X+min(DATA.X);
XX=XX+min(DATA.X);

% будуємо графіки
figure(handles.plotFigure);
cla
a1=plot(X,Y);
hold on
a2=plot(XX,YY,'r');
hold off
legend([a1,a2],'real data','forecasting data');
    
