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

% Last Modified by GUIDE v2.5 22-Feb-2007 14:15:26

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @InteractiveAnalysis_OpeningFcn, ...
    'gui_OutputFcn',  @InteractiveAnalysis_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 InteractiveAnalysis is made visible.
function InteractiveAnalysis_OpeningFcn(hObject, eventdata, handles, varargin)
load('Preferences.mat');%This reads the last settings from the previous session
GUI_dimentions=get(hObject, 'position');%Used to extract the DIMENTIONS (the 3rd and 4th component) in case some changes to the GUI shape were made...
OneByOne_position=[OneByOne_position(1),OneByOne_position(2),GUI_dimentions(3),GUI_dimentions(4)];
save('Preferences.mat','Pref','Audio','ShowTotals','ShowNs','ShowGaps','ShowExpected','Rounding','main_position','preferences_position','OneByOne_position','OneByOne_PercentsCounts','MasterParser_position','FastaExtractor_position','FastaFixer_position','SeqViewerYES','GUspecialYES');
set(hObject, 'position', OneByOne_position);
set(handles.PercentsCounts,'Value',OneByOne_PercentsCounts);%This will remember the last choice for PercentsCounts
mBPsBuilder
handles.BPs=BPs;
handles.Bases=Bases;

mReadSCOREweights
w.wi=wi; w.wni=wni; w.wh=wh; w.wf=wf; w.wg1=wg1; w.wg2=wg2;
handles.w = w;

% set(handles.BrowseForOrganismName,'String','abcdef')
if ~isempty(varargin)
    FastaOrganismNames  =   varargin{1};      	%this is how you import from the main GUI (mMutualCounterGUI)
    Sequences           =   varargin{2};
    DomainNames         =   varargin{3};
    DomainLimits        =   varargin{4};
    ListInputData       =   varargin{5};
    ListInteraction     =   varargin{6};
    ListOrganismName    =   varargin{7};
    ListUnivBas         =   varargin{8};
    ListTable           =   varargin{9};
    ListPosArray        =   varargin{10};
    ListFoundOrganism   =   varargin{11};
    ListUniv            =   varargin{12};
    ListOrgInd          =   varargin{13};
else
    FastaOrganismNames  = [];
    Sequences           = [];
    DomainNames         = [];
    DomainLimits        = [];
    ListInputData       = [];
    ListInteraction     = [];
    ListOrganismName    = [];
    ListUnivBas         = [];
    ListTable           = [];
    ListPosArray        = [];
    ListFoundOrganism   = [];
    ListUniv            = [];
    ListOrgInd          = [];
end


set(handles.BrowseForOrganismName,'String',FastaOrganismNames,'Visible','on');
handles.FastaOrganismNames = FastaOrganismNames;
handles.Sequences          = Sequences;
set(handles.ChosenDomains,'String',DomainNames);
P=get(handles.ChosenDomains,'Value'); %Which is 1 by default (maybe that will change in a later version)
set(handles.NumberOfSequences,'String',strcat(num2str(DomainLimits(P+1)-DomainLimits(P)),' sequences'))

L=0;
if ~isempty(ListInputData)
    L=1;
    if length(ListInputData(L,:))==1
        string = num2str(ListInputData(L,1));
    elseif length(ListInputData(L,:))==2
        string = strcat(num2str(ListInputData(L,1)),',',num2str(ListInputData(L,2)));
    else
        string=[];
        for i=1:length(ListInputData(L,:))
            string=[string num2str(ListInputData(L,i)) ','];
        end
        string=string(1:end-1);
    end
    set(handles.INPUT,'String',string)
    if length(ListInputData(:,1))>1
        set(handles.FF,'Visible','on')
    end
end
handles.ListCount=L;

if isempty(ListInputData)
    set(handles.AnalyzeFamily,'Visible','off');
    set(handles.ChosenTable,'Visible','off');
    set(handles.AlignmentOrStructure,'Visible','off');
elseif length(ListInputData(1,:))~=2
    set(handles.AnalyzeFamily,'Visible','off');
    set(handles.ChosenTable,'Visible','off');
    set(handles.AlignmentOrStructure,'Visible','off');
else 
    set(handles.AnalyzeFamily,'Visible','on');
    set(handles.ChosenTable,'Visible','on');
    set(handles.AlignmentOrStructure,'Visible','on');
end

if ~isempty(ListOrganismName)
    set(handles.ChosenOrganismName,'String',ListOrganismName{1})
%     set(handles.AnalyzeFamily,'Visible','on')
%     set(handles.ChosenTable,'Visible','on')
%     set(handles.AlignmentOrStructure,'Visible','on')
    OrganismName = ListOrganismName(1);
%     n=1; %needed for mGetUnivFromAnyFasta
%     mGetUnivFromAnyFasta;
    handles.mGetUnivFromAnyFastaDONE = 1;%This is a little trick
    handles.FoundOrganism=ListFoundOrganism;
    handles.Univ=ListUniv;
    handles.OrgInd=ListOrgInd;
    handles.OrgInd_Structure=ListOrgInd;%%%This is to save the value for the crystal structure
    set(handles.BrowseForOrganismName,'Value',ListOrgInd(1),'Visible','on');%%%OrgInd is taken from mGetUnivFromAnyFasta
    guidata(hObject, handles);
end



handles.DomainLimits    = DomainLimits;%to pass to other functions within this GUI
handles.DomainNames     = DomainNames;
handles.ListInputData   = ListInputData;
handles.ListInteraction = ListInteraction;
handles.ListOrganismName= ListOrganismName;
handles.ListUnivBas     = ListUnivBas;
handles.ListTable       = ListTable;
handles.ListPosArray    = ListPosArray;

%Too much hassle to include UNIVERSAL among FastaOrganismNames
% % % FastaOrganismNames      =['Universal',FastaOrganismNames];
% % % Sequences               =strvcat(' ',Sequences);          %This is to keep the Sequences and their names at the same positions, after the addition of Universal at the top

% if ~isempty(DomainLimits)
%     set(handles.NumberOfSequences,'String',strcat(num2str(DomainLimits(P+1)-DomainLimits(P)),' sequences'))
% end
handles.runlast=-1;
handles.output = hObject;%%%%%not necessary here
guidata(hObject, handles);
% if ~isempty(ListOrganismName)
%     InteractiveAnalysis('ChosenOrganismName_Callback',gcbo,[],guidata(gcbo))
% end
% --- Outputs from this function are returned to the command line.
function varargout = InteractiveAnalysis_OutputFcn(hObject, eventdata, handles)
%varargout{1} = handles.output;
guidata(hObject, handles);

% --- Executes during object deletion, before destroying properties.
function FigOneByOne_DeleteFcn(hObject, eventdata, handles)
load('Preferences.mat');%This reads the last settings from the previous session
OneByOne_position=get(hObject, 'position');  %Updated here just before closing, this way, the next time this GUI will open in the same location it was closed in
try %For some reason, the following line gives an error when the GUI's figure is closed from GUIDE
    OneByOne_PercentsCounts=get(handles.PercentsCounts,'Value');
catch
    OneByOne_PercentsCounts=2;
end
save('Preferences.mat','Pref','Audio','ShowTotals','ShowNs','ShowGaps','ShowExpected','Rounding','main_position','preferences_position','OneByOne_position','OneByOne_PercentsCounts','MasterParser_position','FastaExtractor_position','FastaFixer_position','SeqViewerYES','GUspecialYES');

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

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

function PercentsCounts_Callback(hObject, eventdata, handles)
INPUT = get(handles.INPUT,'String');
if handles.runlast==1
% if ~isempty(INPUT)
    InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))
elseif handles.runlast>1
    InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
end

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

function ImposeColor_Callback(hObject, eventdata, handles)
% load('Preferences.mat');%This reads the last settings from the previous session
Table = get(handles.ImposeColor,'Value')-1;
if Table > 0
    mColorBPButtons(handles,Table)
    Name = get(handles.ImposeColor,'String');
    s=strcat('Color as: ',Name{Table+1}(4:6));
    set(handles.FamilyName,'String',s);
end
function ImposeColor_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in ChosenDomains.
function ChosenDomains_Callback(hObject, eventdata, handles)
INPUT = get(handles.INPUT,'String');
if handles.runlast==1
% if ~isempty(INPUT)
    InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))
elseif handles.runlast>1
    InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
end
DomainLimits=handles.DomainLimits;
P=get(handles.ChosenDomains,'Value');
set(handles.NumberOfSequences,'String',strcat(num2str(DomainLimits(P+1)-DomainLimits(P)),' sequences'))
function ChosenDomains_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

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


function ChosenOrganismName_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
function ChosenOrganismName_Callback(hObject, eventdata, handles)
FastaOrganismNames = handles.FastaOrganismNames; %these should be imported from the main GUI, otherwise do GetFasta first and pass>>>
OrganismName = {get(handles.ChosenOrganismName,'String')};
Sequences  = handles.Sequences;  %>>>them here when you call the GUI [by doing InteractiveAnalysis(FastaOrganismNames,Sequences) instead of InteractiveAnalysis]
n=1; %needed for mGetUnivFromAnyFasta
mGetUnivFromAnyFasta;
handles.mGetUnivFromAnyFastaDONE=1;
handles.FoundOrganism=FoundOrganism;
handles.Univ=Univ;
handles.OrgInd=OrgInd;
set(handles.BrowseForOrganismName,'Value',OrgInd,'Visible','on');%%%OrgInd is taken from mGetUnivFromAnyFasta
guidata(hObject, handles);

INPUT = get(handles.INPUT,'String');
if handles.runlast==1
% if ~isempty(INPUT)
    InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))
elseif handles.runlast==3
    InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
end

function BrowseForOrganismName_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
function BrowseForOrganismName_Callback(hObject, eventdata, handles)
FastaOrganismNames=handles.FastaOrganismNames;
o=get(handles.BrowseForOrganismName,'Value');
set(handles.ChosenOrganismName,'String',FastaOrganismNames{o})
OrganismName = {get(handles.ChosenOrganismName,'String')};
FastaOrganismNames = handles.FastaOrganismNames; %these should be imported from the main GUI, otherwise do GetFasta first and pass>>>
Sequences  = handles.Sequences;  %>>>them here when you call the GUI [by doing InteractiveAnalysis(FastaOrganismNames,Sequences) instead of InteractiveAnalysis]
n=1; %needed for mGetUnivFromAnyFasta

mGetUnivFromAnyFasta;
handles.mGetUnivFromAnyFastaDONE=1;
handles.FoundOrganism=FoundOrganism;
handles.Univ=Univ;
handles.OrgInd=OrgInd;
guidata(hObject, handles);

INPUT = get(handles.INPUT,'String');
if handles.runlast==1
% if ~isempty(INPUT)
    InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))
elseif handles.runlast==3
    InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
end
% --- Executes on button press in RUNone.
function RUNone_Callback(hObject, eventdata, handles)
% clc
load('Preferences.mat');
Rounding = 10^(Rounding);
PercentsCounts=get(handles.PercentsCounts,'Value');

OrganismName        = {get(handles.ChosenOrganismName,'String')};
ChosenDomains       = get(handles.ChosenDomains,'Value');
DomainNames         = handles.DomainNames;
DomainLimits        = handles.DomainLimits;
FastaOrganismNames  = handles.FastaOrganismNames; %these should be imported from the main GUI, otherwise do GetFasta first and pass>>>
Sequences           = handles.Sequences;  %>>>them here when you call the GUI [by doing InteractiveAnalysis(FastaOrganismNames,Sequences) instead of InteractiveAnalysis]
ListInputData       = handles.ListInputData;
ListInteraction     = handles.ListInteraction;
ListOrganismName    = handles.ListOrganismName;
BPs                 = handles.BPs;
Bases               = handles.Bases;

if  ~isfield(handles,'mGetUnivFromAnyFastaDONE')
    n=1;
    mGetUnivFromAnyFasta;
    handles.mGetUnivFromAnyFastaDONE=1;
    handles.FoundOrganism=FoundOrganism;
    handles.Univ=Univ;
    handles.OrgInd=OrgInd;
    guidata(hObject, handles);
else FoundOrganism=handles.FoundOrganism;
    Univ=handles.Univ;
    OrgInd=handles.OrgInd;
end
% if isfield(handles,'OrgInd'),;end

INPUT = get(handles.INPUT,'String');
INPUT = strrep(INPUT,' ','');
INPUT = strrep(INPUT,':','-');
INPUT = strrep(INPUT,';',',');

inddash= findstr('-',INPUT);
indcomm= findstr(',',INPUT);
if ~isempty(INPUT)
    if ~((~isempty(inddash) && inddash(1)==1) || (~isempty(indcomm) && indcomm(1)==1) || (~isempty(inddash) && inddash(end)==length(INPUT)) || (~isempty(indcomm) && indcomm(end)==length(INPUT)))
        if length(regexp(INPUT,'-|,|\d'))==length(INPUT) %If no other characters are there except for numbers and - or ,
            handles.runlast=1;
            if isempty(inddash)&&length(indcomm)==1 %This means it is a BP (be careful not to separate them by -)
                LN1=str2num(INPUT(1:indcomm-1));
                LN2=str2num(INPUT(indcomm+1:end));
                if LN1>0 && LN2>0
                    if (LN1<=length(Univ))&&(LN2<=length(Univ))
                        mCheckBPOrder%%%CHECK IF NEED REVERSE OR KEEP ORDER OF LN1 and LN2 depending on their presence in the NT positions list
                        set(handles.FamilyName,'String',ThisInteraction,'Visible','on');
                        InputData=[LN1,LN2];
                        for b=1:length(InputData(1,:))
                            UnivBas(1,b)=Univ(InputData(1,b));
                        end
                        PosArray(:,:,1) = Sequences(:,UnivBas(1,:));	%Optimized for Speed%
                        mMutualCounter_IF_OnebyOne_BP
                        handles.SEQNAME=SEQNAME;
                        BPs=handles.BPs;
                        Bases=handles.Bases;
                        mBuildBPButtons
                        mColorBPButtons(handles,ThisInteraction)
                        set(handles.ImposeColor,'Value',1)
                        set(handles.NTListbox,'Visible','off')
                        set(handles.OutputListbox,'Visible','off')
                        set(handles.OutputListboxTitle,'Visible','off')
                        set(handles.Status,'String','')
                        set(handles.LN1,'String',num2str(LN1),'Visible','on');
                        set(handles.LN2,'String',num2str(LN2),'Visible','on');
                        set(handles.uipanelAnalyzeFamily,'Visible','off');
                        set(handles.uipanelAnalyzePosition,'Visible','on');
                    else set(handles.Status,'String','NT number requested larger than sequence size')
                    end
                else set(handles.Status,'String','NT number requested can not be zero!')
                end
            else
                %%%%%%%Extract InputData:
                if isempty(inddash) && isempty(indcomm) %It means it is only one NT
                    InputData = str2num(INPUT);
                    if InputData>length(Univ)
                        OutsideBound=1;
                    end
                else
                    mGetInputData_for_InteractiveAnalysis
                end
                if ~exist('ZeroInput','var')
                    if ~exist('OutsideBound','var')
                        PosArray=[];

if isempty(strfind(INPUT,'-'))
UnivBas=Univ(InputData);
PosArray = Sequences(:,UnivBas);
else
                        for b=1:length(InputData(1,:))
                            if InputData(2,b)~=0
                                UnivBas1(b)=Univ(InputData(1,b));
                                UnivBas2(b)=Univ(InputData(2,b));
                                if InputData(1,b)<InputData(2,b)
PosArray = [PosArray strcat(Sequences(:,UnivBas1(b):UnivBas2(b)),'..')];          %Optimized for Speed%
                                else
PosArray = [PosArray strcat(Sequences(:,UnivBas1(b):-1:UnivBas2(b)),'..')];   	%Optimized for Speed%
                                end
                            else UnivBas1(b)=Univ(InputData(1,b));
PosArray = [PosArray strcat(Sequences(:,UnivBas1(b)),'..')];                      %Optimized for Speed%
                            end
                        end
end
                        % Sequences(:,UnivBas(n,:))
                        % Sequences(:,1:4)
                        % PosArray
                        HideBPButtons
                        mMutualCounter_IF_OnebyOne_NT
                        handles.SEQNAME=SEQNAME;
                        handles.OUTPUT=OUTPUT;
                        set(handles.OutputListbox,'Visible','off');
                        set(handles.OutputListboxTitle,'Visible','off');
                        set(handles.NTListbox,'String',OUTPUT,'Value',1,'Visible','on');
                        set(handles.Status,'String','');
                        set(handles.uipanelAnalyzeFamily,'Visible','off');
                        set(handles.uipanelAnalyzePosition,'Visible','on');
                    else set(handles.Status,'String','NT number requested larger than sequence size');
                    end
                else set(handles.Status,'String','NT number requested can not be zero!');
                end
            end
        else set(handles.Status,'String','Input error: Only positive integer numbers and - , combinations allowed');
        end
    else set(handles.Status,'String','Input error: you have a , or a - at one end of the input string');
    end
else set(handles.Status,'String','Error: Input box empty');
end

guidata(hObject, handles);

function Pushbutton_Callback(hObject, x, handles)
BPs=handles.BPs;
Bases=handles.Bases;
SEQNAME=handles.SEQNAME;
x=get(gco,'Tag'); %This gets the Tag of the button pressed, not necessary to make a code for each line $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
set(handles.OutputListboxTitle,'String',x,'Visible','on')
for a=1:length(BPs),  if strcmp(x(1),BPs{a,1}(1)), break, end,  end
for b=1:length(BPs),  if strcmp(x(2),BPs{1,b}(2)), break, end,  end
if ~isempty(SEQNAME),
    if (a>length(SEQNAME(1,:,1))) || (b>length(SEQNAME(1,1,:))) %If a button is pressed which has no hits in it and also with the hits array being smaller than it
        SEQNAME{1,a,b}='';i=1; %why 2?
    else
        for i=1:length(SEQNAME(:,a,b)) %This loop is to set i and prevent printing empty strings all over below the actual names
            if isempty(SEQNAME{i,a,b})
                i=i-1;
                break
            end
        end
    end
else SEQNAME{1,a,b}='';i=1;
end %This will change the value of i from 1 to 2, why?
set(handles.OutputListbox,'String',SEQNAME(1:i,a,b),'Value',1,'Visible','on')

function NTListbox_Callback(hObject, eventdata, handles)
SEQNAME = handles.SEQNAME;
OUTPUT  = handles.OUTPUT;
x=get(handles.NTListbox,'Value');
ind= findstr('.',OUTPUT{x,1});  %Doesn't work on MAC
OUT=OUTPUT{x,1}(1:ind-1);
for i=1:length(SEQNAME)
    %if isempty(SEQNAME{x,i}),break,end
    try,    SEQNAME{x,i};    catch,        break,    end
end
set(handles.OutputListboxTitle,'String',OUT,'Visible','on');
set(handles.OutputListbox,'String',SEQNAME(x,1:i-1),'Value',1,'Visible','on');


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

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



% --- Executes on button press in FF.
function FF_Callback(hObject, eventdata, handles)
ListInputData=handles.ListInputData;
L=handles.ListCount;
if length(ListInputData(:,1))>L
    L=L+1;
    if length(ListInputData(L,:))==1
        string = num2str(ListInputData(L,1));
    elseif length(ListInputData(L,:))==2
        string = strcat(num2str(ListInputData(L,1)),',',num2str(ListInputData(L,2)));
    else
        string=[];
        for i=1:length(ListInputData(L,:))
            string=[string num2str(ListInputData(L,i)) ','];
        end
        string=string(1:end-1);
    end
    set(handles.INPUT,'String',string)
end

if L==length(ListInputData(:,1))
    set(handles.FF,'Visible','off')
end
if L>1
    set(handles.REW,'Visible','on')
end
handles.ListCount=L;

INPUT = get(handles.INPUT,'String');
InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))

guidata(hObject, handles);

% --- Executes on button press in REW.
function REW_Callback(hObject, eventdata, handles)
ListInputData=handles.ListInputData;
L=handles.ListCount;
if L>1
    L=L-1;
    if length(ListInputData(L,:))==1
        string = num2str(ListInputData(L,1));
    elseif length(ListInputData(L,:))==2
        string = strcat(num2str(ListInputData(L,1)),',',num2str(ListInputData(L,2)));
    else
        string=[];
        for i=1:length(ListInputData(L,:))
            string=[string num2str(ListInputData(L,i)) ','];
        end
        string=string(1:end-1);
    end
    set(handles.INPUT,'String',string)
end

if L==1
    set(handles.REW,'Visible','off')
end
if L<length(ListInputData(:,1))
    set(handles.FF,'Visible','on')
end
handles.ListCount=L;

INPUT = get(handles.INPUT,'String');
InteractiveAnalysis('RUNone_Callback',gcbo,[],guidata(gcbo))

guidata(hObject, handles);


function ChosenTable_Callback(hObject, eventdata, handles)
InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
function ChosenTable_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function AlignmentOrStructure_Callback(hObject, eventdata, handles)
InteractiveAnalysis('AnalyzeFamily_Callback',gcbo,[],guidata(gcbo))
function AlignmentOrStructure_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function AnalyzeFamily_Callback(hObject, eventdata, handles)
load('Preferences.mat');
AlignmentOrStructure=   get(handles.AlignmentOrStructure,'Value');
ChosenTable         =   get(handles.ChosenTable,'Value')-1;

ListInputData       =   handles.ListInputData;
% ListInteraction     =   handles.ListInteraction;
% ListOrganismName    =   handles.ListOrganismName;
ChosenDomains       =   get(handles.ChosenDomains,'Value');
Rounding            =   10^(Rounding);
PercentsCounts      =   get(handles.PercentsCounts,'Value');
DomainLimits        =   handles.DomainLimits;
% ListUnivBas       =   handles.ListUnivBas;
ListTable           =   handles.ListTable;
ListPosArray        =   handles.ListPosArray;
BPs                 =   handles.BPs;
Bases               =   handles.Bases;
OrgInd              =   handles.OrgInd;
% OrgInd              =   handles.OrgInd_Structure;%%%%%%%%%%%%%%%%%%%%This will apply the following on structure only
% set(handles.BrowseForOrganismName,'Value',OrgInd);%%%%%%%%%%%%%%%%%%%This will apply the following on structure only
FastaOrganismNames=handles.FastaOrganismNames;%%%%%%%%%%%%%%%%%%%%%%%
% set(handles.ChosenOrganismName,'String',FastaOrganismNames{OrgInd})%%This will apply the following on structure only

if ChosenTable~=0
    
    switch AlignmentOrStructure
        case 1 %Get counts from sequence alignment
            mMutualCounter_IF_Alignment
            handles.runlast=2;
        case 2 %Get counts from crystal structure

            %OrganismName = {get(handles.ChosenOrganismName,'String')};
            mMutualCounter_IF_OneOrganism
            handles.runlast=3;
    end
    handles.SEQNAME=SEQNAME;
    mBuildBPButtons
    Table = ChosenTable;
    TableName={'cWW' 'tWW' 'cWH' 'tWH' 'cWS' 'tWS' 'cHH' 'tHH' 'cHS' 'tHS' 'cSS' 'tSs' 'bif'};
    mColorBPButtons(handles,Table)
    set(handles.NTListbox,'Visible','off')
    set(handles.OutputListbox,'Visible','off')
    set(handles.OutputListboxTitle,'Visible','off')
    set(handles.Status,'String','')
    set(handles.LN1,'Visible','off');
    set(handles.LN2,'Visible','off');
    set(handles.INPUT,'String','');
    set(handles.uipanelAnalyzePosition,'Visible','off');
    set(handles.uipanelAnalyzeFamily,'Visible','on');
    set(handles.FamilyName,'String',strcat('Family: ',TableName{Table}),'Visible','on');
    set(handles.HitCount,'String',strcat(num2str(HitCount),' BPs'));
    % handles.SEQNAME=SEQNAME; %BUG??, DOESN'T WORK HERE!!!!
    guidata(hObject, handles);
else set(handles.Status,'String','Please chose a family to analyze')
end



% --- Executes on button press in Display3D.
function Display3D_Callback(hObject, eventdata, handles)
% % % %PDBFile='../PDB_structures/rr0033_5S'; %%%% this needs to point to the crysta structure being represented\

%%%%%%%%%%%%%%%%%%%%%%%%%The next code if for loading a PDB file%%%%%%%%%%%%%%%%%%%%%%%%%
% PDBFile='../PDB_structures/rr0033_5S';
if ~isfield(handles,'File') %The user will be asked for this just once while this GUI is open
    if ispc, sep='\'; else, sep='/';end
    if (~exist('pdbFILEpath','var'))||(exist('pdbFILEname','var')&&(~strcmp(class(pdbFILEname),'char')))
        if exist(['..',sep,'..',sep,'PDB_structures'],'dir')
            OrigDir=cd;
            ind= findstr(sep,OrigDir);  %Doesn't work on MAC
            pdbFILEpath=strcat(OrigDir(1:ind(length(ind)-1)),'PDB_structures',sep);
        elseif exist(['..',sep,'PDB_structures'],'dir')
            OrigDir=cd;
            ind= findstr(sep,OrigDir);  %Doesn't work on MAC
            pdbFILEpath=strcat(OrigDir(1:ind(length(ind))),'PDB_structures',sep);
        else pdbFILEpath=strcat(cd,sep);
        end
        %chdir ../PDB_structures/
    elseif pdbFILEpath==0
        pdbFILEpath=strcat(cd,sep);
    end

    if ispc
        [pdbFILEname, pdbFILEpath] = uigetfile({...
            '*.pdb','*.pdb';...
            '*.pdbs','*.pdbs';...
            '*.*','*.* (all files)'},...
            'Pick a PDB file',pdbFILEpath);
    else
        [pdbFILEname, pdbFILEpath] = uigetfile({...
            '*.pdb','*.pdb'},...
            'Pick a PDB file',pdbFILEpath);
    end
    
    if strcmp(class(pdbFILEname),'char')

        ind= findstr('.',pdbFILEname);
        pdbFILEname=pdbFILEname(1:ind-1); %remove .pdb or .pdbs, that's how zGetNTData likes it

        PDBFile=strcat(pdbFILEpath,pdbFILEname);
        File = zGetNTData(PDBFile,0);  %%%%%%%%%%%%%%%%%%%%%%%%%%THIS IS THE HEART%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        handles.File=File;
        guidata(hObject, handles);

        set(handles.pdbFILEname,'String',pdbFILEname)
    else fprintf('%s\n','Selection of a PDB file cancelled by user')
    end
else
    File=handles.File;
end

if exist('File','var')

    %%%%%%%%%%%%%%%%%%%%%%%%%The next code if for plotting NTs from the PDB file%%%%%%%%%%%%%%%%%%%%%%%%%
    preINPUT = get(handles.INPUT,'String');
    preINPUT = strrep(preINPUT,' ','');
    preINPUT = strrep(preINPUT,'-',':');
    preINPUT = strrep(preINPUT,';',',');
    inddash= findstr(':',preINPUT);
    indcomm= findstr(',',preINPUT);
    INPUT=[];

    %%%next code is to resort the list for the PDB viewing program
    index   = findstr(',',preINPUT);
    index   = [0 index length(preINPUT)+1];
    clear ex,    clear e,
    for i=1:length(index)-1
        ex{i}=preINPUT(index(i)+1:index(i+1)-1);
        e{i}=str2num(ex{i});
        if isempty(e{i})
            ind     = findstr(':',ex{i});
            ex{i}=[ex{i}(ind+1:length(ex{i})),':',ex{i}(1:ind-1)];    %resort
            %         e{i}=str2num(ex{i}); %not needed
        end
        if i==1
            INPUT=num2str(ex{i});
        else
            INPUT=[INPUT,',',num2str(ex{i})];
        end
    end
    %%%Now list is sorted

    if ~isempty(INPUT) && ~strcmp(INPUT,':')
        if ~((~isempty(inddash) && inddash(1)==1) || (~isempty(indcomm) && indcomm(1)==1) || (~isempty(inddash) && inddash(end)==length(INPUT)) || (~isempty(indcomm) && indcomm(end)==length(INPUT)))
            if length(regexp(INPUT,':|,|\d'))==length(INPUT) %If no other characters are there except for numbers and - or ,

                INPUT=strcat('''',strrep(INPUT,',',''','''),'''');
                fig=figure(1);
                set(fig,'name','Ribostral Structure Viewer','NumberTitle','off','Color','k')
                set(gca,'Color','k')
                %%%eval(['zDisplayNT(PDBFile,{',INPUT,'});']);   %%WRONG, File is already read, see next line
                eval(['zDisplayNT(File,{',INPUT,'});']);   %%%%%%%%%%this is the plotting function
                set(handles.Status,'String',['Plotted NT ',INPUT,' ']);

            else set(handles.Status,'String','Input error: Only positive integer numbers and - , combinations allowed');
            end
        else set(handles.Status,'String','Input error: you have a , or a - at one end of the input string');
        end
    else set(handles.Status,'String','Error: Input box empty')
    end
end
