function varargout = GEv1(varargin)
% GEv1 M-file for GEv1.fig
%      GEv1, by itself, creates a new GEv1 or raises the existing
%      singleton*.
%
%      H = GEv1 returns the handle to a new GEv1 or the handle to
%      the existing singleton*.
%
%      GEv1('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GEv1.M with the given input arguments.
%
%      GEv1('Property','Value',...) creates a new GEv1 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GEv1_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GEv1_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help GEv1

% Last Modified by GUIDE v2.5 27-Nov-2012 21:13:39

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GEv1_OpeningFcn, ...
                   'gui_OutputFcn',  @GEv1_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before GEv1 is made visible.
function GEv1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to GEv1 (see VARARGIN)

% Choose default command line output for GEv1
handles.output = hObject;

handles.datos=varargin{1}; %input1: matriz D
handles.modelo=varargin{2}; %input2: modelo
datoseventos=varargin{3}; %input 3: todos los datos de los eventos actuales
handles.perfil=varargin{4}; %input 4:para perfil de análisis

handles.listaeventos=datoseventos{1};
handles.grafeventos=datoseventos{2};
handles.rescomb=datoseventos{3};
handles.rescombgrp=datoseventos{4};
handles.tablaeventos=datoseventos{5};
handles.neventos=datoseventos{6};

[currentdic,inutil]=importdic(handles.modelo);

[M,N]=size(handles.datos);
[P,inutil]=size(currentdic{1});
handles.M=M-1; %duracion de los datos
handles.N=N;

set(handles.textdurtot1,'String',num2str(handles.M));

%Inicializamos las listas sin filtrar%%%%%%%%%%%%%%%
listapne=cell(P,1);
listapnecargadas=cell(N,1);
listacomp=cell(P,1);
matrizposibilidades=cell(P,16);
posibilidadestabla=cell(P,1);
cargadas=zeros(P,1);
cargadastabla=cell(P,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Llenamos las listas sin filtrar%%%%%%%%%%%%%%%%%%%%
for i=1:P 
    intermedio=currentdic{8}(i); %lista pnemonic (nombres armonizados!!)
    listapne{i,1}=intermedio{1};
    intermedio=currentdic{3}(i); %lista nombres completos
    listacomp{i,1}=intermedio{1};
    
    cad=currentdic{7}(i);
    cad=cad{1};
    posibilidades=cell(1);
    posibilidades=textscan(cad,'%s',15,'Delimiter','/');
    [numpos,inutil]=size(posibilidades{1});
    
    if strcmp(currentdic{5}{i},'DISCRETE')
        for x=1:numpos
            intermedio=posibilidades{1}(x);
            posibilidadestabla{i,1}=[posibilidadestabla{i,1},num2str(x),':',intermedio{1},' '];
            matrizposibilidades{i,x+1}=intermedio{1};
        end
        matrizposibilidades{i,1}=numpos;
    else
        intermedio=posibilidades{1}(1);
        posibilidadestabla{i,1}=intermedio{1};
        matrizposibilidades{i,1}=0;        
    end
end

for t=1:N
    cargadas(handles.datos(1,t))=1;
    cargadastabla{handles.datos(1,t)}='#';
    intermedio=currentdic{8}(handles.datos(1,t)); %lista pnemonic cargadas
    listapnecargadas{t,1}=intermedio{1};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Salvamos las listas sin filtrar%%%%%%%%%%%%%%%%%%%%
handles.listapne=listapne;
handles.listapnecargadas=listapnecargadas;
handles.listacomp=listacomp;
handles.matrizposibilidades=matrizposibilidades;
handles.posibilidadestabla=posibilidadestabla;
handles.cargadas=cargadas;
handles.cargadastabla=cargadastabla;
handles.P=P;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Filtros%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
handles.solocargadas=0;
handles.cadena='';
[handles]=actualizartabla(handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%Resultado eventos%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
handles.resind=zeros(8,handles.M); %iniz. resultados individuales de las búsquedas
handles.marcada=0; %iniz. selección sobre la tabla

set(handles.popupmenuforma,'String',{'Punto';'Círculo';'X';'Cuadrado';'Triángulo'});
set(handles.popupmenucolor,'String',{'Rojo';'Negro';'Azul';'Amarillo';'Verde'});

if handles.neventos>0
    set(handles.popupmenueventos,'String',handles.listaeventos);
    set(handles.popupmenueventos,'Value',handles.neventos);
    set(handles.uitableeventos,'Data',handles.tablaeventos{(handles.neventos)});
    set(handles.checkboxmarcar,'Value',handles.grafeventos(handles.neventos,1));
    set(handles.popupmenuforma,'Value',handles.grafeventos(handles.neventos,2));
    set(handles.popupmenucolor,'Value',handles.grafeventos(handles.neventos,3));
    handles.nev=handles.neventos;
else
    handles.nev=1;
    handles.listaeventos=cell(1);
    handles.grafeventos=[0 1 1];
    handles.rescomb=cell(0);
    handles.rescombgrp=cell(0);
    handles.tablaeventos=cell(0);
    set(handles.popupmenueventos,'String',handles.listaeventos);
    set(handles.popupmenueventos,'Value',1);
    set(handles.uitableeventos,'Data',handles.tablaeventos);
    set(handles.checkboxmarcar,'Value',handles.grafeventos(1,1));
    set(handles.popupmenuforma,'Value',handles.grafeventos(1,2));
    set(handles.popupmenucolor,'Value',handles.grafeventos(1,3));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%Limpiar%%%%%%%%%%%%%%%%%%%
handles.evento.comienzo=0;
set(handles.editcomienzo,'String','');
handles.evento.final=0;
set(handles.editfinal,'String','');
handles.evento.dmin=0;
set(handles.editdmin,'String','');
% handles.evento.dmax=0;
% set(handles.editdmax,'String',num2str(handles.evento.dmax));
handles.evento.combinacion='';
set(handles.editcombi,'String',num2str(handles.evento.combinacion));
handles.evento.nombre='';
set(handles.editnombre,'String',num2str(handles.evento.nombre));
handles.evento.modelo=handles.modelo;
    
for h=1:8
    handles.evento.cond{h}='';
    eval(['set(handles.editcond',num2str(h),',''String'',handles.evento.cond{h})']);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%PERFIL%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isstruct(handles.perfil)
    for k=1:5
        eval(['eventok=handles.perfil.evento',num2str(k),';']);
        if isempty(eventok)==0
            [handles]=cargar(handles,eventok,0);
            if handles.testeve==1
                %%%%%%%%Control Variables%%%%%%%%%%%%%
                Z=cell(1);
                for g=1:P
                    nombreabr=currentdic{8}(g);
                    nombreabr=nombreabr{1};
                    for b=1:8
                        matches=regexpi(handles.evento.cond{b},nombreabr);
                        if isempty(matches)==0
                            Z=[Z,nombreabr]; %Z contiene las variables
                        end                  %usadas en el evento
                    end
                    
                end
                [inutil,Y]=size(Z);
                if Y>1
                    test1=0;
                    for d=2:Y
                        for f=1:handles.N
                            matches=strcmp(handles.listapnecargadas{f},Z(d));
                            test1=test1+matches;
                        end
                    end
                    if test1>=(Y-1)
                        control=1;
                    else
                        control=0;
                    end
                else
                    uiwait(warndlg(['Alguna de las variables del evento ',eventok,' no se encuentra en los datos.'], 'Error de evento','modal'));
                end
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                if control==1
                    [handles]=buscar(handles);
                    handles.grafeventos(handles.nev,1)=handles.perfil.grafeve(k,1);
                    handles.grafeventos(handles.nev,2)=handles.perfil.grafeve(k,2);
                    handles.grafeventos(handles.nev,3)=handles.perfil.grafeve(k,3);
                    set(handles.checkboxmarcar,'Value',handles.grafeventos(handles.nev,1));
                    set(handles.popupmenuforma,'Value',handles.grafeventos(handles.nev,2));
                    set(handles.popupmenucolor,'Value',handles.grafeventos(handles.nev,3));
                else
                    uiwait(warndlg(['Alguna de las variables del evento ',eventok,' no se encuentra en los datos.'], 'Error de evento','modal'));
                end
            end
        end
    end
handles.datoseventos{1}=handles.listaeventos;
handles.datoseventos{2}=handles.grafeventos;
handles.datoseventos{3}=handles.rescomb;
handles.datoseventos{4}=handles.rescombgrp;
handles.datoseventos{5}=handles.tablaeventos;
handles.datoseventos{6}=handles.neventos;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes GEv1 wait for user response (see UIRESUME)
if isstruct(handles.perfil)==0
uiwait(handles.figure1);
end

% --- Outputs from this function are returned to the command line.
function varargout = GEv1_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure

varargout{1}=handles.datoseventos;

% varargout{1}=handles.evento;
% varargout{2}=handles.rescomb;
% varargout{3}=handles.rescombgrp;

guidata(hObject,handles);

delete(gcf);



function editcond1_Callback(hObject, eventdata, handles)
% hObject    handle to editcond1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond1 as text
%        str2double(get(hObject,'String')) returns contents of editcond1 as a double

handles.evento.cond{1}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond7_Callback(hObject, eventdata, handles)
% hObject    handle to editcond7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond7 as text
%        str2double(get(hObject,'String')) returns contents of editcond7 as a double
handles.evento.cond{7}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editcond8_Callback(hObject, eventdata, handles)
% hObject    handle to editcond8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond8 as text
%        str2double(get(hObject,'String')) returns contents of editcond8 as a double

handles.evento.cond{8}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond5_Callback(hObject, eventdata, handles)
% hObject    handle to editcond5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond5 as text
%        str2double(get(hObject,'String')) returns contents of editcond5 as a double

handles.evento.cond{5}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond4_Callback(hObject, eventdata, handles)
% hObject    handle to editcond4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond4 as text
%        str2double(get(hObject,'String')) returns contents of editcond4 as a double

handles.evento.cond{4}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond3_Callback(hObject, eventdata, handles)
% hObject    handle to editcond3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond3 as text
%        str2double(get(hObject,'String')) returns contents of editcond3 as a double

handles.evento.cond{3}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond6_Callback(hObject, eventdata, handles)
% hObject    handle to editcond6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond6 as text
%        str2double(get(hObject,'String')) returns contents of editcond6 as a double

handles.evento.cond{6}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function editcond2_Callback(hObject, eventdata, handles)
% hObject    handle to editcond2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcond2 as text
%        str2double(get(hObject,'String')) returns contents of editcond2 as a double

handles.evento.cond{2}=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcond2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcond2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbuttonbuscar.
function pushbuttonbuscar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonbuscar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[handles]=buscar(handles);

guidata(hObject, handles);



function editcombi_Callback(hObject, eventdata, handles)
% hObject    handle to editcombi (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcombi as text
%        str2double(get(hObject,'String')) returns contents of editcombi as a double

handles.evento.combinacion=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcombi_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcombi (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% PARÁMETRO DMAX DE MOMENTO ELIMINADO
% function editdmax_Callback(hObject, eventdata, handles)
% % hObject    handle to editdmax (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    structure with handles and user data (see GUIDATA)
% 
% % Hints: get(hObject,'String') returns contents of editdmax as text
% %        str2double(get(hObject,'String')) returns contents of editdmax as a double
% 
% dmax=str2double(get(hObject,'String'));
% 
% if isempty(get(hObject,'String'))
%     handles.evento.dmax=0;
% elseif isnan(dmax)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif floor(dmax)~=dmax
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif (dmax>handles.M||dmax<0)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% else
% handles.evento.dmax=dmax;
% end
% 
% guidata(hObject, handles);
% 
% % --- Executes during object creation, after setting all properties.
% function editdmax_CreateFcn(hObject, eventdata, handles)
% % hObject    handle to editdmax (see GCBO)
% % eventdata  reserved - to be defined in a future version of MATLAB
% % handles    empty - handles not created until after all CreateFcns called
% 
% % Hint: edit controls usually have a white background on Windows.
% %       See ISPC and COMPUTER.
% if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
%     set(hObject,'BackgroundColor','white');
% end



function editdmin_Callback(hObject, eventdata, handles)
% hObject    handle to editdmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editdmin as text
%        str2double(get(hObject,'String')) returns contents of editdmin as a double

dmin=str2double(get(hObject,'String'));

if isempty(get(hObject,'String'))
    handles.evento.dmin=0;
elseif isnan(dmin)
    warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(dmin)~=dmin
    warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
    set(hObject,'String','');
elseif (dmin>handles.M||dmin<0)
    warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
    set(hObject,'String','');
else
handles.evento.dmin=dmin;
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editdmin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editdmin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editfinal_Callback(hObject, eventdata, handles)
% hObject    handle to editfinal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editfinal as text
%        str2double(get(hObject,'String')) returns contents of editfinal as a double

final=get(hObject,'String');

if isempty(get(hObject,'String'))
    handles.evento.final='0';
% elseif isnan(final)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif floor(final)~=final
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif (final>handles.M||final<0)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
else
handles.evento.final=final;
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editfinal_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editfinal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editcomienzo_Callback(hObject, eventdata, handles)
% hObject    handle to editcomienzo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcomienzo as text
%        str2double(get(hObject,'String')) returns contents of editcomienzo as a double

comienzo=get(hObject,'String');

if isempty(get(hObject,'String'))
    handles.evento.comienzo='0';
% elseif isnan(comienzo)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif floor(comienzo)~=comienzo
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
% elseif (comienzo>handles.M||comienzo<0)
%     warndlg('El formato no es válido. Introduzca un número entero entre 1 y la duración total.','Error de entrada','modal');
%     set(hObject,'String','');
else
handles.evento.comienzo=comienzo;
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editcomienzo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcomienzo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes when selected cell(s) is changed in uitablevariables.
function uitablevariables_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitablevariables (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)
indice=eventdata.Indices;
[I,inutil]=size(indice);

if I==1
    handles.marcada=indice(1,1);
else
    handles.marcada=0;
end
guidata(hObject, handles);


% --- Executes on key press with focus on editcond1 and none of its controls.
function editcond1_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond1 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond1,'String');
        set(handles.editcond1,'String',[temp,handles.tablafiltrada{handles.marcada,2},'()']);
        uicontrol(handles.editcond1);

    end
end


% --- Executes on button press in pushbuttonlimpiar.
function pushbuttonlimpiar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonlimpiar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.evento.comienzo=0;
set(handles.editcomienzo,'String','');
handles.evento.final=0;
set(handles.editfinal,'String','');
handles.evento.dmin=0;
set(handles.editdmin,'String','');
% handles.evento.dmax=0;
% set(handles.editdmax,'String',num2str(handles.evento.dmax));
handles.evento.combinacion='';
set(handles.editcombi,'String',num2str(handles.evento.combinacion));
handles.evento.nombre='';
set(handles.editnombre,'String',num2str(handles.evento.nombre));
handles.evento.modelo=handles.modelo;
    
for h=1:8
    handles.evento.cond{h}='';
    eval(['set(handles.editcond',num2str(h),',''String'',handles.evento.cond{h})']);
end


function editnombre_Callback(hObject, eventdata, handles)
% hObject    handle to editnombre (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editnombre as text
%        str2double(get(hObject,'String')) returns contents of editnombre as a double

handles.evento.nombre=get(hObject,'String');
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editnombre_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editnombre (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
handles.datoseventos=0;
guidata(hObject,handles);

uiresume(handles.figure1);


% --- Executes on key press with focus on editcond2 and none of its controls.
function editcond2_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond2 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond2,'String');
        set(handles.editcond2,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond2);

    end
end


% --- Executes on key press with focus on editcond3 and none of its controls.
function editcond3_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond3 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond3,'String');
        set(handles.editcond3,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond3);

    end
end


% --- Executes on key press with focus on editcond4 and none of its controls.
function editcond4_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond4 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond4,'String');
        set(handles.editcond4,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond4);

    end
end


% --- Executes on key press with focus on editcond5 and none of its controls.
function editcond5_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond5 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond5,'String');
        set(handles.editcond5,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond5);

    end
end


% --- Executes on key press with focus on editcond6 and none of its controls.
function editcond6_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond6 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond6,'String');
        set(handles.editcond6,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond6);

    end
end


% --- Executes on key press with focus on editcond7 and none of its controls.
function editcond7_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond7 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond7,'String');
        set(handles.editcond7,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond7);

    end
end


% --- Executes on key press with focus on editcond8 and none of its controls.
function editcond8_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to editcond8 (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

if strcmp(eventdata.Key,'f9')
    if handles.marcada~=0
        temp=get(handles.editcond8,'String');
        set(handles.editcond8,'String',[temp,handles.listapne{handles.marcada},'()']);
        uicontrol(handles.editcond8);

    end
end

% --- Executes on button press in pushbuttonquitar.
function pushbuttonquitar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonquitar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if handles.neventos==0
    warndlg('No hay ningún evento.','Error','modal');
else
    n=get(handles.popupmenueventos,'Value');
    handles.listaeventos(n)=[];
%     handles.rescomb(n)=[];
    handles.rescombgrp(n)=[];
    handles.tablaeventos(n)=[];
    handles.grafeventos(n,:)=[];

    handles.neventos=handles.neventos-1;
    if handles.neventos==0
        handles.listaeventos=cell(1);
        set(handles.popupmenueventos,'String',handles.listaeventos);
        handles.tablaeventos{1}=zeros(0,2);
        handles.grafeventos=[0 1 1];
    end
    set(handles.popupmenueventos,'String',handles.listaeventos);
    set(handles.popupmenueventos,'Value',1);
    set(handles.uitableeventos,'Data',handles.tablaeventos{1});
    handles.nev=1;
    set(handles.checkboxmarcar,'Value',handles.grafeventos(1,1));
    set(handles.popupmenuforma,'Value',handles.grafeventos(1,2));
    set(handles.popupmenucolor,'Value',handles.grafeventos(1,3));
end

guidata(hObject,handles);

% --- Executes on button press in checkboxmarcar.
function checkboxmarcar_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxmarcar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxmarcar

handles.grafeventos(handles.nev,1)=get(handles.checkboxmarcar,'Value');

guidata(hObject,handles);

% --- Executes on selection change in popupmenucolor.
function popupmenucolor_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenucolor (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenucolor contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenucolor

handles.grafeventos(handles.nev,3)=get(handles.popupmenucolor,'Value');

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenucolor_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenucolor (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenuforma.
function popupmenuforma_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenuforma (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenuforma contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenuforma

handles.grafeventos(handles.nev,2)=get(handles.popupmenuforma,'Value');

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenuforma_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenuforma (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenueventos.
function popupmenueventos_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenueventos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenueventos contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenueventos

handles.nev=get(handles.popupmenueventos,'Value');
set(handles.uitableeventos,'Data',handles.tablaeventos{handles.nev});
set(handles.checkboxmarcar,'Value',handles.grafeventos(handles.nev,1));
set(handles.popupmenuforma,'Value',handles.grafeventos(handles.nev,2));
set(handles.popupmenucolor,'Value',handles.grafeventos(handles.nev,3));

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenueventos_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenueventos (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbuttoncargar.
function pushbuttoncargar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttoncargar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[nombrearchivo,ruta,filtro] = uigetfile(['.\',handles.modelo,'\Eventos\*.eve'], 'Seleccione un archivo de evento');

[handles]=cargar(handles,nombrearchivo,ruta);

guidata(hObject,handles);


% --- Executes on button press in pushbuttonguardar.
function pushbuttonguardar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonguardar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[nombrearchivo,ruta,filtro] = uiputfile(['.\',handles.modelo,'\Eventos\',handles.evento.nombre,'.eve'], 'Elija un nombre para guardar el evento');

if nombrearchivo~=0
    directrabajo=cd;
    cd(ruta);

    uiresume(handles.figure1);
    fid=fopen(nombrearchivo,'wt');

    fprintf(fid,'%s,',handles.evento.nombre);
    fprintf(fid,'%s,',handles.evento.modelo);
    fprintf(fid,'%s,',handles.evento.comienzo);
    fprintf(fid,'%s,',handles.evento.final);
    fprintf(fid,'%d,',handles.evento.dmin);
    fprintf(fid,'%s,',handles.evento.cond{1});
    fprintf(fid,'%s,',handles.evento.cond{2});
    fprintf(fid,'%s,',handles.evento.cond{3});
    fprintf(fid,'%s,',handles.evento.cond{4});
    fprintf(fid,'%s,',handles.evento.cond{5});
    fprintf(fid,'%s,',handles.evento.cond{6});
    fprintf(fid,'%s,',handles.evento.cond{7});
    fprintf(fid,'%s,',handles.evento.cond{8});
    fprintf(fid,'%s,',handles.evento.combinacion);

    fclose(fid);

    cd(directrabajo)
    uiwait(handles.figure1);
end


function [handles]=anyadireve(handles,rescomb,rescombgrp)

handles.listaeventos{(handles.neventos+1)}=handles.evento.nombre;
% handles.rescomb{(handles.neventos+1)}=rescomb;
handles.rescombgrp{(handles.neventos+1)}=rescombgrp;

handles.grafeventos((handles.neventos+1),1)=0;
set(handles.checkboxmarcar,'Value',0);
handles.grafeventos((handles.neventos+1),2)=1;
set(handles.popupmenuforma,'Value',1);
handles.grafeventos((handles.neventos+1),3)=1;
set(handles.popupmenucolor,'Value',1);

tablacargada=zeros(0,2);
k=1;
for i=1:handles.M    
    if rescombgrp(i)~=0
        tablacargada(k,1)=i;
        tablacargada(k,2)=rescombgrp(i);
        k=k+1;
    end
end
handles.tablaeventos{(handles.neventos+1)}=tablacargada;

handles.neventos=handles.neventos+1;
handles.nev=handles.neventos;
set(handles.popupmenueventos,'String',handles.listaeventos);
set(handles.popupmenueventos,'Value',handles.nev);
set(handles.uitableeventos,'Data',handles.tablaeventos{(handles.nev)});
set(handles.checkboxmarcar,'Value',handles.grafeventos(handles.nev,1));
set(handles.popupmenuforma,'Value',handles.grafeventos(handles.nev,2));
set(handles.popupmenucolor,'Value',handles.grafeventos(handles.nev,3));


% --- Executes on button press in pushbuttonaceptar.
function pushbuttonaceptar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonaceptar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.datoseventos{1}=handles.listaeventos;
handles.datoseventos{2}=handles.grafeventos;
handles.datoseventos{3}=handles.rescomb;
handles.datoseventos{4}=handles.rescombgrp;
handles.datoseventos{5}=handles.tablaeventos;
handles.datoseventos{6}=handles.neventos;

guidata(hObject,handles);

uiresume(handles.figure1);

function [handles]=buscar(handles)

datosbusq=zeros(handles.N,handles.M);
handles.errorsintaxis=0;

%-----Se llena datosbusq con los datos quitando la primera fila y
%trasponiendo para pasárselo como argumento a busca2-----------------------
datosbusq=handles.datos';
datosbusq(:,1)=[];
%--------------------------------------------------------------------
%--------Se traduce comienzo y final---------------------------------

d=handles.M;
D=handles.M;

if strcmpi(handles.evento.comienzo,'auto')||strcmpi(handles.evento.final,'auto')
    [handles,principiov,finalv]=detectar(handles);
end

if strcmpi(handles.evento.comienzo,'auto')
    if principiov~=-1
        comienzotrad=principiov;
    else
        comienzotrad=0;
    end
else
    try
        comienzotrad=eval(handles.evento.comienzo);
    catch error
        uiwait(warndlg('La sintaxis de la variable Comienzo no es correcta, se tomará el valor por defecto. Recuerda que solo se admiten números naturales entre 1 y la duración total, 0 como valor por defecto, operaciones con números y la variable d (que tiene el valor de la duración total, y la palabra "auto" para detección automática de tiempo de vuelo.', 'Error de sintaxis','modal'));
        comienzotrad=0;
    end
    if (comienzotrad>handles.M)||(comienzotrad<0)
        uiwait(warndlg('La sintaxis de la variable Comienzo no es correcta, se tomará el valor por defecto. Recuerda que solo se admiten números naturales entre 1 y la duración total, 0 como valor por defecto, operaciones con números y la variable d (que tiene el valor de la duración total, y la palabra "auto" para detección automática de tiempo de vuelo.', 'Error de sintaxis','modal'));
        comienzotrad=0;
    end
end
if strcmpi(handles.evento.final,'auto')
    if principiov~=-1
        finaltrad=finalv;
    else
        finaltrad=0;
    end
else
    try
        finaltrad=eval(handles.evento.final);
    catch error
        uiwait(warndlg('La sintaxis de la variable Final no es correcta, se tomará el valor por defecto. Recuerda que solo se admiten números naturales entre 1 y la duración total, 0 como valor por defecto, operaciones con números y la variable d (que tiene el valor de la duración total, y la palabra "auto" para detección automática de tiempo de vuelo.', 'Error de sintaxis','modal'));
        finaltrad=0;
    end
    if (finaltrad>handles.M)||(finaltrad<0)
        uiwait(warndlg('La sintaxis de la variable Final no es correcta, se tomará el valor por defecto. Recuerda que solo se admiten números naturales entre 1 y la duración total, 0 como valor por defecto, operaciones con números y la variable d (que tiene el valor de la duración total, y la palabra "auto" para detección automática de tiempo de vuelo.', 'Error de sintaxis','modal'));
        finaltrad=0;
    end    
end

%--------------------------------------------------------------------
%--------Se crea el array de estructuras para busca2:----------------
for i=1:8
   
    busqueda{i}.dmax=0; %hasta nuevo aviso
    busqueda{i}.dmin=handles.evento.dmin;
    busqueda{i}.comienzo=comienzotrad;
    busqueda{i}.final=finaltrad;
    
    if isempty(handles.evento.cond{i})==0
                   
        busqueda{i}.condicion=handles.evento.cond{i}; 
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'=','==');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'&','&&');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'|','||');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'and','&&');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'or','||');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'not','~');
        busqueda{i}.condicion=regexprep(busqueda{i}.condicion,'~=','~==');
        
        
        for j=1:handles.N
            
            busqueda{i}.condicion=regexprep(busqueda{i}.condicion,[handles.listapnecargadas{j},'('],['v(',num2str(j),',k']);
        end
         
    else
        
        busqueda{i}.condicion='0';
    
    end
    
end
%------------------------------------------------------------------
%-------------Se realiza la búsqueda-------------------------------
[handles.resind,grp]=busca2(datosbusq,busqueda);
%------------------------------------------------------------------
%-------------Da dialog de error si alguna condición no válida-----
if strcmp(handles.resind,'error')
    warndlg(['Error de sintaxis en la condición ',num2str(grp),'.','No olvide usar paréntesis tras cada variable. Por ej. AOA1(). Por favor, compruebe también que las variables mencionadas en la condición están en los datos.'], 'Error de sintaxis','modal');
    handles.errorsintaxis=1;
%------------------------------------------------------------------
else
%----------Si las condiciones son válidas se busca combinación-----
%COMBINACIÓN:

rescomb=zeros(1,handles.M);
%handles.rescomb=rescomb;
rescombgrp=zeros(1,handles.M);
%handles.rescombgrp=rescombgrp;
        

if handles.evento.combinacion~=0
    if isempty(handles.evento.combinacion)==0
        
        combi{1}.dmax=0; %hasta nuevo aviso
        combi{1}.dmin=handles.evento.dmin;
        combi{1}.comienzo=comienzotrad;
        combi{1}.final=finaltrad;
        % Traducción de cadena de combinación:
        combitraducida=handles.evento.combinacion;
        combitraducida=regexprep(combitraducida,'C1','v(1,k)');
        combitraducida=regexprep(combitraducida,'C2','v(2,k)');
        combitraducida=regexprep(combitraducida,'C3','v(3,k)');
        combitraducida=regexprep(combitraducida,'C4','v(4,k)');
        combitraducida=regexprep(combitraducida,'C5','v(5,k)');
        combitraducida=regexprep(combitraducida,'C6','v(6,k)');
        combitraducida=regexprep(combitraducida,'C7','v(7,k)');
        combitraducida=regexprep(combitraducida,'C8','v(8,k)');
        combitraducida=regexprep(combitraducida,'&','&&');
        combitraducida=regexprep(combitraducida,'|','||');
        combitraducida=regexprep(combitraducida,'and','&&');
        combitraducida=regexprep(combitraducida,'or','||');
        combitraducida=regexprep(combitraducida,'not','~');
        combitraducida=regexprep(combitraducida,'=','==');
        
        %combitraducida
        combi{1}.condicion=combitraducida;
        %busca2 de combinación
        [rescomb,rescombgrp]=busca2(handles.resind,combi);
        %--------------Da error si sintaxis de combinación no válida-----
        if strcmp(rescomb,'error')
            warndlg('Error de sintaxis en la combinación.', 'Error de sintaxis','modal');
            handles.errorsintaxis=1;
        end
        %----------------------------------------------------------------

        
    end
end

end

% ---------Lo siguiente se hace si no ha habido error de sintaxis--------
if handles.errorsintaxis==0
% assignin('base','resind',handles.resind);
% assignin('base','datosbusq',datosbusq);
% assignin('base','rescomb',handles.rescomb);
% assignin('base','rescombgrp',handles.rescombgrp);
% handles.rescomb=rescomb;
% handles.rescombgrp=rescombgrp;
% handles.busqueda=busqueda;

    if numel(rescombgrp)>1
        [handles]=anyadireve(handles,rescomb,rescombgrp);
    end


end
%------------------------------------------------------------------------

function [handles]=cargar(handles,nombrearchivo,ruta)
handles.testeve=1;
if nombrearchivo~=0
    try %lo que se carga se mete en la estructura evento hasta q sea definitivo
        if ruta~=0
            fid=fopen([ruta,nombrearchivo]);
            evento=textscan(fid,'%s%s%s%s%d%s%s%s%s%s%s%s%s%s',1,'Delimiter',',');
            fclose(fid);
        else
            fid=fopen(['.\',handles.modelo,'\Eventos\',nombrearchivo,'.eve']);
            evento=textscan(fid,'%s%s%s%s%d%s%s%s%s%s%s%s%s%s',1,'Delimiter',',');
            fclose(fid);
        end
        intermedio=evento{1};
        handles.evento.nombre=intermedio{1};

        intermedio=evento{2};
        handles.evento.modelo=intermedio{1};

        intermedio=evento{3};
        handles.evento.comienzo=intermedio{1};

        intermedio=evento{4};
        handles.evento.final=intermedio{1};

        intermedio=evento{5};
        handles.evento.dmin=intermedio;

%         intermedio=evento{6};
%         handles.evento.dmax=intermedio;

        intermedio=evento{6};
        handles.evento.cond{1}=intermedio{1};

        intermedio=evento{7};
        handles.evento.cond{2}=intermedio{1};

        intermedio=evento{8};
        handles.evento.cond{3}=intermedio{1};

        intermedio=evento{9};
        handles.evento.cond{4}=intermedio{1};

        intermedio=evento{10};
        handles.evento.cond{5}=intermedio{1};

        intermedio=evento{11};
        handles.evento.cond{6}=intermedio{1};

        intermedio=evento{12};
        handles.evento.cond{7}=intermedio{1};

        intermedio=evento{13};
        handles.evento.cond{8}=intermedio{1};

        intermedio=evento{14};
        handles.evento.combinacion=intermedio{1};

%assignin('base','evento',handles.evento);
        if strcmpi(handles.evento.modelo,handles.modelo)
            
            handles.comienzo=handles.evento.comienzo;
            set(handles.editcomienzo,'String',handles.evento.comienzo);
            handles.final=handles.evento.final;
            set(handles.editfinal,'String',handles.evento.final);
            handles.dmin=handles.evento.dmin;
            set(handles.editdmin,'String',num2str(handles.evento.dmin));
%             handles.dmax=handles.evento.dmax;
%             set(handles.editdmax,'String',num2str(handles.evento.dmax));
            handles.combinacion=handles.evento.combinacion;
            set(handles.editcombi,'String',handles.evento.combinacion);
            handles.nombre=handles.evento.nombre;
            set(handles.editnombre,'String',handles.evento.nombre);
            
            for h=1:8
                eval(['set(handles.editcond',num2str(h),',''String'',handles.evento.cond{h})']);
            end
            
        else
            warndlg('El evento se corresponde con un modelo de avión distinto del actual.','Error de evento','modal');
        end
    catch error
        warndlg(['Error al cargar el evento ',nombrearchivo],'Error de evento','modal');
        handles.testeve=0;
    end
    
end


% --- Executes on button press in pushbuttondetectar.
function pushbuttondetectar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttondetectar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[handles,principiov,finalv]=detectar(handles);

if principiov~=-1
set(handles.editcomienzo,'String',num2str(principiov));
handles.evento.comienzo=num2str(principiov);
set(handles.editfinal,'String',num2str(finalv));
handles.evento.final=num2str(finalv);
end

guidata(hObject,handles);
        
function [handles,principiov,finalv]=detectar(handles)
test=0;
principiov=0;
finalv=0;
for i=1:handles.N
    if strcmp('PA1',handles.listapnecargadas{i,1})
        test=i;
        break
    end
end
if test==0
    uiwait(warndlg('La variable PA1 no se encuentra en los datos. No se puede realizar la detección.', 'Error de evento','modal'));
    principiov=-1;
    finalv=-1;
else
    altura=handles.datos(2:handles.M+1,test);
    
    %%Detección de un punto del vuelo%%
    test2=0;
    vuelo=0;
    tierra=mean(altura(1:500));
    for j=1:handles.M
        if altura(j)>tierra+100
            test2=test2+1;
        else
            test2=0;
            if vuelo==1;
                finalv=j;
                break
            end
        end
        if test2==600
            principiov=j-600;
            vuelo=1;
        end
    end
    if (vuelo==1)&&(finalv==0)
        finalv=handles.M;
    end
end



function editcadena_Callback(hObject, eventdata, handles)
% hObject    handle to editcadena (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editcadena as text
%        str2double(get(hObject,'String')) returns contents of editcadena as a double

handles.cadena=get(handles.editcadena,'String');
[handles]=actualizartabla(handles);
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editcadena_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editcadena (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in checkboxcargadas.
function checkboxcargadas_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxcargadas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkboxcargadas

handles.solocargadas=get(handles.checkboxcargadas,'Value');
[handles]=actualizartabla(handles);
guidata(hObject,handles);

function [handles]=actualizartabla(handles)

handles.tablafiltrada=[handles.cargadastabla,handles.listapne,handles.listacomp,handles.posibilidadestabla]; %La llenamos al completo antes de filtrar

if handles.solocargadas==1 %Quitamos las no cargadas si el check está marcado
    for i=handles.P:-1:1
        if handles.cargadas(i)==0
            handles.tablafiltrada(i,:)=[];
        end
    end
end

[Q,inutil]=size(handles.tablafiltrada);%Tamaño restante

if isempty(handles.cadena)==0
    for j=Q:-1:1
        matches1=regexpi(handles.tablafiltrada(j,2),handles.cadena); %Buscamos la cadena en la lista pne y en los nombres completos
        matches2=regexpi(handles.tablafiltrada(j,3),handles.cadena);
        if isempty(matches1{1})&&isempty(matches2{1})
            handles.tablafiltrada(j,:)=[];
        end
    end
end

set(handles.uitablevariables,'Data',handles.tablafiltrada);


% --------------------------------------------------------------------
function Ayuda_Callback(hObject, eventdata, handles)
% hObject    handle to Ayuda (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function ayudage_Callback(hObject, eventdata, handles)
% hObject    handle to ayudage (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
web AyudaGE.htm
