function varargout = GVv1(varargin)
%GVV1 M-file for GVv1.fig
%      GVV1, by itself, creates a new GVV1 or raises the existing
%      singleton*.
%
%      H = GVV1 returns the handle to a new GVV1 or the handle to
%      the existing singleton*.
%
%      GVV1('Property','Value',...) creates a new GVV1 using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to GVv1_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      GVV1('CALLBACK') and GVV1('CALLBACK',hObject,...) call the
%      local function named CALLBACK in GVV1.M with the given input
%      arguments.
%
%      *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 GVv1

% Last Modified by GUIDE v2.5 27-Nov-2012 21:10:58

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GVv1_OpeningFcn, ...
                   'gui_OutputFcn',  @GVv1_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 GVv1 is made visible.
function GVv1_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   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

handles.D=varargin{1};
handles.modelo=varargin{2};
handles.dicc=varargin{3};
handles.seleccionadas=varargin{4};
handles.posdatsel=varargin{5};
handles.GVauto=varargin{6};

%%%%%%%%%%%%%%%%%%%%Carga de la imagen del 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

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

[inutil,handles.N]=size(handles.D);

handles.sd=0;
handles.ss=0;

%Se crea la lista de variables disponibles totales (variables que aparecen en D)
handles.disptotales=zeros(1,handles.N);
handles.disptotales(1,:)=handles.D(1,:);

%Se inicializa la lista de variables en la tabla (totales filtradas)
handles.dispfiltradas=handles.disptotales;
%Se inicializa la lista de posiciones en los datos de las variables disponibles
handles.posdatdisp=1:handles.N;
%Se inicializan filtros
handles.filtroATA=0;
handles.seleccionATA=1;
handles.cadena='';
%Se actualiza la tabla disp
[handles]=actualizardisp(handles);
%Se actualiza la tabla selec
[handles]=actualizarselec(handles);

%%%%%%%%%%%% Se llena el pop-up de ATA %%%%%%%%%%%%%%%%%%%%%%%
listaATA=cell(1);
listaATAnum=zeros(0);
for r=1:handles.N
    if handles.D(1,r)~=0
        listaATAnum(r)=handles.dicc{4}(handles.D(1,r));
    end
end
listaATAnum=unique(listaATAnum);
[inutil,W]=size(listaATAnum);
for s=1:W
    listaATA{s}=num2str(listaATAnum(s));
end
set(handles.popupmenuATA,'String',listaATA);
handles.listaATA=listaATA;
handles.listaATAnum=listaATAnum;


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

set(handles.checkboxabre,'Value',1);
set(handles.checkboxcompleto,'Value',0);
set(handles.checkboxposib,'Value',0);

%%%%%%%%%%%%%%%%%%%%%%%CASO CARGA PERFIL%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if handles.GVauto~=0
    test2=1;
    try
        
        fid=fopen(['.\',handles.modelo,'\Sets\',handles.GVauto,'.set']);
        intermedio=textscan(fid,'%s','Delimiter',',');
        fclose(fid);
        
        intermedio=intermedio{1};
        [T,inutil]=size(intermedio);
        
        modelo=intermedio(1);
        variables=zeros(1);
        
        if strcmp(modelo,handles.modelo)==0
            
            warndlg('El set se corresponde con un modelo de avión distinto del actual.','Error de set','modal');
            
        else
            
            
            for i=3:T
                variables(i-2)=str2double(intermedio(i));
            end
            
            s=1;
            
            for r=1:T-2
                
                test=0;
                
                for j=1:handles.N
                    if variables(r)==handles.disptotales(j)
                        test=j;
                        break;
                    end
                end
                
                if test==0
                    test2=0;
                    intermedio=handles.dicc{8}(variables(r));
                    intermedio=intermedio{1};
                    disp(['La variable ',intermedio,' no aparece en los datos.']);
                else
                    
                    handles.seleccionadas(s)=variables(r);
                    handles.posdatsel(s)=j;
                    s=s+1;
                    
                end
                
            end
            if test2==0
                uiwait(warndlg('Algunas variables no se han añadido porque no aparecen en los datos. Consulte la línea de comando para ver una lista.', 'Error de variable','non-modal'));
            end
        end
    catch error
        warndlg('Error al cargar el set de variables.', 'Error de variable','non-modal');
        handles.seleccionadas=-1;
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes GVv1 wait for user response (see UIRESUME)
if handles.GVauto==0
    uiwait(handles.figureGV);
end

% --- Outputs from this function are returned to the command line.
function varargout = GVv1_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

[inutil,Q]=size(handles.seleccionadas);
handles.tipovar=[];

if handles.seleccionadas~=-1;
    for j=1:Q
        intermedio=handles.dicc{5}(handles.seleccionadas(j));
        if strcmpi(intermedio{1},'DISCRETE')
            handles.tipovar(j)=1;
        else
            handles.tipovar(j)=0;
        end
    end
end


varargout{1}=handles.seleccionadas;
varargout{2}=handles.posdatsel;
varargout{3}=handles.tipovar;


delete(gcf)


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

[inutil,Q]=size(handles.seleccionadas);
[sel,inutil]=size(handles.sd);

if handles.sd==0
    
else
    if isempty(handles.seleccionadas)
        Q=0;
    end
    r=0; %para los casos de variables no válidas
    for j=1:sel
        if handles.dispfiltradas(handles.sd(j,1))~=0
            handles.seleccionadas(Q+j-r)=handles.dispfiltradas(handles.sd(j,1));
            handles.posdatsel(Q+j-r)=handles.posdatdisp(handles.sd(j,1));
        else
            r=r+1;
        end
    end
    
    [handles.seleccionadas,I,J]=unique(handles.seleccionadas);
    handles.posdatsel=handles.posdatsel(I);
    
    [handles]=actualizarselec(handles);
end

guidata(hObject,handles);

% --- 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)

[sel,inutil]=size(handles.ss);

if handles.ss==0
    
else
    
    for j=sel:-1:1
        handles.seleccionadas(handles.ss(j,1))=[];
        handles.posdatsel(handles.ss(j,1))=[];
    end
    [handles]=actualizarselec(handles);
end

guidata(hObject,handles);

function [handles]=actualizardisp(handles)
% Filtrado ATA
handles.dispfiltradas=handles.disptotales;
handles.posdatdisp=1:handles.N;
if handles.filtroATA==1
    [inutil,L]=size(handles.dispfiltradas);
    for t=L:-1:1
        suATA=handles.dicc{4}(handles.dispfiltradas(t));
        if suATA~=handles.listaATAnum(handles.seleccionATA)
            handles.dispfiltradas(t)=[];
            handles.posdatdisp(t)=[];
        end
    end
end

% Filtrado cadena
[inutil,L]=size(handles.dispfiltradas);

if isempty(handles.cadena)==0
    for r=L:-1:1
        if get(handles.checkboxabre,'Value')
            nombreabr=handles.dicc{8}(handles.dispfiltradas(r));
            matches1=regexpi(nombreabr,handles.cadena);
        else
            matches1{1}='';
        end
        if get(handles.checkboxcompleto,'Value')
            nombrecomp=handles.dicc{3}(handles.dispfiltradas(r));
            matches2=regexpi(nombrecomp,handles.cadena);
        else
            matches2{1}='';
        end
        if get(handles.checkboxposib,'Value')
            posibles=handles.dicc{7}(handles.dispfiltradas(r));
            matches3=regexpi(posibles,handles.cadena);
        else matches3{1}='';
        end
        if isempty(matches1{1})&&isempty(matches2{1})&&isempty(matches3{1})
            handles.dispfiltradas(r)=[];
            handles.posdatdisp(r)=[];
        end
    end
end

% Representación en la tabla
[inutil,L]=size(handles.dispfiltradas);
tabladisp=cell(L,8);
for i=1:L     
%     i
    if handles.dispfiltradas(i)~=0
        intermedio=handles.dicc{8}(handles.dispfiltradas(i));
        tabladisp{i,1}=intermedio{1};
        
        intermedio=handles.dicc{3}(handles.dispfiltradas(i));
        tabladisp{i,2}=intermedio{1};
        
        tabladisp{i,3}=handles.dicc{4}(handles.dispfiltradas(i));
        
        tabladisp{i,4}=handles.posdatdisp(i);
        
        tabladisp{i,5}=handles.dispfiltradas(i);
        
        intermedio=handles.dicc{5}(handles.dispfiltradas(i));
        tabladisp{i,6}=intermedio{1};
        
        intermedio=handles.dicc{6}(handles.dispfiltradas(i));
        tabladisp{i,7}=intermedio{1};
        
        intermedio=handles.dicc{7}(handles.dispfiltradas(i));
        tabladisp{i,8}=intermedio{1};
    else
        tabladisp{i,1}='Desconocida';
        tabladisp{i,2}='';
        tabladisp{i,3}=0;
        tabladisp{i,4}=handles.posdatdisp(i);
        tabladisp{i,5}=handles.dispfiltradas(i);
        tabladisp{i,6}='';
        tabladisp{i,7}='';
        tabladisp{i,8}='';
    end
end
set(handles.uitabledisponibles,'Data',tabladisp);
    
    
function [handles]=actualizarselec(handles)

[inutil,L]=size(handles.seleccionadas);

if isempty(handles.seleccionadas)==0
    tablaselec=cell(L,8);
        
    for i=1:L
        if handles.seleccionadas(i)~=0
            intermedio=handles.dicc{8}(handles.seleccionadas(i));
            tablaselec{i,1}=intermedio{1};
            
            intermedio=handles.dicc{3}(handles.seleccionadas(i));
            tablaselec{i,2}=intermedio{1};
            
            tablaselec{i,3}=handles.dicc{4}(handles.seleccionadas(i));
            
            tablaselec{i,4}=handles.posdatsel(i);
            
            tablaselec{i,5}=handles.seleccionadas(i);
            
            intermedio=handles.dicc{5}(handles.seleccionadas(i));
            tablaselec{i,6}=intermedio{1};
            
            intermedio=handles.dicc{6}(handles.seleccionadas(i));
            tablaselec{i,7}=intermedio{1};
            
            intermedio=handles.dicc{7}(handles.seleccionadas(i));
            tablaselec{i,8}=intermedio{1};
        end
    end
    set(handles.uitableseleccionadas,'Data',tablaselec);
else
    tablaselec=cell(0,2);
    set(handles.uitableseleccionadas,'Data',tablaselec);
end
% --- Executes when selected cell(s) is changed in uitabledisponibles.
function uitabledisponibles_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitabledisponibles (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)

celdas=eventdata.Indices;
handles.sd=celdas(:,1);
handles.sd=unique(handles.sd);
guidata(hObject,handles);


% --- Executes when selected cell(s) is changed in uitableseleccionadas.
function uitableseleccionadas_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to uitableseleccionadas (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)

celdas=eventdata.Indices;
handles.ss=celdas(:,1);
handles.ss=unique(handles.ss);
guidata(hObject,handles);


% --- Executes on selection change in popupmenuATA.
function popupmenuATA_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenuATA (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 popupmenuATA contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenuATA
handles.seleccionATA=get(hObject,'Value');
[handles]=actualizardisp(handles);
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function popupmenuATA_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenuATA (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 checkboxATA.
function checkboxATA_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxATA (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 checkboxATA
handles.filtroATA=get(hObject,'Value');
[handles]=actualizardisp(handles);
guidata(hObject,handles);


% --- 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)

uiresume(handles.figureGV);


% --- Executes when user attempts to close figureGV.
function figureGV_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figureGV (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.seleccionadas=-1;
handles.postdatsel=-1;
guidata(hObject,handles);
uiresume(handles.figureGV);


% --------------------------------------------------------------------
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)


% --------------------------------------------------------------------
function guardarset_Callback(hObject, eventdata, handles)
% hObject    handle to guardarset (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,'\Sets\','Sin titulo','.set'], 'Elija un nombre para guardar el set de variables');

if nombrearchivo~=0

    directrabajo=cd;
    cd(ruta);

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

    fprintf(fid,'%s,',handles.modelo);
    fprintf(fid,'%s,','Variables');

    [inutil,S]=size(handles.seleccionadas);

    for r=1:S
    fprintf(fid,'%d,',handles.seleccionadas(1,r));
    end

    fclose(fid);

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


% --------------------------------------------------------------------
function cargarset_Callback(hObject, eventdata, handles)
% hObject    handle to cargarset (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,'\Sets\*.set'], 'Seleccione un archivo de set');
test2=1;
if nombrearchivo~=0
    fid=fopen([ruta,nombrearchivo]);
    intermedio=textscan(fid,'%s','Delimiter',',');
    fclose(fid);
    
    intermedio=intermedio{1};
    [T,inutil]=size(intermedio);
    
    modelo=intermedio(1);
    variables=zeros(1);
    
    if strcmp(modelo,handles.modelo)==0
    
        warndlg('El set se corresponde con un modelo de avión distinto del actual.','Error de set','modal');

    else
          

        for i=3:T
            variables(i-2)=str2double(intermedio(i));
        end
    
        s=1;
    
        for r=1:T-2
        
            test=0;
        
            for j=1:handles.N
                if variables(r)==handles.disptotales(j)
                    test=j;
                    break;           
                end                        
            end
        
            if test==0
                test2=0;
                intermedio=handles.dicc{8}(variables(r));
                intermedio=intermedio{1};
                disp(['La variable ',intermedio,' no aparece en los datos.']);
            else
                handles.seleccionadas(s)=variables(r);
                handles.posdatsel(s)=j;
                s=s+1;            
            end
        
        end
        
        if test2==0
            uiwait(warndlg('Algunas variables no se han añadido porque no aparecen en los datos. Consulte la línea de comando para ver una lista.', 'Error de variable','non-modal'));
        end
        
        [handles]=actualizarselec(handles);   
    
    end
    
end

guidata(hObject,handles);

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

handles.seleccionadas=-1;
handles.postdatsel=-1;
guidata(hObject,handles);
uiresume(handles.figureGV);



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]=actualizardisp(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 checkboxabre.
function checkboxabre_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxabre (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 checkboxabre
[handles]=actualizardisp(handles);
guidata(hObject,handles);

% --- Executes on button press in checkboxcompleto.
function checkboxcompleto_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxcompleto (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 checkboxcompleto
[handles]=actualizardisp(handles);
guidata(hObject,handles);

% --- Executes on button press in checkboxposib.
function checkboxposib_Callback(hObject, eventdata, handles)
% hObject    handle to checkboxposib (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 checkboxposib
[handles]=actualizardisp(handles);
guidata(hObject,handles);
