function varargout = NADv03b(varargin)
% NADv03b M-file for NADv03b.fig
%      NADv03b, by itself, creates a new NADv03b or raises the existing
%      singleton*.
%
%      H = NADv03b returns the handle to a new NADv03b or the handle to
%      the existing singleton*.
%
%      NADv03b('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in NADv03b.M with the given input arguments.
%
%      NADv03b('Property','Value',...) creates a new NADv03b or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before NADv03b_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property
%      application
%      stop.  All inputs are passed to NADv03b_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 NADv03b

% Last Modified by GUIDE v2.5 27-Jun-2011 03:57:42

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @NADv03b_OpeningFcn, ...
                   'gui_OutputFcn',  @NADv03b_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 NADv03b is made visible.
function NADv03b_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 NADv03b (see VARARGIN)

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

handles.rutaD=varargin{1};
modelo=varargin{2};
handles.modelo=modelo{1};
handles.analisis=varargin{3};
handles.nombreperfil=varargin{4};

%%%%%%%%%%%% CASO ANÁLISIS NUEVO %%%%%%%%%%%%%%%%%%%%%%
if handles.analisis==0
    testruta=1;
    try
        load(handles.rutaD{1});
    catch error
        warndlg('Archivo de datos no encontrado.','Error de lectura','modal');
        testruta=0;
    end

    if testruta==1
        handles.D=D;
        [handles.M,handles.N]=size(handles.D);
        handles.M=handles.M-1;
        
        pasosruta=textscan(handles.rutaD{1},'%s',30,'Delimiter','\\');
        pasosruta=pasosruta{1};
        [numpasos,inutil]=size(pasosruta);
        handles.nombreop=pasosruta{numpasos};
        
        handles.zoom.centro=handles.M/2;
        handles.zoom.rango=1;
        handles.zoom.Min=1;
        handles.zoom.Max=handles.M;
        handles.pintarnum=zeros(0);
        handles.pintardis=zeros(0);
        handles.neventos=0;
        handles.listaeventos=cell(1);
        handles.grafeventos=zeros(1);
        handles.rescomb=cell(0);
        handles.rescombgrp=cell(0);
        handles.tablaeventos=cell(0);
        handles.nev=1;
    
        set(handles.sliderpan,'Min',(handles.zoom.Max-handles.zoom.Min)/2);
        set(handles.sliderpan,'Max',handles.M-(handles.zoom.Max-handles.zoom.Min)/2+0.00001);
    
        handles.variables=zeros(0);
        handles.posdat=zeros(0);
        handles.tipovar=zeros(0);

        handles.tablaGV=cell(0,2);
        handles.tablaGV2=cell(0,2);
        [handles]=actualizarGV(handles);
        
        handles.varup1=0;
        handles.varup2=0;
        handles.varup3=0;
        handles.varup4=0;
        handles.vardo1=0;
        handles.vardo2=0;
        handles.vardo3=0;
        handles.vardo4=0;
        
        handles.YlimN=[0 10];
        handles.YlimR=[0 10];
        handles.YlimA=[0 10];
        handles.YlimV=[0 10];
        
        handles.gridyN=0;
        handles.gridyR=0;
        handles.gridx=0;
    
        [handles.dicc,inutil]=importdic(handles.modelo);
        
        %Se detectan los valores max y min de las variables
        [handles]=detectmaxmin(handles); %se crea handles.maxmin
                                         %q es una matriz de 
                                         %(variables en dicc,2)
        set(handles.textvar1,'String','');
        set(handles.textvar2,'String','');
        set(handles.textvar3,'String','');
        set(handles.textvar4,'String','');
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%% CASO CARGA DE ANÁLISIS%%%%%%%%%%%%%%%%%%%%
if handles.analisis~=0
    
    fid=fopen(handles.analisis); %escaneamos el archivo de análisis
    intermedio=textscan(fid,'%s%s%s%d%d%d','Delimiter',',');
    fclose(fid);
    
    intermedio2=intermedio{1};  %nombre del archivo con los datos de
    datosanalisis=intermedio2{1}; %análisis
    
    intermedio2=intermedio{2}; %ruta a los datos de operación (es la que
    handles.rutaD=intermedio2; %se toma como válida)
    
    intermedio2=intermedio{3}; %modelo, para poder acceder a la carpeta
    modelo=intermedio2{1};   %correcta de análisis
    
    directrabajo=cd; %cargamos los datos de análisis
    cd(['.\',modelo,'\Analisis\']); %tienen que estar en la carpeta
    load(datosanalisis);            %\Análisis\
    cd(directrabajo);
    
    %Comprobamos la ruta a los datos de operación (rutaD):
    testruta=1;
    ruta=handles.rutaD{1};
    try %Posibilidad 1
        load(ruta);
    catch error
        testruta=0;
    end
    
    if testruta==0
        testruta=1;
        try %Posibilidad 2
            pasosruta=textscan(ruta,'%s',30,'Delimiter','\\');
            pasosruta=pasosruta{1};
            [numpasos,inutil]=size(pasosruta);
            nombreop2=pasosruta{numpasos}; %cogemos la última palabra de la
            directrabajo=cd;              %ruta y la buscamos en la
            cd(['.\',modelo,'\Operaciones\']);% carpeta de operaciones
            load(nombreop2);
            cd(directrabajo);
        catch error
            testruta=0;
            warndlg('Archivo de datos no encontrado.','Error de lectura','modal');
            error('Archivo de datos no encontrado.')
        end
    end
        
    handles.D=D; handles.modelo=modelo; handles.M=M; handles.N=N; handles.zoom.centro=zoomcentro;
    handles.zoom.rango=zoomrango; handles.pintarnum=pintarnum; handles.pintardis=pintardis; handles.dicc=dicc; handles.neventos=neventos;
    handles.listaeventos=listaeventos; handles.rescomb=rescomb; handles.rescombgrp=rescombgrp; handles.tablaeventos=tablaeventos;
    handles.variables=variables; handles.posdat=posdat; handles.tipovar=tipovar; handles.tablaGV=tablaGV; handles.tablaGV2=tablaGV2;
    handles.grafeventos=grafeventos; 
    handles.YlimN=ylimn; handles.YlimR=ylimr; handles.YlimA=ylima; handles.YlimV=ylimv; handles.maxmin=maxmin;
    
    handles.nev=1;
    handles.gridyN=gridyN; handles.gridyR=gridyR; handles.gridx=gridx;
    
    handles.varup1=varup1; handles.varup2=varup2; handles.varup3=varup3; handles.varup4=varup4;
    handles.vardo1=vardo1; handles.vardo2=vardo2; handles.vardo3=vardo3; handles.vardo4=vardo4;
    
    handles.nombreop=nombreop;
    
    set(handles.uitableGV,'Data',tablaGV);
    set(handles.uitableGV2,'Data',tablaGV2);
    
    set(handles.editMinN,'String',num2str(ylimn(1)));
    set(handles.editMinR,'String',num2str(ylimr(1)));
    set(handles.editMinA,'String',num2str(ylima(1)));
    set(handles.editMinV,'String',num2str(ylimv(1)));
    set(handles.editMaxN,'String',num2str(ylimn(2)));
    set(handles.editMaxR,'String',num2str(ylimr(2)));
    set(handles.editMaxA,'String',num2str(ylima(2)));
    set(handles.editMaxV,'String',num2str(ylimv(2)));
    
    set(handles.sliderpan,'Min',slidermin);
    set(handles.sliderpan,'Max',slidermax);
            
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%CASO APLICACIÓN DE PERFIL%%%%%%%%%%%%%%%%%%%

if handles.nombreperfil~=0
    try
        fid=fopen(['.\',handles.modelo,'\Perfiles\',handles.nombreperfil]);
        perfil=textscan(fid,'%s%s%s%s%s%s%s%s%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d',1,'Delimiter',',');
        fclose(fid);
        
        intermedio=perfil{2};
    catch error
        warndlg('Formato no válido. No se puedo cargar el archivo de perfil.','Error de perfil','modal');
    end
    if strcmp(intermedio{1},handles.modelo)==0
        warndlg('El perfil se corresponde con un modelo de avión distinto del actual.','Error de perfil','modal');
    else
        intermedio=perfil{1};
        handles.perfil.perfil=intermedio{1};
        
        intermedio=perfil{3};
        handles.perfil.set=intermedio{1};
        
        intermedio=perfil{4};
        handles.perfil.evento1=intermedio{1};
        
        intermedio=perfil{5};
        handles.perfil.evento2=intermedio{1};
        
        intermedio=perfil{6};
        handles.perfil.evento3=intermedio{1};
        
        intermedio=perfil{7};
        handles.perfil.evento4=intermedio{1};
        
        intermedio=perfil{8};
        handles.perfil.evento5=intermedio{1};
        
        handles.perfil.grafeve(1,1)=perfil{9};
        handles.perfil.grafeve(1,2)=perfil{10};
        handles.perfil.grafeve(1,3)=perfil{11};
        handles.perfil.grafeve(2,1)=perfil{12};
        handles.perfil.grafeve(2,2)=perfil{13};
        handles.perfil.grafeve(2,3)=perfil{14};
        handles.perfil.grafeve(3,1)=perfil{15};
        handles.perfil.grafeve(3,2)=perfil{16};
        handles.perfil.grafeve(3,3)=perfil{17};
        handles.perfil.grafeve(4,1)=perfil{18};
        handles.perfil.grafeve(4,2)=perfil{19};
        handles.perfil.grafeve(4,3)=perfil{20};
        handles.perfil.grafeve(5,1)=perfil{21};
        handles.perfil.grafeve(5,2)=perfil{22};
        handles.perfil.grafeve(5,3)=perfil{23};
        
        %%GV%%
        [nuevasvar,nuevaspos,nuevotipo]=GVv1(handles.D,handles.modelo,handles.dicc,handles.variables,handles.posdat,handles.perfil.set);
        
        if nuevasvar==-1
        else
            handles.variables=nuevasvar;
            handles.posdat=nuevaspos;
            handles.tipovar=nuevotipo;
            [handles]=actualizarGV(handles);
        end
        %%%%%%
        %%GE%%
        datoseventos{1}=handles.listaeventos;
        datoseventos{2}=handles.grafeventos;
        datoseventos{3}=handles.rescomb;
        datoseventos{4}=handles.rescombgrp;
        datoseventos{5}=handles.tablaeventos;
        datoseventos{6}=handles.neventos;

        [datoseventos]=GEv1(handles.D,handles.modelo,datoseventos,handles.perfil);
       
        if iscell(datoseventos)
            handles.listaeventos=datoseventos{1};
            handles.grafeventos=datoseventos{2};
            handles.rescomb=datoseventos{3};
            handles.rescombgrp=datoseventos{4};
            handles.tablaeventos=datoseventos{5};
            handles.neventos=datoseventos{6};
        end
        %%%%%%
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%Título ventana%%%
set(handles.textoperacion,'String',handles.nombreop);
set(handles.textmodelo,'String',handles.modelo);
%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%IMAGEN MODELO%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% switch handles.modelo
%     case 'C-295'
%         fondo=importdata('.\buttons\botonC295peq.jpg');
%     case 'C-235'
%         fondo=importdata('.\buttons\botonC235peq.jpg');
%     case 'C-235DW'
%         fondo=importdata('.\buttons\botonCN235peq.jpg');
%     case 'A400M'
%         fondo=importdata('.\buttons\botonA400Mpeq.jpg');
% end
% axes(handles.axesmodelo);
% image(fondo);
% axis off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%CONFIGURACIÓN GRÁFICAS%%%%%%%%%%%%%%%%%%%%%
handles.datacursor=datacursormode(handles.figureNAD);
set(handles.datacursor,'Enable','off');
set(get(get(handles.datacursor,'UIContextMenu'),'Children'),'Visible','off');


% set(handles.popupmenueventos,'String',handles.listaeventos);
% set(handles.uitableeventos,'Data',handles.tablaeventos);

handles.notacion=0;
set(handles.menunotacion,'Label','Activar notación científica');
set(handles.menuleyenda,'Label','Desactivar leyenda');
uistack(handles.uipanelleyenda,'top');

set(handles.popupmenudatacursor,'String',{'N';'R';'A';'V'});

handles.autozN=0;
handles.autozR=0;
handles.autozA=0;
handles.autozV=0;
handles.ZpordefN=0;
handles.ZpordefR=0;
handles.ZpordefA=0;
handles.ZpordefV=0;

[handles]=pinta(handles);
handles=refresca(handles);


%get(handles.pushbuttonzoomout,'Extent');
%set(handles.pushbuttonzoomout,'Extent',
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes NADv03b wait for user response (see UIRESUME)
uiwait(handles.figureNAD);

% --- Outputs from this function are returned to the command line.
function varargout = NADv03b_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.output;
delete(gcf)


% --- Executes on slider movement.
function sliderpan_Callback(hObject, eventdata, handles)
% hObject    handle to sliderpan (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

centro=get(hObject,'Value');
handles.zoom.centro=centro;
handles=refresca(handles);
handles=actualizarstack(handles);
guidata(hObject, handles);

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

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


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

incvista=0.1*(handles.zoom.Max-handles.zoom.Min);
Min=handles.zoom.Min+incvista;
Max=handles.zoom.Max-incvista;

handles.zoom.centro=(Min+Max)/2;
handles.zoom.rango=(Max-Min)/handles.M;

set(handles.sliderpan,'Min',(Max-Min)/2);
set(handles.sliderpan,'Max',handles.M-(Max-Min)/2);

handles=refresca(handles);
handles=actualizarstack(handles);
guidata(hObject, handles);

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

incvista=0.1*(handles.zoom.Max-handles.zoom.Min);
Min=handles.zoom.Min-incvista;
Max=handles.zoom.Max+incvista;

if Min<1&&Max<handles.M
    Min=1;
    Max=Max+incvista;
    if Max>handles.M
        Max=handles.M;
    end
elseif Min>1&&Max>handles.M
    Min=Min-incvista;
    Max=handles.M;
    if Min<1
        Min=1;
    end
elseif Min<1&&Max>handles.M
    Min=1;
    Max=handles.M;
end
handles.zoom.centro=(Min+Max)/2;
handles.zoom.rango=(Max-Min)/handles.M;

set(handles.sliderpan,'Min',(Max-Min)/2);
set(handles.sliderpan,'Max',handles.M-(Max-Min)/2);

handles=refresca(handles);
handles=actualizarstack(handles);
guidata(hObject, handles);


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

[nuevasvar,nuevaspos,nuevotipo]=GVv1(handles.D,handles.modelo,handles.dicc,handles.variables,handles.posdat,0);

if nuevasvar==-1
else
    handles.variables=nuevasvar;
    handles.posdat=nuevaspos;
    handles.tipovar=nuevotipo;
    %%%%%%%%se borran las gráficas siempre que se cambian las variables%%%%
    testborrar=zeros(1,4);
    [handles]=borrargrafnum(handles,testborrar);
    [handles]=borrargrafdis(handles,testborrar);
    
    handles.varup1=0;
    handles.varup2=0;
    handles.varup3=0;
    handles.varup4=0;
    handles.vardo1=0;
    handles.vardo2=0;
    handles.vardo3=0;
    handles.vardo4=0;
    
    [handles]=refresca(handles);
    [handles]=actualizarGV(handles);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

guidata(hObject,handles);

function [handles]=actualizarGV(handles)

%%%%%%%%%%%% Refresco de las tablas%%%%%%%%%%%%%%%%%%%%%%
    [inutil,L]=size(handles.variables);
    tablaGV=cell(1,12);
    tablaGV2=cell(1,12);
    handles.pintarnum=zeros(0);
    handles.pintardis=zeros(0);
    z=1;
    x=1;
    for i=1:L
        if handles.tipovar(i)==0
            intermedio=handles.dicc{8}(handles.variables(i));
            tablaGV{z,1}=intermedio{1};
            
            tablaGV{z,2}=false;
            tablaGV{z,3}=false;
            tablaGV{z,4}=false;
            tablaGV{z,5}=false;
                
            intermedio=handles.dicc{3}(handles.variables(i));
            tablaGV{z,6}=intermedio{1};
      
            tablaGV{z,7}=handles.dicc{4}(handles.variables(i));
        
            tablaGV{z,8}=handles.posdat(i);
        
            tablaGV{z,9}=handles.variables(i);
    
            intermedio=handles.dicc{5}(handles.variables(i));
            tablaGV{z,10}=intermedio{1};
    
            intermedio=handles.dicc{6}(handles.variables(i));
            tablaGV{z,11}=intermedio{1};
    
            intermedio=handles.dicc{7}(handles.variables(i));
            tablaGV{z,12}=intermedio{1};
            
            handles.pintarnum(z,1)=handles.posdat(i);
            handles.pintarnum(z,2)=handles.variables(i);
            
            z=z+1;
        else
            intermedio=handles.dicc{8}(handles.variables(i));
            tablaGV2{x,1}=intermedio{1};            
            
            tablaGV2{x,2}=false;
            tablaGV2{x,3}=false;
            tablaGV2{x,4}=false;
            tablaGV2{x,5}=false;
    
            intermedio=handles.dicc{3}(handles.variables(i));
            tablaGV2{x,6}=intermedio{1};
      
            tablaGV2{x,7}=handles.dicc{4}(handles.variables(i));
        
            tablaGV2{x,8}=handles.posdat(i);
        
            tablaGV2{x,9}=handles.variables(i);
    
            intermedio=handles.dicc{5}(handles.variables(i));
            tablaGV2{x,10}=intermedio{1};
    
            intermedio=handles.dicc{6}(handles.variables(i));
            tablaGV2{x,11}=intermedio{1};
    
            intermedio=handles.dicc{7}(handles.variables(i));
            tablaGV2{x,12}=intermedio{1};
            
            handles.pintardis(x,1)=handles.posdat(i);
            handles.pintardis(x,2)=handles.variables(i);
            
            x=x+1;
        end
    end
    set(handles.uitableGV,'Data',tablaGV);
    set(handles.uitableGV2,'Data',tablaGV2);
if z==1
    tablaGV=cell(0,2);
    set(handles.uitableGV,'Data',tablaGV);
end
if x==1
    tablaGV2=cell(0,2);
    set(handles.uitableGV2,'Data',tablaGV2);
end

handles.tablaGV=tablaGV;
handles.tablaGV2=tablaGV2;

% handles.pintarnum
% handles.pintardis

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function editira_Callback(hObject, eventdata, handles)
% hObject    handle to editira (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 editira as text
%        str2double(get(hObject,'String')) returns contents of editira as a double
centro=str2double(get(hObject,'String'));
centromax=handles.M-handles.zoom.rango*handles.M/2;
centromin=1+handles.zoom.rango*handles.M/2;
if centro>centromax
    centro=centromax;
end
if centro<centromin
    centro=centromin;
end
handles.zoom.centro=centro;
handles=refresca(handles);
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editira_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editira (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 figureNAD.
function figureNAD_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figureNAD (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

uiresume(handles.figureNAD);


function [handles]=refresca(handles)

%[handles]=pinta(handles);

%%%%%%%%%%%%%%CONFIGURACIÓN DE EJES%%%%%%%%%%%%%%%%%%%
cfig = get(gcf,'color');
posup=get(handles.axesup1,'Position');
posdo=get(handles.axesdo1,'Position');
des=0.041;
desv=0.09;
uistack(handles.axesup1,'top');
uistack(handles.axesup4,'bottom');
uistack(handles.axesdox,'bottom');
set(handles.axesup1,'Color','None','Box','off');
set(handles.axesup2,'Color','none','xtick',[],'XColor',cfig,'yaxislocation','right','YColor','r','Position',posup,'Box','off');
set(handles.axesup3,'Color','none','xtick',[],'XColor',cfig,'ytick',[],'YColor',cfig,'Position',posup,'Box','off');
set(handles.axesup3bis,'Color','none','xtick',[],'XColor',cfig,'YColor','b','Position',posup-[des 0 0 0],'Box','off');
set(handles.axesup4,'Color','w','xtick',[],'XColor',cfig,'ytick',[],'YColor',cfig,'yaxislocation','right','Position',posup,'Box','off');
set(handles.axesup4bis,'Color','none','xtick',[],'XColor',cfig,'yaxislocation','right','YColor',[0,0.5,0],'Position',posup+[des 0 0 0],'Box','off');

set(handles.axesdo1,'Color','none','xtick',[],'yaxislocation','right','Box','off','YGrid','on');
set(handles.axesdo2,'Color','none','xtick',[],'XColor',cfig,'YColor','r','Position',posdo+[0 desv 0 0],'Box','off','YGrid','on');
set(handles.axesdo3,'Color','none','xtick',[],'XColor',cfig,'YColor','b','Position',posdo+[0 0 0 0],'yaxislocation','right','Box','off','YGrid','on');
set(handles.axesdo4,'Color','none','xtick',[],'XColor',cfig,'YColor',[0,0.5,0],'Position',posdo+[0 0 0 0],'Box','off','YGrid','on');
set(handles.axesdox,'YColor',cfig,'Position',posdo+[0 0 0 posdo(4)],'Box','off','ytick',[]);

set(handles.axesev,'Color','none','xtick',[],'XColor',cfig,'YColor',cfig,'Box','off');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%% Límites en X %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Xlim(1)=handles.zoom.centro-handles.zoom.rango*handles.M/2;
Xlim(2)=handles.zoom.centro+handles.zoom.rango*handles.M/2;

handles.zoom.Min=Xlim(1);
handles.zoom.Max=Xlim(2);

s=handles.zoom.rango/(1-handles.zoom.rango);
if s<1&&s>0
set(handles.sliderpan,'SliderStep',[0.05 0.5].*s);
end
    
set(handles.sliderpan,'Value',handles.zoom.centro);

set(handles.axesup1,'Xlim',Xlim);
set(handles.axesup2,'Xlim',Xlim);
set(handles.axesup3,'Xlim',Xlim);
set(handles.axesup4,'Xlim',Xlim);

set(handles.axesdo1,'Xlim',Xlim);
set(handles.axesdo2,'Xlim',Xlim);
set(handles.axesdo3,'Xlim',Xlim);
set(handles.axesdo4,'Xlim',Xlim);
set(handles.axesdox,'Xlim',Xlim);

set(handles.axesev,'Xlim',Xlim);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%Límites en Y%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if handles.ZpordefN==1
    [nvar,inutil]=size(handles.tablaGV);
    
    for i=nvar:-1:1
        if handles.tablaGV{i,2}==true
            poseneldicc=handles.pintarnum(i,2);
            handles.YlimN(1)=handles.maxmin(poseneldicc,1);
            handles.YlimN(2)=handles.maxmin(poseneldicc,2);
            break
        end
    end

    set(handles.axesup1,'Ylim',handles.YlimN);
    set(handles.editMinN,'String',handles.YlimN(1));
    set(handles.editMaxN,'String',handles.YlimN(2));
    handles.ZpordefN=0;
    
    
elseif handles.autozN==0
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,2}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinN,'String','');
        set(handles.editMaxN,'String','');
    else
        set(handles.axesup1,'Ylim',handles.YlimN);
    end
else
    [nvar,inutil]=size(handles.tablaGV);
    test=0;    
    for i=nvar:-1:1
        if handles.tablaGV{i,2}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinN,'String','');
        set(handles.editMaxN,'String','');
    else
        handles.YlimN=get(handles.axesup1,'Ylim');
        set(handles.editMinN,'String',handles.YlimN(1));
        set(handles.editMaxN,'String',handles.YlimN(2));
    end
    handles.autozN=0;
end
%%%%%%%%%%%%%%%
if handles.ZpordefR==1
    [nvar,inutil]=size(handles.tablaGV);

    for i=nvar:-1:1
        if handles.tablaGV{i,3}==true
            poseneldicc=handles.pintarnum(i,2);
            handles.YlimR(1)=handles.maxmin(poseneldicc,1);
            handles.YlimR(2)=handles.maxmin(poseneldicc,2);
            break
        end
    end
    
    set(handles.axesup2,'Ylim',handles.YlimR);
    set(handles.editMinR,'String',handles.YlimR(1));
    set(handles.editMaxR,'String',handles.YlimR(2));
    handles.ZpordefR=0;
    
elseif handles.autozR==0
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,3}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinR,'String','');
        set(handles.editMaxR,'String','');
    else
        set(handles.axesup2,'Ylim',handles.YlimR);
    end
else
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,3}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinR,'String','');
        set(handles.editMaxR,'String','');
    else
        handles.YlimR=get(handles.axesup2,'Ylim');
        set(handles.editMinR,'String',handles.YlimR(1));
        set(handles.editMaxR,'String',handles.YlimR(2));
    end
    handles.autozR=0;
end
%%%%%%%%%%%%%%%
if handles.ZpordefA==1
    [nvar,inutil]=size(handles.tablaGV);

    for i=nvar:-1:1
        if handles.tablaGV{i,4}==true
            poseneldicc=handles.pintarnum(i,2);
            handles.YlimA(1)=handles.maxmin(poseneldicc,1);
            handles.YlimA(2)=handles.maxmin(poseneldicc,2);
            break
        end
    end
    
    set(handles.axesup3,'Ylim',handles.YlimA);
    set(handles.axesup3bis,'Ylim',handles.YlimA);
    set(handles.editMinA,'String',handles.YlimA(1));
    set(handles.editMaxA,'String',handles.YlimA(2));
    handles.ZpordefA=0;
    
elseif handles.autozA==0
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,4}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinA,'String','');
        set(handles.editMaxA,'String','');
    else
        set(handles.axesup3,'Ylim',handles.YlimA);
        set(handles.axesup3bis,'Ylim',handles.YlimA);
    end

else
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,4}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinA,'String','');
        set(handles.editMaxA,'String','');
    else
        handles.YlimA=get(handles.axesup3,'Ylim');
        set(handles.editMinA,'String',handles.YlimA(1));
        set(handles.editMaxA,'String',handles.YlimA(2));
        set(handles.axesup3bis,'Ylim',handles.YlimA);
    end
    handles.autozA=0;
end
%%%%%%%%%%%%%%%
if handles.ZpordefV==1
    [nvar,inutil]=size(handles.tablaGV);

    for i=nvar:-1:1
        if handles.tablaGV{i,5}==true
            poseneldicc=handles.pintarnum(i,2);
            handles.YlimV(1)=handles.maxmin(poseneldicc,1);
            handles.YlimV(2)=handles.maxmin(poseneldicc,2);
            break
        end
    end
    
    set(handles.axesup4,'Ylim',handles.YlimV);
    set(handles.axesup4bis,'Ylim',handles.YlimV);
    set(handles.editMinV,'String',handles.YlimV(1));
    set(handles.editMaxV,'String',handles.YlimV(2));
    handles.ZpordefV=0;
    
elseif handles.autozV==0
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,5}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinV,'String','');
        set(handles.editMaxV,'String','');
    else
        set(handles.axesup4,'Ylim',handles.YlimV);
        set(handles.axesup4bis,'Ylim',handles.YlimV);
    end
else
    
    [nvar,inutil]=size(handles.tablaGV);
    test=0;
    for i=nvar:-1:1
        if handles.tablaGV{i,5}==true
            test=1;
            break
        end
    end
    if test==0
        set(handles.editMinV,'String','');
        set(handles.editMaxV,'String','');
        %PONER TB HANDLES YLIM A [0 1] para salir de probs
    else
        handles.YlimV=get(handles.axesup4,'Ylim');
        set(handles.editMinV,'String',handles.YlimV(1));
        set(handles.editMaxV,'String',handles.YlimV(2));
        set(handles.axesup4bis,'Ylim',handles.YlimV);
    end
    handles.autozV=0;
end

%Notación científica
if handles.notacion==0
    set(handles.axesup1,'yticklabel',num2str(get(handles.axesup1,'ytick')'));
    set(handles.axesup2,'yticklabel',num2str(get(handles.axesup2,'ytick')'));
    set(handles.axesup3bis,'yticklabel',num2str(get(handles.axesup3bis,'ytick')'));
    set(handles.axesup4bis,'yticklabel',num2str(get(handles.axesup4bis,'ytick')'));
    set(handles.axesup1,'xticklabel',num2str(get(handles.axesup1,'xtick')'));
    
    set(handles.axesdo1,'xticklabel',num2str(get(handles.axesdo1,'xtick')'));
    
end

function [handles]=pinta(handles)
%%%%%%%GRÁFICA NUMÉRICA%%%%%%%%
tablanum=get(handles.uitableGV,'Data');
testborrar=zeros(1,4);

if isempty(handles.pintarnum)==0
    [L,inutil]=size(handles.pintarnum);
    for z=1:L
        if tablanum{z,2}==true;
            plot(handles.axesup1,1:handles.M,handles.D(2:handles.M+1,handles.pintarnum(z,1)),'k');
            testborrar(1,1)=1;
        end
        if tablanum{z,3}==true
            plot(handles.axesup2,1:handles.M,handles.D(2:handles.M+1,handles.pintarnum(z,1)),'r');
            testborrar(1,2)=1;
        end
        if tablanum{z,4}==true
            plot(handles.axesup3,1:handles.M,handles.D(2:handles.M+1,handles.pintarnum(z,1)),'b');
            testborrar(1,3)=1;
            set(handles.axesup3bis,'YLimMode','Manual');
            Ylim3=get(handles.axesup3,'Ylim');
            set(handles.axesup3bis,'YLim',Ylim3);
        end
        if tablanum{z,5}==true
            plot(handles.axesup4,1:handles.M,handles.D(2:handles.M+1,handles.pintarnum(z,1)),'Color',[0,0.5,0]);
            testborrar(1,4)=1;
            set(handles.axesup4bis,'YLimMode','Manual');
            Ylim4=get(handles.axesup4,'Ylim');
            set(handles.axesup4bis,'YLim',Ylim4);
        end
        
    end
    
    [handles]=borrargrafnum(handles,testborrar);
 
end

%%%%GRÁFICA DISCRETA%%%%

tabladis=get(handles.uitableGV2,'Data');
testborrar2=zeros(1,4);
if isempty(handles.pintardis)==0
    [K,inutil]=size(handles.pintardis);
      
        
    for x=1:K
        etiquetas=cell(1,1);
        cad=handles.dicc{7}(handles.pintardis(x,2)); %cadena de posibilidades separadas por barras
        cad=cad{1};
        posibilidades=cell(1);
        posibilidades=textscan(cad,'%s',15,'Delimiter','/');
        [numpos,inutil]=size(posibilidades{1});
        for h=1:numpos
            try
                etiquetas(1,h)=lower(posibilidades{1}(h));
            end
        end
        
        Ylimdis(1)= 1-0.1*numpos;         
        Ylimdis(2)= 1.1*numpos;
        
        if tabladis{x,2}==true;
            plot(handles.axesdo1,1:handles.M,handles.D(2:handles.M+1,handles.pintardis(x,1)),'k');
            testborrar2(1,1)=1;
            set(handles.axesdo1,'YLimMode','Manual');      
            
            if numpos>5
                set(handles.axesdo1,'FontSize',7.5)
            end
            if numpos>7
                set(handles.axesdo1,'FontSize',6)
            end
            
            set(handles.axesdo1,'YLim',Ylimdis);
            set(handles.axesdo1,'YTick',1:numpos);
            set(handles.axesdo1,'YTickLabel',etiquetas);
        end
        if tabladis{x,3}==true
            plot(handles.axesdo2,1:handles.M,handles.D(2:handles.M+1,handles.pintardis(x,1)),'r');
            testborrar2(1,2)=1;
            set(handles.axesdo2,'YLimMode','Manual');            
            
            if numpos>5
                set(handles.axesdo2,'FontSize',7.5)
            end
            if numpos>7
                set(handles.axesdo2,'FontSize',6)
            end
            
            set(handles.axesdo2,'YLim',Ylimdis);
            set(handles.axesdo2,'YTick',1:numpos);
            set(handles.axesdo2,'YTickLabel',etiquetas);
        end
%         if tabladis{x,4}==true
%             plot(handles.axesdo3,1:handles.M,handles.D(2:handles.M+1,handles.pintardis(x,1)),'b');
%             testborrar2(1,3)=1;
%             set(handles.axesdo3,'YLimMode','Manual');            
%             
%             if numpos>5
%                 set(handles.axesdo3,'FontSize',7.5)
%             end
%             if numpos>7
%                 set(handles.axesdo3,'FontSize',6)
%             end
%             
%             set(handles.axesdo3,'YLim',Ylimdis);
%             set(handles.axesdo3,'YTick',1:numpos);
%             set(handles.axesdo3,'YTickLabel',etiquetas);
%         end
%         if tabladis{x,5}==true
%             plot(handles.axesdo4,1:handles.M,handles.D(2:handles.M+1,handles.pintardis(x,1)),'Color',[0,0.5,0]);
%             testborrar2(1,4)=1;
%             set(handles.axesdo4,'YLimMode','Manual');            
%             
%             if numpos>5
%                 set(handles.axesdo4,'FontSize',7.5)
%             end
%             if numpos>7
%                 set(handles.axesdo4,'FontSize',6)
%             end
%             
%             set(handles.axesdo4,'YLim',Ylimdis);
%             set(handles.axesdo4,'YTick',1:numpos);
%             set(handles.axesdo4,'YTickLabel',etiquetas);
%         end
%         
    end
    
[handles]=borrargrafdis(handles,testborrar2);

end

%%%%%%%%%%%%%%%%%GRÁFICA EVENTOS%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plot(handles.axesev,0,0);
hold(handles.axesev,'on');

for k=1:handles.neventos
    
    resultados=handles.tablaeventos{k};
    [U,inutil]=size(resultados);
    unos=ones(U,1);
    
    if handles.grafeventos(k,2)==1
        forma='.';
    elseif handles.grafeventos(k,2)==2
        forma='o';
    elseif handles.grafeventos(k,2)==3
        forma='x';
    elseif handles.grafeventos(k,2)==4
        forma='s';
    elseif handles.grafeventos(k,2)==5
        forma='^';
    end
    
    if handles.grafeventos(k,3)==1
        color='r';
    elseif handles.grafeventos(k,3)==2
        color='k';
    elseif handles.grafeventos(k,3)==3
        color='b';
    elseif handles.grafeventos(k,3)==4
        color='y';
    elseif handles.grafeventos(k,3)==5
        color='g';
    end
    
    propiedades=[color,forma];
    
    if handles.grafeventos(k,1)
        plot(handles.axesev,resultados(:,1),unos,propiedades,'MarkerSize',11);
    end
end
hold(handles.axesev,'off');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%%%%%%%% LEYENDA %%%%%%%%%%%
[nvar,inutil]=size(handles.tablaGV);    
    for i=nvar:-1:1
        if handles.tablaGV{i,2}==true
            set(handles.textvar1,'String',[handles.tablaGV{i,1},'(',handles.tablaGV{i,11},')']);
        break
        else
            set(handles.textvar1,'String','');
        end
    end
    
    for i=nvar:-1:1
        if handles.tablaGV{i,3}==true
            set(handles.textvar2,'String',[handles.tablaGV{i,1},'(',handles.tablaGV{i,11},')']);
        break
        else
            set(handles.textvar2,'String','');
        end
    end
    for i=nvar:-1:1
        if handles.tablaGV{i,4}==true
            set(handles.textvar3,'String',[handles.tablaGV{i,1},'(',handles.tablaGV{i,11},')']);
        break
        else
            set(handles.textvar3,'String','');
        end
    end
    for i=nvar:-1:1
        if handles.tablaGV{i,5}==true
            set(handles.textvar4,'String',[handles.tablaGV{i,1},'(',handles.tablaGV{i,11},')']);
        break
        else
            set(handles.textvar4,'String','');
        end
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
%%%%%REJILLA Y%%%%%%%%%%%%%%%%%
if handles.gridyN
    set(handles.rejillayN,'Label','Desactivar rejilla en N');
    set(handles.axesup1,'YGrid','on');
else
    set(handles.rejillayN,'Label','Activar rejilla en N');
    set(handles.axesup1,'YGrid','off');
end

onoff=get(handles.axesup2,'YGrid');
if handles.gridyR
    set(handles.rejillayR,'Label','Desactivar rejilla en R');
    set(handles.axesup2,'YGrid','on');
else
    set(handles.rejillayR,'Label','Activar rejilla en R');
    set(handles.axesup2,'YGrid','off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%REJILLA X%%%%%%%%%%%%%%%%%
if handles.gridx
    set(handles.rejillax,'Label','Desactivar rejilla en X');
    set(handles.axesup1,'XGrid','on');
    set(handles.axesdox,'XGrid','on');
else
    set(handles.rejillax,'Label','Activar rejilla en X');
    set(handles.axesup1,'XGrid','off');
    set(handles.axesdox,'XGrid','off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% --- Executes when entered data in editable cell(s) in uitableGV.
function uitableGV_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to uitableGV (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)
handles.tablaGV=get(handles.uitableGV,'Data');

%Detectamos cuáles entran nuevas
cambiada=eventdata.Indices;
[nvar,inutil]=size(handles.tablaGV);

if handles.tablaGV{cambiada(1,1),cambiada(1,2)}==true
    poseneldicc=handles.pintarnum(cambiada(1,1),2);
    if cambiada(1,2)==2 %La variable introducida va a la gráfica negra
        %Se rellena la estructura varup
        handles.varup1=struct;
        handles.varup1.posenGV=cambiada(1,1);
        handles.varup1.posendicc=poseneldicc;
        handles.varup1.nombreabr=handles.tablaGV{cambiada(1,1),1};
        handles.varup1.nombrecomp=handles.tablaGV{cambiada(1,1),6};
        handles.varup1.unidades=handles.tablaGV{cambiada(1,1),11};
        
        %Se limpian las que pudieran estar seleccionadas antes
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV{t,2}=false;
            end
        end
        
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefN=1;
        else
            handles.autozN=1;
        end
    end
    if cambiada(1,2)==3 %La variable introducida va a la gráfica roja
        
        handles.varup2=struct;
        handles.varup2.posenGV=cambiada(1,1);
        handles.varup2.posendicc=poseneldicc;
        handles.varup2.nombreabr=handles.tablaGV{cambiada(1,1),1};
        handles.varup2.nombrecomp=handles.tablaGV{cambiada(1,1),6};
        handles.varup2.unidades=handles.tablaGV{cambiada(1,1),11};
        
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV{t,3}=false;
            end
        end   
        
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefR=1;
        else
            handles.autozR=1;
        end
    end
    if cambiada(1,2)==4 %La variable introducida va a la gráfica azul
        
        handles.varup3=struct;
        handles.varup3.posenGV=cambiada(1,1);
        handles.varup3.posendicc=poseneldicc;
        handles.varup3.nombreabr=handles.tablaGV{cambiada(1,1),1};
        handles.varup3.nombrecomp=handles.tablaGV{cambiada(1,1),6};
        handles.varup3.unidades=handles.tablaGV{cambiada(1,1),11};
                
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV{t,4}=false;
            end
        end        
        
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefA=1;
        else
            handles.autozA=1;
        end
    end
    if cambiada(1,2)==5 %La variable introducida va a la gráfica verde
        
        handles.varup4=struct;
        handles.varup4.posenGV=cambiada(1,1);
        handles.varup4.posendicc=poseneldicc;
        handles.varup4.nombreabr=handles.tablaGV{cambiada(1,1),1};
        handles.varup4.nombrecomp=handles.tablaGV{cambiada(1,1),6};
        handles.varup4.unidades=handles.tablaGV{cambiada(1,1),11};
        
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV{t,5}=false;
            end
        end                
        
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefV=1;
        else
            handles.autozV=1;
        end
    end
    
    set(handles.uitableGV,'Data',handles.tablaGV);
    
else
    if cambiada(1,2)==2
        handles.varup1=0;
    elseif cambiada(1,2)==3
        handles.varup2=0;
    elseif cambiada(1,2)==4
        handles.varup3=0;
    elseif cambiada(1,2)==5
        handles.varup4=0;
    end
    
end


[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);


% --- Executes when entered data in editable cell(s) in uitableGV2.
function uitableGV2_CellEditCallback(hObject, eventdata, handles)
% hObject    handle to uitableGV2 (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)
handles.tablaGV2=get(handles.uitableGV2,'Data');

%Detectamos cuáles entran nuevas
cambiada=eventdata.Indices;
[nvar,inutil]=size(handles.tablaGV2);

if handles.tablaGV2{cambiada(1,1),cambiada(1,2)}==true
    poseneldicc=handles.pintardis(cambiada(1,1),2);
    if cambiada(1,2)==2 %La variable introducida va a la gráfica negra
        %Se rellena la estructura varup
        handles.vardo1=struct;
        handles.vardo1.posenGV=cambiada(1,1);
        handles.vardo1.posendicc=poseneldicc;
        handles.vardo1.nombreabr=handles.tablaGV2{cambiada(1,1),1};
        handles.vardo1.nombrecomp=handles.tablaGV2{cambiada(1,1),6};
        handles.vardo1.unidades=handles.tablaGV2{cambiada(1,1),11};
        
        %Se limpian las que pudieran estar seleccionadas antes
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV2{t,2}=false;
            end
        end
        
    end
    if cambiada(1,2)==3 %La variable introducida va a la gráfica roja
        
        handles.vardo2=struct;
        handles.vardo2.posenGV=cambiada(1,1);
        handles.vardo2.posendicc=poseneldicc;
        handles.vardo2.nombreabr=handles.tablaGV2{cambiada(1,1),1};
        handles.vardo2.nombrecomp=handles.tablaGV2{cambiada(1,1),6};
        handles.vardo2.unidades=handles.tablaGV2{cambiada(1,1),11};
        
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV2{t,3}=false;
            end
        end
        
    end
    if cambiada(1,2)==4 %La variable introducida va a la gráfica azul
        
        handles.vardo3=struct;
        handles.vardo3.posenGV=cambiada(1,1);
        handles.vardo3.posendicc=poseneldicc;
        handles.vardo3.nombreabr=handles.tablaGV2{cambiada(1,1),1};
        handles.vardo3.nombrecomp=handles.tablaGV2{cambiada(1,1),6};
        handles.vardo3.unidades=handles.tablaGV2{cambiada(1,1),11};
                
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV2{t,4}=false;
            end
        end        
        
    end
    if cambiada(1,2)==5 %La variable introducida va a la gráfica verde
        
        handles.vardo4=struct;
        handles.vardo4.posenGV=cambiada(1,1);
        handles.vardo4.posendicc=poseneldicc;
        handles.vardo4.nombreabr=handles.tablaGV2{cambiada(1,1),1};
        handles.vardo4.nombrecomp=handles.tablaGV2{cambiada(1,1),6};
        handles.vardo4.unidades=handles.tablaGV2{cambiada(1,1),11};
        
        for t=1:nvar
            if t~=cambiada(1,1)
               handles.tablaGV2{t,5}=false;
            end
        end                
        
    end
    
    set(handles.uitableGV2,'Data',handles.tablaGV2);
    
else
    if cambiada(1,2)==2
        handles.vardo1=0;
    elseif cambiada(1,2)==3
        handles.vardo2=0;
    elseif cambiada(1,2)==4
        handles.vardo3=0;
    elseif cambiada(1,2)==5
        handles.vardo4=0;
    end
    
end




[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);

function [handles]=borrargrafnum(handles,testborrar)
    
    if testborrar(1,1)==0
        plot(handles.axesup1,0,0,'k');
        set(handles.rejillayN,'Label','Activar rejilla en N');
    end
    if testborrar(1,2)==0
        plot(handles.axesup2,0,0,'r');
        set(handles.rejillayR,'Label','Activar rejilla en R');
    end
    if testborrar(1,3)==0
        plot(handles.axesup3,0,0,'b');
        set(handles.axesup3bis,'YLimMode','Manual');
        Ylim3=get(handles.axesup3,'Ylim');
        set(handles.axesup3bis,'YLim',Ylim3);
    end
    if testborrar(1,4)==0
        plot(handles.axesup4,0,0,'Color',[0,0.5,0]);
        set(handles.axesup4bis,'YLimMode','Manual');
        Ylim4=get(handles.axesup4,'Ylim');
        set(handles.axesup4bis,'YLim',Ylim4);
    end
    
function [handles]=borrargrafdis(handles,testborrar2)
    if testborrar2(1,1)==0
        plot(handles.axesdo1,0,0,'k');
        set(handles.axesdo1,'YTick',[]);        
    end
    if testborrar2(1,2)==0
        plot(handles.axesdo2,0,0,'r');
        set(handles.axesdo2,'YTick',[]);
    end
%     if testborrar2(1,3)==0
%         plot(handles.axesdo3,0,0,'b');
%         set(handles.axesdo3,'YTick',[]);
% %         plot(handles.axesdo3bis,0,0,'b');
% %         set(handles.axesdo3bis,'YLimMode','Manual');
% %         Ylim3=get(handles.axesdo3,'Ylim');
% %         set(handles.axesdo3bis,'YLim',Ylim3);
%     end
%     if testborrar2(1,4)==0
%         plot(handles.axesdo4,0,0,'Color',[0,0.5,0]);
%         set(handles.axesdo4,'YTick',[]);
% %         plot(handles.axesdo4bis,0,0,'Color',[0,0.5,0]);
% %         set(handles.axesdo4bis,'YLimMode','Manual');
% %         Ylim4=get(handles.axesdo4,'Ylim');
% %         set(handles.axesdo4bis,'YLim',Ylim4);
%     end


% --------------------------------------------------------------------
function cargaranalisis_Callback(hObject, eventdata, handles)
% hObject    handle to cargaranalisis (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,'\Analisis\*.ana'], 'Seleccione un archivo de análisis');

if nombrearchivo~=0
    testborrar=zeros(1,4); %limpiamos
    [handles]=borrargrafnum(handles,testborrar);
    [handles]=borrargrafdis(handles,testborrar);
    [handles]=refresca(handles);
    [handles]=actualizarGV(handles);
    
    handles.analisis=[ruta,nombrearchivo];
    fid=fopen(handles.analisis); %escaneamos el archivo de análisis
    intermedio=textscan(fid,'%s%s%s%d%d%d','Delimiter',',');
    fclose(fid);
    
    intermedio2=intermedio{1};  %nombre del archivo con los datos de
    datosanalisis=intermedio2{1}; %análisis
    
    intermedio2=intermedio{2}; %ruta a los datos de operación (es la que
    handles.rutaD=intermedio2; %se toma como válida)
    
    intermedio2=intermedio{3}; %modelo, para poder acceder a la carpeta
    modelo=intermedio2{1};   %correcta de análisis
    
    directrabajo=cd; %cargamos los datos de análisis
    cd(['.\',modelo,'\Analisis\']); %tienen que estar en la carpeta
    load(datosanalisis);            %\Análisis\
    cd(directrabajo);
    
    %Comprobamos la ruta a los datos de operación (rutaD):
    testruta=1;
    ruta=handles.rutaD{1};
    try %Posibilidad 1
        load(ruta);
    catch error
        testruta=0;
    end
    
    if testruta==0
        testruta=1;
        try %Posibilidad 2
            pasosruta=textscan(ruta,'%s',30,'Delimiter','\\');
            pasosruta=pasosruta{1};
            [numpasos,inutil]=size(pasosruta);
            nombreop=pasosruta{numpasos}; %cogemos la última palabra de la
            directrabajo=cd;              %ruta y la buscamos en la
            cd(['.\',modelo,'\Operaciones\']);% carpeta de operaciones
            load(nombreop);
            cd(directrabajo);
        catch error
            testruta=0;
            warndlg('Archivo de datos no encontrado.','Error de lectura','modal');
            error('Archivo de datos no encontrado.')
        end
    end

    if testruta==1
        handles.D=D; handles.modelo=modelo; handles.M=M; handles.N=N; handles.zoom.centro=zoomcentro;
        handles.zoom.rango=zoomrango; handles.pintarnum=pintarnum; handles.pintardis=pintardis; handles.dicc=dicc; handles.neventos=neventos;
        handles.listaeventos=listaeventos; handles.rescomb=rescomb; handles.rescombgrp=rescombgrp; handles.tablaeventos=tablaeventos;
        handles.variables=variables; handles.posdat=posdat; handles.tipovar=tipovar; handles.tablaGV=tablaGV; handles.tablaGV2=tablaGV2;
        handles.grafeventos=grafeventos;
        handles.YlimN=ylimn; handles.YlimR=ylimr; handles.YlimA=ylima; handles.YlimV=ylimv; handles.maxmin=maxmin;
        
        handles.nev=1;
        handles.gridyN=gridyN; handles.gridyR=gridyR; handles.gridx=gridx;
        
        handles.nombreop=nombreop;
        
        set(handles.textoperacion,'String',handles.nombreop);
        set(handles.textmodelo,'String',handles.modelo);

        set(handles.uitableGV,'Data',tablaGV);
        set(handles.uitableGV2,'Data',tablaGV2);
        
        set(handles.editMinN,'String',num2str(ylimn(1)));
        set(handles.editMinR,'String',num2str(ylimr(1)));
        set(handles.editMinA,'String',num2str(ylima(1)));
        set(handles.editMinV,'String',num2str(ylimv(1)));
        set(handles.editMaxN,'String',num2str(ylimn(2)));
        set(handles.editMaxR,'String',num2str(ylimr(2)));
        set(handles.editMaxA,'String',num2str(ylima(2)));
        set(handles.editMaxV,'String',num2str(ylimv(2)));
        
        set(handles.sliderpan,'Min',slidermin);
        set(handles.sliderpan,'Max',slidermax);
    
        [handles]=pinta(handles);

        handles=refresca(handles);
    

    end
    guidata(hObject,handles);

end
% --------------------------------------------------------------------
function guardaranalisis_Callback(hObject, eventdata, handles)
% hObject    handle to guardaranalisis (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,'\Analisis\','Sin titulo','.ana'], 'Elija un nombre para guardar el análisis');
% 
if nombrearchivo~=0
   
    directrabajo=cd;
    cd(ruta);
    
    intermedio=textscan(nombrearchivo,'%s','Delimiter','.');
    intermedio=intermedio{1}(1);
    intermedio=intermedio{1};
    nombreanalisis=['dat-ana-',intermedio];
    rutaD=handles.rutaD; modelo=handles.modelo; M=handles.M; N=handles.N; zoomcentro=handles.zoom.centro;
    zoomrango=handles.zoom.rango; pintarnum=handles.pintarnum; pintardis=handles.pintardis; dicc=handles.dicc; neventos=handles.neventos;
    listaeventos=handles.listaeventos; rescomb=handles.rescomb; rescombgrp=handles.rescombgrp; tablaeventos=handles.tablaeventos;
    variables=handles.variables; posdat=handles.posdat; tipovar=handles.tipovar; tablaGV=handles.tablaGV; tablaGV2=handles.tablaGV2;
    grafeventos=handles.grafeventos;
    ylimn=handles.YlimN; ylimr=handles.YlimR; ylima=handles.YlimA; ylimv=handles.YlimV; maxmin=handles.maxmin;
    nombreop=handles.nombreop; gridyN=handles.gridyN; gridyR=handles.gridyR; gridx=handles.gridx;
    varup1=handles.varup1; varup2=handles.varup2; varup3=handles.varup3; varup4=handles.varup4;
    vardo1=handles.vardo1; vardo2=handles.vardo2; vardo3=handles.vardo3; vardo4=handles.vardo4;
    
    slidermin=get(handles.sliderpan,'Min');
    slidermax=get(handles.sliderpan,'Max');
    
    save(nombreanalisis,'rutaD','modelo','M','N','zoomcentro','zoomrango','pintarnum','pintardis','dicc','neventos','listaeventos','rescomb','rescombgrp','tablaeventos','variables','posdat','tipovar','tablaGV','tablaGV2','slidermin','slidermax','grafeventos','ylimn','ylimr','ylima','ylimv','maxmin','nombreop','gridyN','gridyR','gridx','varup1','varup2','varup3','varup4','vardo1','vardo2','vardo3','vardo4');

    rutaD=rutaD{1};
    
    uiresume(handles.figureNAD);
    
    fid=fopen(nombrearchivo,'wt');

    fprintf(fid,'%s,',nombreanalisis);
    fprintf(fid,'%s,',rutaD);
    fprintf(fid,'%s,',modelo);
    fprintf(fid,'%d,',day(date));
    fprintf(fid,'%d,',month(date));
    fprintf(fid,'%d,',year(date));

    fclose(fid);

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

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

uiresume(handles.figureNAD);


% --- Executes when figureNAD is resized.
function figureNAD_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to figureNAD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% pos1=get(handles.uipanelmodulos,'Position');
% pos2=get(handles.axesmodelo,'Position');
% pos2(1)=pos1(1);
% pos2(2)=pos1(2)+pos1(4)+0.004;
% set(handles.axesmodelo,'Position',pos2);
% 
% guidata(hObject,handles);


function editMinN_Callback(hObject, eventdata, handles)
% hObject    handle to editMinN (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 editMinN as text
%        str2double(get(hObject,'String')) returns contents of editMinN as a double

min=str2double(get(handles.editMinN,'String'));

if isnan(min)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMinN,'String',num2str(handles.YlimN(1)));
else
    if min<handles.YlimN(2)
        handles.YlimN(1)=min;
    else
        warndlg('La cota inferior ha de ser menor que la superior.','Error de entrada','modal');
        set(handles.editMinN,'String',num2str(handles.YlimN(1)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMinN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMinN (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 editMaxN_Callback(hObject, eventdata, handles)
% hObject    handle to editMaxN (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 editMaxN as text
%        str2double(get(hObject,'String')) returns contents of editMaxN as a double

max=str2double(get(handles.editMaxN,'String'));

if isnan(max)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMaxN,'String',num2str(handles.YlimN(2)));
else
    if max>handles.YlimN(1)
        handles.YlimN(2)=max;
    else
        warndlg('La cota superior ha de ser mayor que la inferior.','Error de entrada','modal');
        set(handles.editMaxN,'String',num2str(handles.YlimN(2)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMaxN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMaxN (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 editMinR_Callback(hObject, eventdata, handles)
% hObject    handle to editMinR (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 editMinR as text
%        str2double(get(hObject,'String')) returns contents of editMinR as a double

min=str2double(get(handles.editMinR,'String'));

if isnan(min)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMinR,'String',num2str(handles.YlimR(1)));
else
    if min<handles.YlimR(2)
        handles.YlimR(1)=min;
    else
        warndlg('La cota inferior ha de ser menor que la superior.','Error de entrada','modal');
        set(handles.editMinR,'String',num2str(handles.YlimR(1)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMinR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMinR (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 editMaxR_Callback(hObject, eventdata, handles)
% hObject    handle to editMaxR (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 editMaxR as text
%        str2double(get(hObject,'String')) returns contents of editMaxR as a double

max=str2double(get(handles.editMaxR,'String'));

if isnan(max)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMaxR,'String',num2str(handles.YlimR(2)));
else
    if max>handles.YlimR(1)
        handles.YlimR(2)=max;
    else
        warndlg('La cota superior ha de ser mayor que la inferior.','Error de entrada','modal');
        set(handles.editMaxR,'String',num2str(handles.YlimR(2)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMaxR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMaxR (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 editMinA_Callback(hObject, eventdata, handles)
% hObject    handle to editMinA (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 editMinA as text
%        str2double(get(hObject,'String')) returns contents of editMinA as a double

min=str2double(get(handles.editMinA,'String'));

if isnan(min)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMinA,'String',num2str(handles.YlimA(1)));
else
    if min<handles.YlimA(2)
        handles.YlimA(1)=min;
    else
        warndlg('La cota inferior ha de ser menor que la superior.','Error de entrada','modal');
        set(handles.editMinA,'String',num2str(handles.YlimA(1)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMinA_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMinA (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 editMaxA_Callback(hObject, eventdata, handles)
% hObject    handle to editMaxA (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 editMaxA as text
%        str2double(get(hObject,'String')) returns contents of editMaxA as a double

max=str2double(get(handles.editMaxA,'String'));

if isnan(max)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMaxA,'String',num2str(handles.YlimA(2)));
else
    if max>handles.YlimA(1)
        handles.YlimA(2)=max;
    else
        warndlg('La cota superior ha de ser mayor que la inferior.','Error de entrada','modal');
        set(handles.editMaxA,'String',num2str(handles.YlimA(2)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMaxA_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMaxA (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 editMinV_Callback(hObject, eventdata, handles)
% hObject    handle to editMinV (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 editMinV as text
%        str2double(get(hObject,'String')) returns contents of editMinV as a double

min=str2double(get(handles.editMinV,'String'));

if isnan(min)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMinV,'String',num2str(handles.YlimV(1)));
else
    if min<handles.YlimV(2)
        handles.YlimV(1)=min;
    else
        warndlg('La cota inferior ha de ser menor que la superior.','Error de entrada','modal');
        set(handles.editMinV,'String',num2str(handles.YlimV(1)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMinV_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMinV (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 editMaxV_Callback(hObject, eventdata, handles)
% hObject    handle to editMaxV (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 editMaxV as text
%        str2double(get(hObject,'String')) returns contents of editMaxV as a double

max=str2double(get(handles.editMaxV,'String'));

if isnan(max)
    warndlg('Por favor introduce un valor numérico.','Error de entrada','modal');
    set(handles.editMaxV,'String',num2str(handles.YlimV(2)));
else
    if max>handles.YlimV(1)
        handles.YlimV(2)=max;
    else
        warndlg('La cota superior ha de ser mayor que la inferior.','Error de entrada','modal');
        set(handles.editMaxV,'String',num2str(handles.YlimV(2)));
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function editMaxV_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editMaxV (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 pushbuttonautozN.
function pushbuttonautozN_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonautozN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.autozN=1;
[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);

% --- Executes on button press in pushbuttonautozR.
function pushbuttonautozR_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonautozR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.autozR=1;
[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);

% --- Executes on button press in pushbuttonautozA.
function pushbuttonautozA_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonautozA (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.autozA=1;
[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);

% --- Executes on button press in pushbuttonautozV.
function pushbuttonautozV_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonautozV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.autozV=1;
[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);

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

[nvar,inutil]=size(handles.tablaGV);

for i=nvar:-1:1
    if handles.tablaGV{i,2}==true
        poseneldicc=handles.pintarnum(i,2);
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefN=1;
        else
            handles.autozN=1;
        end
        break
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

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

[nvar,inutil]=size(handles.tablaGV);

for i=nvar:-1:1
    if handles.tablaGV{i,3}==true
        poseneldicc=handles.pintarnum(i,2);
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefR=1;
        else
            handles.autozR=1;
        end
        break
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

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

[nvar,inutil]=size(handles.tablaGV);

for i=nvar:-1:1
    if handles.tablaGV{i,4}==true
        poseneldicc=handles.pintarnum(i,2);
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefA=1;
        else
            handles.autozA=1;
        end
        break
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

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

[nvar,inutil]=size(handles.tablaGV);

for i=nvar:-1:1
    if handles.tablaGV{i,5}==true
        poseneldicc=handles.pintarnum(i,2);
        if (handles.maxmin(poseneldicc,1)~=0)||(handles.maxmin(poseneldicc,2)~=0)
            handles.ZpordefV=1;
        else
            handles.autozV=1;
        end
        break
    end
end

[handles]=refresca(handles);

guidata(hObject,handles);

function [handles]=detectmaxmin(handles)
[nvar,inutil]=size(handles.dicc{1});

for i=1:nvar
    if strcmp(handles.dicc{5}{i},'DISCRETE')
        handles.maxmin(i,1)=0;
        handles.maxmin(i,2)=0;
    else
        cad=handles.dicc{7}{i};
        cad=regexprep(cad,'Min: ','');
        cad=regexprep(cad,' Max: ','$');
        maxmin=textscan(cad,'%d%d','Delimiter','$');
        try
            handles.maxmin(i,1)=maxmin{1};
            handles.maxmin(i,2)=maxmin{2};
        catch error
            handles.maxmin(i,1)=0;
            handles.maxmin(i,2)=0;
        end
        if handles.maxmin(i,1)>=handles.maxmin(i,2)
            handles.maxmin(i,1)=0;
            handles.maxmin(i,2)=0;
        end
    end
end
        


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

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

[datoseventos]=GEv1(handles.D,handles.modelo,datoseventos,0);

if iscell(datoseventos)
handles.listaeventos=datoseventos{1};
handles.grafeventos=datoseventos{2};
handles.rescomb=datoseventos{3};
handles.rescombgrp=datoseventos{4};
handles.tablaeventos=datoseventos{5};
handles.neventos=datoseventos{6};
end
[handles]=pinta(handles);
[handles]=refresca(handles);

guidata(hObject,handles);


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


% --------------------------------------------------------------------
function menuleyenda_Callback(hObject, eventdata, handles)
% hObject    handle to menuleyenda (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
onoff=get(handles.uipanelleyenda,'Visible');
if strcmp(onoff,'on')
    set(handles.uipanelleyenda,'Visible','off');
    set(handles.menuleyenda,'Label','Activar leyenda');
else
    set(handles.uipanelleyenda,'Visible','on');
    set(handles.menuleyenda,'Label','Desactivar leyenda');
end

guidata(hObject,handles);


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

if handles.notacion==0
    handles.notacion=1;
    set(handles.menunotacion,'Label','Desactivar notación científica');
    set(handles.axesup1,'YTickLabelMode','Auto');
    set(handles.axesup2,'YTickLabelMode','Auto');
    set(handles.axesup3bis,'YTickLabelMode','Auto');
    set(handles.axesup4bis,'YTickLabelMode','Auto');
    set(handles.axesup1,'XTickLabelMode','Auto');
    
    set(handles.axesdo1,'XTickLabelMode','Auto');

else
    handles.notacion=0;
    set(handles.menunotacion,'Label','Activar notación científica');
end

[handles]=pinta(handles);
[handles]=refresca(handles);
guidata(hObject,handles);


% --- Executes on button press in checkboxdatacursor.
function checkboxdatacursor_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxdatacursor (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 checkboxdatacursor
if get(handles.checkboxdatacursor,'Value')==1
    set(handles.datacursor,'Enable','on');
    set(get(get(handles.datacursor,'UIContextMenu'),'Children'),'Visible','off');
    mifuncion=@(x,y) textdatacursor(x,y,handles);
    set(handles.datacursor,'UpdateFcn',mifuncion);
else
    set(handles.datacursor,'Enable','off');
end
guidata(hObject,handles);


% --- Executes on selection change in popupmenudatacursor.
function popupmenudatacursor_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenudatacursor (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 popupmenudatacursor contents as cell array
%        contents{get(hObject,'Value')} returns selected item from
%        popupmenudatacursor

handles=actualizarstack(handles);

% --- Executes during object creation, after setting all properties.
function popupmenudatacursor_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenudatacursor (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


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


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

if handles.gridyN
    set(handles.axesup1,'YGrid','off');
    set(handles.rejillayN,'Label','Activar rejilla en N');
    handles.gridyN=0;
else
    set(handles.axesup1,'YGrid','on');
    set(handles.rejillayN,'Label','Desactivar rejilla en N');
    handles.gridyN=1;
end

guidata(hObject,handles);

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

if handles.gridyR
    set(handles.axesup2,'YGrid','off');
    set(handles.rejillayR,'Label','Activar rejilla en R');
    handles.gridyR=0;
else
    set(handles.axesup2,'YGrid','on');
    set(handles.rejillayR,'Label','Desactivar rejilla en R');
    handles.gridyR=1;
end

guidata(hObject,handles);

%---------------------------------------------------------------------


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

delete(findall(handles.axesup1,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesup2,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesup3,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesup4,'Type','hggroup','HandleVisibility','off'));

delete(findall(handles.axesdo1,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesdo2,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesdo3,'Type','hggroup','HandleVisibility','off'));
delete(findall(handles.axesdo4,'Type','hggroup','HandleVisibility','off'));

function [handles]=actualizarstack(handles)

sel=get(handles.popupmenudatacursor,'Value');

if sel~=1
    set(handles.axesup4,'Color','none');
    set(handles.axesup1,'Color','w');
    uistack(handles.axesup1,'bottom');
end

if sel==1
    uistack(handles.axesup1,'top');
    set(handles.axesup1,'Color','none');
    set(handles.axesup4,'Color','w');
    uistack(handles.axesup4,'bottom');
elseif sel==2
    uistack(handles.axesup2,'top');
elseif sel==3
    uistack(handles.axesup3,'top');
elseif sel==4
    uistack(handles.axesup4,'top');
end
uistack(handles.uipanelleyenda,'top');


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

if handles.gridx
    set(handles.axesup1,'XGrid','off');
    set(handles.axesdox,'XGrid','off');
    set(handles.rejillax,'Label','Activar rejilla en X');
    handles.gridx=0;
else
    set(handles.axesup1,'XGrid','on');
    set(handles.axesdox,'XGrid','on');
    set(handles.rejillax,'Label','Desactivar rejilla en X');
    handles.gridx=1;
end

guidata(hObject,handles);
