function varargout = ribostral(varargin)

warning off

%warning off all
%warning('off','MATLAB:dispatcher:InexactMatch')
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @ribostral_OpeningFcn, ...
    'gui_OutputFcn',  @ribostral_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 ribostral is made visible.
function ribostral_OpeningFcn(hObject, eventdata, handles, varargin)

if ~isdeployed %Otherwise this will give errors after compilation to a stand alone
    mPath
end

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...
main_position=[main_position(1),main_position(2),GUI_dimentions(3),GUI_dimentions(4)];

[MasterParser_position , FastaExtractor_position , FastaFixer_position , ...
    main_position , preferences_position , OneByOne_position] = ...
    FixPositionsForScreen(MasterParser_position , FastaExtractor_position , FastaFixer_position , ...
    main_position , preferences_position , OneByOne_position);

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', main_position);

if Audio==1
    try
        [Ys,Fs] = wavread(['..',filesep,'Audio',filesep,'Opening']);
        sound(Ys,Fs); %wavplay(Ys,Fs,'async')
    end
end

% Choose default command line output for ribostral
handles.output = hObject;
% data.hpushcb = @GetFasta_Callback;   % GetFasta function handle
% data.hpush = handles.GetFasta;       % graphic object value
% handles.output = data;               % pass data structure to output


handles.valid   =0; %initially no valid handles
for i=1:5       %create 5 checkboxes and make them invisible
    handles.h(i)=uicontrol('Style','checkbox',...
        'Callback',eval(strcat('@ChoseDomain',num2str(i),'_Callback')),...
        'Background',[.502 .502 1],...
        'Value',0,'Units','normalized',...
        'Position',[0.025 (0.73-0.13*i) 0.06 0.09]);  %%%%'Position',[25 (153-25*i) 14 14]);
    set(handles.h(i),'Visible','off')

    handles.h(i+5)=uicontrol('Style','edit',...
        'Callback',eval(strcat('@Domain',num2str(i),'Name_Callback')),...
        'Background','w','Units','normalized',...
        'Position',[0.055 (0.73-0.13*i) 0.18 0.09],...         %%%'Position',[42 (150-25*i) 90 20],...
        'String',strcat('Domain',num2str(i)));
    set(handles.h(i+5),'Visible','off')
end


% Update handles structure
guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = ribostral_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;

%handles.Preferences = Preferences(handles.output);
guidata(hObject, handles);

function File_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function GetFasta_Callback(hObject, eventdata, handles)
if ~isdeployed,clc,end
set(handles.Status,'String','Reading alignment...');drawnow
load('Preferences.mat');
if isfield(handles,'FastaPath')
    FastaPath = handles.FastaPath;
else
    FastaPath = Pref.FastaPath;
end
mGetFasta


if strcmp(class(FastaFilename),'char') %In case the prompt is not cancelled
    handles.InputData =[];
    handles.OrganismName =[];
    % % %             handles.InputData     =   InputData;
    % % %             handles.InputText     =   InputText;
    % % %             %handles.Local        =   Local;
    % % %             handles.PosArray	  =   PosArray;
    % % %             handles.PositionList  =   PositionList;
    % % %             handles.Univ          =   Univ;
    % % %             handles.UnivBas       =   UnivBas;
    % % %             handles.OrganismName  =   OrganismName;
    % % %             handles.OrgInd        =   OrgInd;
    % % %             handles.Interaction   =   Interaction;
    % % %             handles.Table         =   Table;
    % % %             handles.PositionPath  =   PositionPath;
    % % %             handles.FoundOrganism =   FoundOrganism;

    fig2=findobj('Tag','FigOneByOne'); %Close this GUI if open, to make user repass the new sequence data to it
    fig3=findobj('Tag','FigMasterParser');
    fig4=findobj('Tag','FigFastaExtractor');
    close(fig2);
    close(fig3);
    close(fig4);

    handles.FastaFilename      =   FastaFilename;
    handles.FastaOrganismNames =   FastaOrganismNames;
    handles.DomainNames        =   DomainNames;
    handles.DomainLimits       =   DomainLimits;
    %handles.SeqCount          =   SeqCount;
    handles.Sequences          =   Sequences;
    handles.M                  =   M;
    handles.FastaPath          =   FastaPath;

    set(handles.AlignmentFilename,'String',FastaFilename);
    set(handles.PositionsFilename,'String','-');
    set(handles.Status,'String','Alignment loaded, now load a NT list or apply real-time analysis');
    set(handles.uipanelFASTA,'Visible','on');
    set(handles.AnalyzeOneByOne,'Visible','on');
    set(handles.uipanelNT,'Visible','off');
    %     rh=findobj('Tag','FigOneByOne');%This finds out if the OneByOne GUI is open or not
    %     if ~isempty(rh)
    %         FastaFilename = InteractiveAnalysis(FastaOrganismNames,Sequences) %if open then this will export some data to it...
    %     end

    x=length(DomainNames);
    for i=1:x
        set(handles.h(i+5),'String',DomainNames(i))
    end

    if x > handles.valid    %if need to make new checkboxes visible
        for i=handles.valid+1:x
            set(handles.h(i),'Visible','on')    %These are the chekboxes
            set(handles.h(i+5),'Visible','on')  %These are the editboxes
            set(handles.h(i),'Value',1)
        end
        %%%modified%%%
        handles.valid   =   x;
    end
    if handles.valid > x  %need to remove some
        for i=x+1:handles.valid
            set(handles.h(i),'Visible','off')
            set(handles.h(i+5),'Visible','off')
            set(handles.h(i),'Value',0)
        end
        handles.valid   =   x;
    end


    guidata(hObject,handles)
else
    set(handles.Status,'String','Alignment reading cancelled by user');drawnow
end
% --------------------------------------------------------------------
function GetPositions_Callback(hObject, eventdata, handles)
if isfield(handles,'FastaFilename')% if this field exists
    set(handles.Status,'String','Reading NT list...');drawnow

    load('Preferences.mat');

    FastaOrganismNames	=   handles.FastaOrganismNames;
    Sequences           =   handles.Sequences;
    DomainLimits        =   handles.DomainLimits;

    if isfield(handles,'PositionPath')
        PositionPath = handles.PositionPath;
    else
        PositionPath = Pref.PositionPath;
    end


    mGetPositions

    if strcmp(class(PositionList),'char') %In case the prompt is not cancelled
        fig2=findobj('Tag','FigOneByOne'); %Close this GUI if open, to make user repass the new sequence data to it
        close(fig2);

        if FoundOrganism(n) ~=0 %In case organism name was found in the fasta file
            handles.InputData     =   InputData;
            %handles.InputFile    =   InputFile;
            handles.InputText     =   InputText;
            %handles.Local        =   Local;
            handles.PosArray	  =   PosArray;
            handles.PositionList  =   PositionList;
            handles.Univ          =   Univ;
            handles.UnivBas       =   UnivBas;
            handles.OrganismName  =   OrganismName;
            handles.OrgInd        =   OrgInd;
            handles.Interaction   =   Interaction;
            handles.Table         =   Table;
            handles.PositionPath  =   PositionPath;
            handles.FoundOrganism =   FoundOrganism;

            set(handles.PositionsFilename,'String',PositionList);
            set(handles.Status,'String','NT list loaded');
            set(handles.uipanelNT,'Visible','on');
            set(handles.DisplayResults,'Visible','off');
            set(handles.PlotScores,'Visible','off');
            guidata(hObject,handles)
        end
    else
        set(handles.Status,'String','NT list reading cancelled by user');drawnow
    end
else set(handles.Status,'String','Please load an alignment file before you attempt to load a NT list file');
end

% --------------------------------------------------------------------
function Preferences_Callback(hObject, eventdata, handles)
Preferences


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Help_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function Website_Callback(hObject, eventdata, handles)
web http://rna.bgsu.edu/mokdad/ribostral

% --------------------------------------------------------------------
function About_Callback(hObject, eventdata, handles)
DisplayImage('about','About Ribostral',1,0)




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in EXECUTE.
function EXECUTE_Callback(hObject, eventdata, handles)
% FastaFilename  =   handles.FastaFilename
% PositionList=   handles.PositionList
% exist('FastaFilename')
% exist('PositionList')
if ~isdeployed,clc,end

if isfield(handles,'FastaFilename')% if this field exists
    if strcmp(get(handles.PositionsFilename,'String'),'-')~=1,
        %if isfield(handles,'PositionList')
        set(handles.Status,'String','Analyzing NT list...');drawnow

        FastaFilename	   =   handles.FastaFilename;
        FastaOrganismNames =   handles.FastaOrganismNames;
        DomainNames        =   handles.DomainNames;
        DomainLimits       =   handles.DomainLimits;
        %SeqCount          =   handles.SeqCount;
        Sequences          =   handles.Sequences;
        M                  =   handles.M;

        %Now overwrite the old values for DomainNames when you execute, important in case the user already loaded the Fasta file, and only then decided to change the names of the domains
        Domain1Name = get(handles.h(1+5),'String');
        Domain2Name = get(handles.h(2+5),'String');
        Domain3Name = get(handles.h(3+5),'String');
        DomainNames = [Domain1Name,Domain2Name,Domain3Name];

        InputData    =   handles.InputData;
        %InputFile   =   handles.InputFile;
        InputText    =   handles.InputText;
        %Local       =   handles.Local;
        PosArray	 =   handles.PosArray;
        Univ         =   handles.Univ;
        UnivBas      =   handles.UnivBas;
        OrganismName =	 handles.OrganismName;
        OrgInd       =   handles.OrgInd;
        Interaction  =   handles.Interaction;
        Table        =   handles.Table;
        PositionList =   handles.PositionList;
        PositionPath =   handles.PositionPath;
        % --------------------------------------------------------------------
        %handles.output = [Audio,Percentages,ShowTotals,ShowOthers,Rounding];This line is in Preferences

        load('Preferences.mat');

        if get(handles.h(1),'Value')==1,A=1;else A=[];end
        if get(handles.h(2),'Value')==1,B=2;else B=[];end
        if get(handles.h(3),'Value')==1,C=3;else C=[];end
        if get(handles.h(4),'Value')==1,D=4;else D=[];end
        if get(handles.h(5),'Value')==1,E=5;else E=[];end

        ChosenDomains = [A B C D E];
        FoundOrganism   =   handles.FoundOrganism;
        Rounding = 10^(Rounding);
        for Percentages=0:1
            mMutualCounter_IF
        end

        if exist('TotScore','var') %%%%This will only be created in case the program is analyzing a BP list
            handles.Plot.ScoreFormula   = ScoreFormula;
            handles.Plot.corc           = corc;
            handles.Plot.wmax           = wmax;
            handles.Plot.wmin           = wmin;
            handles.Plot.TotScore       = TotScore;
            handles.Plot.Score          = Score;
            %%Already saved:
            % handles.DomainLimits
            % handles.DomainNames
            % handles.Table
            % handles.InputData
        end

        if exist('OutputFileHTML'),handles.OutputFile = OutputFileHTML;
        elseif exist('OutputFileM'),handles.OutputFile = OutputFileM;
        else handles.OutputFile = ' - No output file created - ';
        end

        guidata(hObject,handles)

        set(handles.Status,'String','NT list results ready');

    else set(handles.Status,'String','Load a NT list from the file menu before attempting to EXECUTE');
    end
else set(handles.Status,'String','Please load a Fasta alignment file and a NT list file before attempting to analyze BP list');
end
set(handles.DisplayResults,'Visible','on');

if exist('TotScore','var') %%%%This will only be created in case the program is analyzing a BP list
    set(handles.PlotScores,'Visible','on');
end

function DisplayResults_Callback(hObject, eventdata, handles)
if isfield(handles,'OutputFile')
    if ispc ==1 %ispc returns 1 if this is executed on a PC (Windows)
        eval(['winopen(''',handles.OutputFile,''')'])
    else
        try
            eval(['open(''',handles.OutputFile,''')'])
        catch
            fprintf('%s\n%s\n%s\n','The file:',handles.OutputFile,'could not be opened automatically, please open it manually');
        end
    end
else
    set(handles.Status,'String','You must analyze BP list before being able to see the output file');
end

% --------------------------------------------------------------------
function Helpmestart_Callback(hObject, eventdata, handles)
helpfile = strcat(cd,'/../Help/help.html');
if ispc ==1
    eval(['winopen(''',helpfile,''')'])
else eval(['open(''',helpfile,''')'])
end
%winopen('\..\Help\help.htm')
%web \..\Help\help.htm

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

% % % for D=1:length(DomainNames)
% % %
% % % end
function ChoseDomain1_Callback(hObject, eventdata, handles)
function ChoseDomain2_Callback(hObject, eventdata, handles)
function ChoseDomain3_Callback(hObject, eventdata, handles)
function ChoseDomain4_Callback(hObject, eventdata, handles)
function ChoseDomain5_Callback(hObject, eventdata, handles)
function Domain1Name_Callback(hObject, eventdata, handles)
function Domain2Name_Callback(hObject, eventdata, handles)
function Domain3Name_Callback(hObject, eventdata, handles)
function Domain4Name_Callback(hObject, eventdata, handles)
function Domain5Name_Callback(hObject, eventdata, handles)

% --- Executes during object deletion, before destroying properties.
function FigMain_DeleteFcn(hObject, eventdata, handles)
load('Preferences.mat');%This reads the last settings from the previous session
main_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
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');

fig1=findobj('Tag','FigPreferences');
fig2=findobj('Tag','FigOneByOne');
fig3=findobj('Tag','FigMasterParser');
fig4=findobj('Tag','FigFastaExtractor');
fig5=findobj('Tag','FigFastaFixer');

close(fig1)
close(fig2)
close(fig3)
close(fig4)
close(fig5)

% --------------------------------------------------------------------
function GenerateBPListsFromPDB_Callback(hObject, eventdata, handles)
if ispc
    set(handles.Status,'String','Generating BP lists from PDB...');drawnow

    load('Preferences.mat');
    %cd PDB_Analysis
    mGenerateBPListsFromPDB
    %cd ..

    if strcmp(class(pdbFILEname),'char')
        set(handles.Status,'String','BP lists generated from PDB');
        % set(handles.PDBFilenameAndOrganism,'String',strcat(pdbFILEname,' (',PDBOrganism,')'));
    else
        set(handles.Status,'String','BP lists generation from PDB cancelled by user');drawnow
    end
else
    set(handles.Status,'String','This tool only works on PC... sorry!');drawnow
end

function Tools_Callback(hObject, eventdata, handles)

function Create_fasta_from_mat_Callback(hObject, eventdata, handles)
set(handles.Status,'String','Creating .fasta file from .mat file ...');drawnow
load('Preferences.mat');

%cd FASTA_Maker
mPrintFastaFromMat
%cd ..

if strcmp(class(MatFile),'char')
    set(handles.Status,'String','.fasta file(s) created from .mat file');
    % set(handles.PDBFilenameAndOrganism,'String',strcat(pdbFILEname,' (',PDBOrganism,')'));
else
    set(handles.Status,'String','Creating .fasta file from .mat file cancelled by user');drawnow
end


function Fasta_merger_Callback(hObject, eventdata, handles)
set(handles.Status,'String','Fixing and merging FASTA files ...');drawnow
load('Preferences.mat');

%set(handles.Status,'String','');
%cd FASTA_Maker
mFastaFixerGUI
%cd ..

% if strcmp(class(MatFile),'char')
%     set(handles.Status,'String','UNIQUE and MERGED FASTA files created');
%     % set(handles.PDBFilenameAndOrganism,'String',strcat(pdbFILEname,' (',PDBOrganism,')'));
% else
%     set(handles.Status,'String','Merging FASTA files cancelled by user');drawnow
% end


% --- Executes on button press in AnalyzeOneByOne.
function AnalyzeOneByOne_Callback(hObject, eventdata, handles)
if isfield(handles,'FastaFilename')% if this field exists
    set(handles.Status,'String','');
    FastaOrganismNames = handles.FastaOrganismNames;
    Sequences  = handles.Sequences ;
    DomainNames=handles.DomainNames;
    DomainLimits=handles.DomainLimits;

    %     if isfield(handles,'PosArray')
    %         x=handles.PosArray;
    %     else x(1,3,1)='x'; %dummy, just to make length(x(1,:,1))~=2 (the case of a BP list)
    %     end
    %
    %     if isfield(handles,'PosArray') && (length(x(1,:,1))),%%%%end

    if isfield(handles,'PosArray')
        ListInputData   = handles.InputData;
        ListInteraction = handles.Interaction;
        ListOrganismName= handles.OrganismName;
        ListUnivBas     = handles.UnivBas;
        ListTable       = handles.Table;
        ListPosArray    = handles.PosArray;
        ListFoundOrganism = handles.FoundOrganism;
        ListUniv        = handles.Univ;
        ListOrgInd      = handles.OrgInd;
    else
        ListInputData   = [];
        ListInteraction = {'No BP'};
        ListOrganismName= [];
        ListUnivBas     = [];
        ListTable       = 14;
        ListPosArray    = [];
        ListFoundOrganism = [];
        ListUniv        = [];
        ListOrgInd      = [];
    end
    InteractiveAnalysis(FastaOrganismNames,Sequences,DomainNames,DomainLimits,...
        ListInputData,ListInteraction,ListOrganismName,ListUnivBas,ListTable,ListPosArray,...
        ListFoundOrganism,ListUniv,ListOrgInd);
else set(handles.Status,'String','Please load an alignment file before you attempt to apply real-time analysis');
end


% --------------------------------------------------------------------
function ExtractFasta_Callback(hObject, eventdata, handles)
if isfield(handles,'FastaFilename')% if this field exists
%     load('Preferences.mat');
    set(handles.Status,'String','Extracting columns from the loaded FASTA file ...');drawnow

    %     FastaOrganismNames =   handles.FastaOrganismNames;
    %     DomainNames        =   handles.DomainNames;
    %     DomainLimits       =   handles.DomainLimits;
    %     Sequences          =   handles.Sequences;
    %     FastaFilename	   =   handles.FastaFilename;
    %     FastaPath          =   handles.FastaPath;
    %     if isfield(handles,'handles.InputData')
    %         NTListLoaded = 1;
    %         InputData    =   handles.InputData;
    %         InputText    =   handles.InputText;
    %         PosArray	 =   handles.PosArray;
    %         Univ         =   handles.Univ;
    %         UnivBas      =   handles.UnivBas;
    %         OrganismName =	 handles.OrganismName;
    %         OrgInd       =   handles.OrgInd;
    %         Interaction  =   handles.Interaction;
    %         Table        =   handles.Table;
    %         PositionList =   handles.PositionList;
    %         PositionPath =   handles.PositionPath;
    %     else
    %         NTListLoaded = 0;
    %     end

    %cd FASTA_Maker
    mFastaExtractor_multipleGUI(handles)
    %cd ..

else
    set(handles.Status,'String','Please load a Fasta alignment file to extract positions from it');drawnow
end


function Align_sequences_Callback(hObject, eventdata, handles)
%cd Alignment_Parser
if isfield(handles,'FastaPath')
    mMasterParserGUI(handles.FastaPath,handles.FastaFilename)
else
    mMasterParserGUI
end
%cd ..



% --- Executes on button press in PlotScores.
function PlotScores_Callback(hObject, eventdata, handles)
if isfield(handles,'Plot') %%%%The plots will only be created in case the program is analyzing a BP list


    %Better reassign ChosenDomains here, to change choice for plots independently
    if get(handles.h(1),'Value')==1,A=1;else A=[];end
    if get(handles.h(2),'Value')==1,B=2;else B=[];end
    if get(handles.h(3),'Value')==1,C=3;else C=[];end
    if get(handles.h(4),'Value')==1,D=4;else D=[];end
    if get(handles.h(5),'Value')==1,E=5;else E=[];end
    ChosenDomains = [A B C D E];
    
    if isfield(handles.Plot,'ColCount')
        ColCount=handles.Plot.ColCount;
    else
        ColCount=0;
    end        

    ColCount = mPlotBPScores(handles,ChosenDomains,ColCount);
    
    handles.Plot.ColCount = ColCount;
    guidata(hObject, handles);
end



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

% url = java.net.URL('http://rna.bgsu.edu/mokdad/ribostral/dnld.html');
% is = openStream(url);
% isr = java.io.InputStreamReader(is);
% br = java.io.BufferedReader(isr);
% for i=1:18
%     readLine(br);
% end
% s=readLine(br);
URL = 'http://rna.bgsu.edu/mokdad/ribostral/dnld.html';
string = urlread(URL);
s = string(861:868);

load('Release');
% d=strcat(d,'</strong><br>');

if strcmp(s,d)
    set(handles.Status,'String','Congratulations! Your version is up to date');%drawnow
else
    ss=strcat('Your release (',d,') has an available update (',s,'), please replace your version');
    set(handles.Status,'String', ss);
    web http://rna.bgsu.edu/mokdad/ribostral/dnld.html
end
