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

% Last Modified by GUIDE v2.5 27-Nov-2012 21:08:46

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

% Choose default command line output for CSVv1
intermedio=varargin{1};
handles.modelo=intermedio{1};

set(handles.textmodelo,'String',handles.modelo);

handles.archivo=0;
handles.serie='Desconocido';
handles.piloto='Desconocido';
handles.hora=0;
handles.minuto=0;
handles.dia=day(date);
handles.mes=month(date);
handles.anyo=year(date);
handles.nombreop='Sin nombre';
handles.comienzo=0;
handles.final=0;

handles.archivosmulti=cell(15,1);
handles.T=zeros(1,4);

handles.duracion=0;
handles.param=0;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes CSVv1 wait for user response (see UIRESUME)
uiwait(handles.figure1);


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


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

if isempty(get(hObject,'String'))
    handles.serie='Desconocido';
else    
handles.serie=get(hObject,'String');
end

guidata(hObject, handles);

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

if isempty(get(hObject,'String'))
    handles.piloto='Desconocido';
else    
handles.piloto=get(hObject,'String');
end
guidata(hObject, handles);

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

h=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.hora=0;
elseif isnan(h)
    warndlg('El formato de las horas no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(h)~=h
    warndlg('El formato de las horas no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (h>23||h<0)
    warndlg('El formato de las horas no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.hora=h;
end
guidata(hObject, handles);


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

if isempty(get(hObject,'String'))
    handles.archivo=0;
    handles.duracion=0;
    handles.param=0;
    set(handles.textduracion,'String','');
    set(handles.textparam,'String','');
else    
    handles.archivo=get(hObject,'String');
    try
        [handles.duracion,handles.param]=tamanyo(handles.archivo);

        set(handles.textduracion,'String',num2str(handles.duracion));
        set(handles.textparam,'String',num2str(handles.param));
    catch error
        warndlg('Archivo no válido.','Error de entrada','modal');
        set(handles.textduracion,'String','');
        set(handles.textparam,'String',''); 
        set(handles.editarchivo,'String','');
        handles.archivo=0;
    end
end

guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editarchivo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editarchivo (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 pushbuscar.
function pushbuscar_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuscar (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('*.csv', 'Seleccione un archivo de datos CSV');
if nombrearchivo~=0
    set(handles.editarchivo,'String',[ruta,nombrearchivo]);
    handles.archivo=[ruta,nombrearchivo];
    try
        [handles.duracion,handles.param]=tamanyo(handles.archivo);

        set(handles.textduracion,'String',num2str(handles.duracion));
        set(handles.textparam,'String',num2str(handles.param));
    catch error
        warndlg('Archivo no válido.','Error de entrada','modal');
        set(handles.textduracion,'String','');
        set(handles.textparam,'String',''); 
        set(handles.editarchivo,'String','');
        handles.archivo=0;
    end

end
guidata(hObject, handles);

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

m=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.minuto=0;
elseif isnan(m)
    warndlg('El formato de los minutos no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(m)~=m
    warndlg('El formato de los minutos no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (m>59||m<0)
    warndlg('El formato de los minutos no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.minuto=m;
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editminuto_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editminuto (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 pushcargar.
function pushcargar_Callback(hObject, eventdata, handles)
% hObject    handle to pushcargar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
D=0;
%guidata(hObject);

if handles.archivo~=0
    if strcmp(handles.archivo,'Múltiple') %caso de archivos múltiples
        
        if handles.final==0
            handles.final=handles.T(4);
        end
        
        archivo0=0;
        archivof=3;
        
        %Determinamos el archivo de inicio
        if handles.comienzo<=handles.T(2)
            archivo0=1;
        elseif handles.comienzo<=handles.T(3)
            archivo0=2;
        elseif handles.comienzo<=handles.T(4)
            archivo0=3;
        else
            warndlg('Comienzo fuera del rango de datos','Error de concordancia','modal');
        end
        
        %Determinamos el archivo de final
        if handles.final<=handles.T(2)
            archivof=1;
        elseif handles.final<=handles.T(3)
            archivof=2;
        elseif handles.final<=handles.T(4)
            archivof=3;
        else
            handles.final=handles.T(4);
            archivof=3;
        end
% 
%         archivo0
%         archivof
        
        for g=1:15
            estaD=['D',num2str(g)];
            
            if isempty(handles.archivosmulti{g})==0&&g>=(1+(archivo0-1)*5)&&g<=(archivof*5)
                if g<=(archivo0*5)
                    t0=handles.comienzo-handles.T(archivo0);
                else
                    t0=0;
                end
                
                if g>(archivof-1)*5
                    tf=handles.final-handles.T(archivof);
                end
                
%                 estaD
%                 t0
%                 tf
%                 pause
                    eval(['[',estaD,',P,E]=importer(handles.archivosmulti{g},handles.modelo,[t0 tf]);']);
                    if g>(archivo0*5) % se le quita la primera fila (que contiene las variables) para las matrices de debajo
                        eval([estaD,'(1,:)=[];']);
                    end
            else
                eval([estaD,'=[];']);
            end
        end
        
        try
            D=[D1,D2,D3,D4,D5;
                D6,D7,D8,D9,D10;
                D11,D12,D13,D14,D15];
        catch error
            warndlg('Las dimensiones de los archivos no concuerdan. Revise las duraciones y número de variables.','Error de concordancia','modal');
            D=0;
        end
        
    else %caso de un solo archivo cargado
        try
            [D,P,E]=importer(handles.archivo,handles.modelo,[handles.comienzo handles.final]);
        catch error
            warndlg('Archivo no válido.','Error de entrada','modal');
            D=0;
        end
    end
else
    warndlg('No se ha seleccionado ningún archivo.','Error de entrada','modal');
end

if size(D)~=[1 1] %si la conversión se ha hecho con éxito

    dia=num2str(handles.dia); %y se crea el archivo de texto
    mes=num2str(handles.mes);
    anyo=num2str(handles.anyo);
    hora=num2str(handles.hora);
    minuto=num2str(handles.minuto);

    operacion=['MSN',num2str(handles.serie),'-',handles.nombreop,'-',dia,mes,anyo];

    % assignin('base',['D',operacion],D); %se guarda D en el workspace
    % assignin('base',['E',operacion],E); %se guarda E en el workspace

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

    O=cell(13,1);
    O{1}=handles.archivo;
    O{2}=handles.modelo;
    O{3}=handles.nombreop;
    O{4}=handles.serie;
    O{5}=handles.piloto;
    O{6}=handles.hora;
    O{7}=handles.minuto;
    O{8}=handles.dia;
    O{9}=handles.mes;
    O{10}=handles.anyo;
    O{11}=handles.comienzo;
    O{12}=handles.final;
    O{13}=dicc;
    
    directrabajo=cd;
    cd(['.\',handles.modelo,'\Operaciones\']);
    
    save(operacion,'D','E');

    fid=fopen([operacion,'.txt'],'wt');
    for i=1:13
        if isstr(O{i})
            [inutil,longitud]=size(O{i});
            fprintf(fid,'%s,',O{i});
        else
            fprintf(fid,'%d,',O{i});
        end
    end
    
    fclose(fid);
    
    cd(directrabajo);

end

uiresume(handles.figure1);

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

d=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.dia='Desconocido';
elseif isnan(d)
    warndlg('El formato de los días no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(d)~=d
    warndlg('El formato de los días no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (d>31||d<1)
    warndlg('El formato de los días no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.dia=d;
end
guidata(hObject, handles);


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

set(hObject,'String',num2str(day(date)));


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

m=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.mes='Desconocido';
elseif isnan(m)
    warndlg('El formato de los meses no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(m)~=m
    warndlg('El formato de los meses no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (m>12||m<1)
    warndlg('El formato de los meses no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.mes=m;
end
guidata(hObject, handles);

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

set(hObject,'String',num2str(month(date)));


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

a=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.anyo='Desconocido';
elseif isnan(a)
    warndlg('El formato de los años no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(a)~=a
    warndlg('El formato de los años no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (a<0)
    warndlg('El formato de los minutos no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.anyo=a;
end
guidata(hObject, handles);

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

set(hObject,'String',num2str(year(date)));


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

if isempty(get(hObject,'String'))
    handles.nombreop='Sin nombre';
else    
handles.nombreop=get(hObject,'String');
end

guidata(hObject, handles);

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

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



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

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

a=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.comienzo=0;
elseif isnan(a)
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(a)~=a
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (a<0) %AÑADIR CONDICIONES
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.comienzo=a;
end
guidata(hObject, handles);

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

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



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

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

a=str2double(get(hObject,'String'));
if isempty(get(hObject,'String'))
    handles.final=0;
elseif isnan(a)
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif floor(a)~=a
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
elseif (a<0)
    warndlg('El formato no es válido','Error de entrada','modal');
    set(hObject,'String','');
else
handles.final=a;
end
guidata(hObject, handles);

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

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


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

% Hint: delete(hObject) closes the figure
uiresume(handles.figure1);


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

[handles.archivosmulti,handles.T]=csvmulti(handles.archivosmulti);
set(handles.editarchivo,'String','Múltiple');
handles.archivo='Múltiple';
set(handles.textduracion,'String','');

guidata(hObject,handles);
