function varargout = Main_GUI_Aviv(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Main_GUI_Aviv_OpeningFcn, ...
                   'gui_OutputFcn',  @Main_GUI_Aviv_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

function Main_GUI_Aviv_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
guidata(hObject, handles);

function varargout = Main_GUI_Aviv_OutputFcn(hObject, eventdata, handles) 
varargout{1} = handles.output;

function pushbutton19_Callback(hObject, eventdata, handles)

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

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


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

% Hint: listbox 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 Spike_Analysis_Callback(hObject, eventdata, handles)
switch get(handles.Single_or_Multi_Electro,'Value')
    case 1
        close;
        choose_unit_gui_Aviv('singleUnit');
    case 2
        close;
        choose_unit_gui_Aviv('multiUnit');
end

function Single_or_Multi_Electro_Callback(hObject, eventdata, handles)

function Single_or_Multi_Electro_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function Perform_Staging_Callback(hObject, eventdata, handles)
global Save_2_Staging folder_for_staging
clear folder
if ~exist('folder','var') || isempty(folder_for_staging)
    folder_for_staging=uipickfiles('NumFiles',1,'Output','char','FilterSpec','*.Folder','Prompt','Pick directory in which MAT files are located');
end;

if folder_for_staging(1)~=0 && isdir(folder_for_staging) && ~isempty(dir([folder_for_staging,'\*.mat']))
    matfiles=dir([folder_for_staging,'\NPX-Camera*.mat']);
    %sort matfiles
    do_not_delete=[];
    added=0;
    for jj=1:length(matfiles)
        if (length(matfiles(jj,1).name)==38) && str2num(matfiles(jj,1).name(27))==1
            matfiles(end+1,1)=matfiles(jj,1);
            added=added+1; % to allow proper deleting of the >=100 files
        elseif (length(matfiles(jj,1).name)==38) && str2num(matfiles(jj,1).name(27))==2
            matfiles(end+1,1)=matfiles(jj,1);
            added=added+1; % to allow proper deleting of the >=100 files
        else
            do_not_delete=[do_not_delete,jj]; % to allow proper deleting of the >=100 files that were multiplied and left in the middle of the list.
        end
    end
    do_not_delete=[do_not_delete,length(matfiles)-added+1:length(matfiles)];
    matfiles=matfiles(do_not_delete,1);
    %check the sorting of matfile went fine
    all_nums=[];
    for jj=1:length(matfiles)
        if (length(matfiles(jj,1).name)==38)
            zz=str2num(matfiles(jj,1).name(27:29));
        elseif (length(matfiles(jj,1).name)==37)
            zz=str2num(matfiles(jj,1).name(27:28));
        end
        all_nums=[all_nums,zz];
    end
    if sum(diff(all_nums))~=length(diff(all_nums))
        errordlg('ERROR IN SORTING MATFILES BY NUMERICAL ORDER')
    end
        
    Prefix=cell(0);
    for ii=1:length(matfiles)
        if length(matfiles(ii).name)==12 && isempty(find(ismember(Prefix,matfiles(ii).name(1:5)), 1))
            Prefix(end+1)={matfiles(ii).name(1:5)};
        end;
    end;
end
Polysomnography_GUI(folder_for_staging, Save_2_Staging, matfiles)

function Save_2_Staging_Callback(hObject, eventdata, handles)
global Save_2_Staging
Save_2_Staging=get(hObject,'String');

function Save_2_Staging_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (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 pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (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 pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (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 pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton9 (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 pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton10 (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 pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton11 (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 Select_Directory_PSG.
function Select_Directory_PSG_Callback(hObject, eventdata, handles)
% hObject    handle to Select_Directory_PSG (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 Save_Compact_File_PSG.
function Save_Compact_File_PSG_Callback(hObject, eventdata, handles)
% hObject    handle to Save_Compact_File_PSG (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


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

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

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

function Path_2_Save_PSG_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Path_2_Save_PSG (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 ChooseDir_Callback(hObject, eventdata, handles)
global startnum endnum Prefix folder
folder=uipickfiles('NumFiles',1,'Output','char','FilterSpec','*.Folder','Prompt','Pick directory in which MAT files are located');
if folder(1)~=0 && isdir(folder) && ~isempty(dir([folder,'\*.mat']))
    matfiles=dir([folder,'\*.mat']);
    Prefix=cell(0);
    for ii=1:length(matfiles)
        if length(matfiles(ii).name)>26 && isempty(find(ismember(Prefix,matfiles(ii).name(13:20)), 1))
            Prefix(end+1)={matfiles(ii).name(13:20)};
        end;
    end;
    if isempty(Prefix)
        set(handles.Prefix,'Visible','off');
        set(handles.ChoosePrefix,'Visible','off');
        set(handles.text14,'Visible','off');
        set(handles.to,'Visible','off');
        set(handles.FileNum,'Visible','off');
        set(handles.to,'Visible','off');
        set(handles.textFROM,'Visible','off');
        set(handles.textTO,'Visible','off');
        
        ed = errordlg('No .mat files long enough to have a prefix','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);

    else
        set(handles.Prefix,'Visible','on');
        set(handles.ChoosePrefix,'Visible','on');
        set(handles.to,'Visible','on');
        set(handles.FileNum,'Visible','on');
        set(handles.text14,'Visible','on');
        set(handles.to,'Visible','on');
        set(handles.textFROM,'Visible','on');
        set(handles.textTO,'Visible','on');
        set(handles.ChoosePrefix,'String',Prefix);
        files_w_prefix=dir([folder,'\*',Prefix{1},'*.mat']);    
        if length(Prefix)>1
            files_w_prefix=[files_w_prefix;dir([folder,'\*',Prefix{2},'*.mat'])];
        end
        nums=[];
        for ii=1:length(files_w_prefix)
            disp(ii)
            k=strfind(files_w_prefix(ii).name,'#');
            l=strfind(files_w_prefix(ii).name,'-');
            nums=[nums str2double(files_w_prefix(ii).name(k+1:l(end)-1))];
        end;
        nums=sort(nums);
        if length(nums)==1
            startnum=nums;
            endnum=nums;
        else
            b=diff(nums);
            c=[0 find(b~=1) length(b)+1];
            d=diff(c);
            [~,e]=max(d);
            f=nums(c(e)+1:c(e)+max(d));
            startnum=f(1);
            endnum=f(end);            
        end;
        set(handles.textFROM,'String',num2str(startnum));
        set(handles.textTO,'String',num2str(endnum));
    end;
else
    set(handles.Prefix,'Visible','off');
    set(handles.ChoosePrefix,'Visible','off');
    set(handles.text14,'Visible','off');
    set(handles.to,'Visible','off');
    set(handles.FileNum,'Visible','off');
    set(handles.to,'Visible','off');
    set(handles.textFROM,'Visible','off');
    set(handles.textTO,'Visible','off');

    if isempty(dir([folder,'\*.mat'])) && folder(1)~=0
        % no mat files
        ed = errordlg('No .mat files in directory','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);

    elseif folder(1)~=0
        %not a directory
        ed = errordlg('You must choose a directory and not a file','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);
    end;
end;

function FileFormat_Callback(hObject, eventdata, handles)

function FileFormat_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (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 Retrieval_button_Callback(hObject, eventdata, handles)
global chosenprefix folder startnum endnum saving_format saving_in session_type
contents=cellstr(get(handles.ChoosePrefix,'String'));
chosenprefix=contents{get(handles.ChoosePrefix,'Value')};
contents=cellstr(get(handles.FileFormat,'String'));
saving_format=contents{get(handles.FileFormat,'Value')};
contents = cellstr(get(handles.SaveIn,'String'));
choice=contents{get(handles.SaveIn,'Value')};
switch choice 
    case 'Current Directory'
        saving_in=pwd;
    case 'Original Data directory'
        saving_in=folder;
    case 'F:\AllData'
        saving_in='F:\AllData';
end;
if isempty(folder) || strcmp(chosenprefix,'')
        ed = errordlg('You must first choose data files','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);
elseif isnan(startnum) || isnan(endnum)
        ed = errordlg('MAT Files not in right format for arrangement','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);
else
    set(handles.Processing,'Visible','on');
    set(handles.Processing2,'Visible','on');
    pause(0.01);
    fullprefix=ls([folder,'\*',chosenprefix,'*']);
    fullprefix=fullprefix(1,1:strfind(fullprefix(1,:),chosenprefix)+length(chosenprefix)-1);
    
    arrange_digital_data([folder,'\',fullprefix],startnum,endnum,saving_in,saving_format,session_type,get(handles.blink,'Value'));

    set(handles.Processing,'Visible','off');
    set(handles.Processing2,'Visible','off');
end

function Find_Spindles_Callback(hObject, eventdata, handles)
% hObject    handle to Find_Spindles (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 Find_K_complexes.
function Find_K_complexes_Callback(hObject, eventdata, handles)
% hObject    handle to Find_K_complexes (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 Find_REM.
function Find_REM_Callback(hObject, eventdata, handles)
% hObject    handle to Find_REM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

function UpdateDatabase_Telemetry_Callback(hObject, eventdata, handles)
TeleFile=uipickfiles('NumFiles',1,'Output','char','FilterSpec','*.xls*');
if TeleFile(1)~=0 && (strcmp(TeleFile(end-2:end),'xls') || strcmp(TeleFile(end-3:end-1),'xls'))
    ID=str2double(get(handles.ID,'String'));
    if isnan(ID)
        ed = errordlg('ID should be a number.','Error');
        set(ed, 'WindowStyle', 'modal');
        uiwait(ed);
        return;
    end;
    LoadTelemetry(TeleFile,ID);
elseif TeleFile(1)~=0
    ed = errordlg('Not a Excel file.','Error');
    set(ed, 'WindowStyle', 'modal');
    uiwait(ed);
end;
return;

function DataAnalysis_Telemetry_Callback(~, ~, handles)
ID=str2double(get(handles.ID,'String'));
if isnan(ID)
    ed = errordlg('ID should be a number.','Error');
    set(ed, 'WindowStyle', 'modal');
    uiwait(ed);
    return;
end;
Telemetry_analysis(ID);

function ID_Callback(hObject, eventdata, handles)

function ID_CreateFcn(hObject, ~, ~)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function blink_Callback(hObject, eventdata, handles)
% hObject    handle to blink (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 blink


% --- Executes on selection change in ChoosePrefix.
function ChoosePrefix_Callback(hObject, eventdata, handles)
global Prefix startnum endnum folder
contents = cellstr(get(hObject,'String'));
prefixind=find(ismember(Prefix,contents{get(hObject,'Value')}), 1);

files_w_prefix=dir([folder,'\*',Prefix{prefixind},'*.mat']);    
nums=[];
for ii=1:length(files_w_prefix)
    nums=[nums str2double(files_w_prefix(ii).name(27:28))];
end;
nums=sort(nums);
 if length(nums)==1
     startnum=nums;
     endnum=nums;
 else
     [m,~] = size(diff(nums));
     y = [zeros(1,m);diff(nums).'];
     y = y(:);
     p = find(y~=1);
     y(p) = [0;1-diff(p)];
     y = reshape(cumsum(y),[],m).';
     y(:,1) = [];
    [~,maxind]=max(y);
     endnum=nums(maxind+1);
     startnum=nums(max([0 find(y(1:maxind)==0,1,'last')])+1);
 end;
set(handles.textFROM,'String',num2str(startnum));
set(handles.textTO,'String',num2str(endnum));

function ChoosePrefix_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function textFROM_Callback(hObject, eventdata, handles)
global startnum
startnum=str2double(get(hObject,'String'));

function textFROM_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function textTO_Callback(hObject, eventdata, handles)
global endnum
endnum=str2double(get(hObject,'String'));

function textTO_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function SaveIn_Callback(hObject, eventdata, handles)

function SaveIn_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function SaveIn_DeleteFcn(hObject, eventdata, handles)
global saving_in folder
contents = cellstr(get(hObject,'String'));
choice=contents{get(hObject,'Value')};
switch choice
    case 'Current Directory'
        saving_in=pwd;
    case 'Original Data directory'
        saving_in=folder;
    case 'F:\AllData'
        saving_in='F:\AllData';
end;

function ChoosePrefix_DeleteFcn(hObject, eventdata, handles)
global chosenprefix;
contents = cellstr(get(hObject,'String'));
chosenprefix=contents{get(hObject,'Value')};

function FileFormat_DeleteFcn(hObject, eventdata, handles)
global saving_format
contents = cellstr(get(hObject,'String'));
saving_format=contents{get(hObject,'Value')};

function Single_or_Multi_Electro_DeleteFcn(hObject, eventdata, handles)

function Choose_Session_Type_Callback(hObject, eventdata, handles)
global session_type
if get(hObject,'Value')==2
    session_type='sleep';
elseif get(hObject,'Value')==3
    session_type='four_state';
end

function Choose_Session_Type_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
