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

% Last Modified by GUIDE v2.5 28-Sep-2006 16:01:23

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_plot_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_plot_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(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 GUI_plot is made visible.
function GUI_plot_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 GUI_plot (see VARARGIN)

% Choose default command line output for GUI_plot
handles.output = hObject;


% UIWAIT makes GUI_plot wait for user response (see UIRESUME)
% uiwait(handles.figure1);
global dir_info
global PLOT_info

% retrieve input arguments
param_dir = varargin{1};
handles.param_dir = param_dir;

% Initialize lists
code_dir = dir_info.code_dir;
output_filename = dir_info.output_filename;

clear storing_and_plotting
other_constants
collect_rundata

set(handles.listbox1, 'String', monitor_cmpds);

PLOT_info  = plot_info;

% Populate the listbox with compounds to plot

load_plot_cmpds(plot_info.plot_cmpds,handles)

% Update handles structure
guidata(hObject, handles);

% ------------------------------------------------------------
%  Load listbox with compounds to plot
% ------------------------------------------------------------
function load_plot_cmpds(plot_cmpds,handles)

figs_number = length(plot_cmpds);
for i = 1:figs_number
    cmpds_number = length(plot_cmpds{i});
    name{i} = [];
    for j = 1:cmpds_number
       name{i} = strcat(name{i},plot_cmpds{i}{j});
       if (j < cmpds_number)
          name{i} = strcat(name{i},',');
      end
    end
end

set (handles.listbox2, 'String', name, 'Value', 1);


% --- Outputs from this function are returned to the command line.
function varargout = GUI_plot_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
varargout{1} = handles.output;


% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


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

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


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

% Add compounds to monitor

global TEXT
global dir_info

param_dir = handles.param_dir;

GUI_text();
uiwait(GUI_text);
str = TEXT;
 
if ~isempty(str)
    
    if strcmpi(str,'all')

        param_dir = handles.param_dir;
        code_dir = dir_info.code_dir;

        other_constants
        collect_rundata
 
%    Modified to work with SBML files    -    Slava Chushak    
%                                             12/19/05
%    Look for *.mat files in the rxns_dir    
        file_list = dir(param_dir);
% If exist *.mat file, check whether it is an SBML model file    
        use_sbml = 0;   
        clear model
        for i = 1:size(file_list,1)
            file_name = file_list(i).name;
            if ~isempty(strfind(file_name,'.xml'))
                file_name = fullfile(param_dir,file_name);
                model = TranslateSBML(file_name);
                if isfield(model,'typecode')
                    use_sbml = 1;
                    break;
                end
            end
        end
        if use_sbml ==1
            n_cmpds =  size(model.species,2);
            if (model.SBML_level == 2)
                name_str = 'model.species(i).id';
            else
                name_str = 'model.species(i).name';
            end
     
            for i = 1:n_cmpds
              list{i} = eval(name_str);
            end
            clear model
        else
              
            read_cmpds
            n_cmpds = length(cmpd_list);
 
            for  i=1:n_cmpds
                list{i} = cmpd_list{i}{1};
            end 
        end
        set(handles.listbox1, 'String', list, 'Value', 1);
    else

%
% In case of several names separated by comma, tokenize string
%  
        list = get(handles.listbox1,'String');
        rem = str; 
        while true
            if isempty(rem)
                break;
            end

            [name, rem] = strtok(rem, ',');
   
            n_old = length(list); 
            add = 1;
                for i=1:n_old
                    if strcmp(list{i}, name)
                        add = 0;
                        break;
                    end
                end
    
            if add == 1
               list{n_old + 1} = name;
            end
        end

        set(handles.listbox1,'String', list, 'Value', 1);

    end
end

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

% Remove element from monitor list

index = get(handles.listbox1,'Value');
list = get(handles.listbox1,'String');

n_old = length(list);
j = 0;
for i = 1:n_old
   if (i ~= index)
       j=j+1;
       list_new{j} = list{i};
   end
end

set(handles.listbox1,'String', list_new, 'Value', 1); 
 
% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox2 (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
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end


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

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


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

% Add plot
global TEXT

param_dir = handles.param_dir;
GUI_add_plot();

uiwait(GUI_add_plot);
str = TEXT;
 
if ~isempty(str)
  if strcmpi(str, 'all')
    errordlg('You can''t put all compounds on same plot. Sorry!','Input Argument Error!')
     return
  else    
  list = get(handles.listbox2,'String');
   
    n_old = length(list); 
    list{n_old + 1} = str;
  
set(handles.listbox2,'String', list, 'Value', 1); 
  end
end

%  Check whether compounds are in the list to monitor. 
%  If not - add them.              Slava Chushak  12/20/05
% In case of several names separated by comma, tokenize string
%  
        list =[];
        list = get(handles.listbox1,'String');
        rem = str;  
        while true
            if isempty(rem)
                break;
            end

            [name, rem] = strtok(rem, ',');
               add = 1;
                n_old = length(list); 
                for i=1:n_old
                    if strcmp(list{i}, name)
                        add = 0;
                        break;
                    end
                end
    
            if add == 1
               list{n_old + 1} = name;
            end
        end
  
        set(handles.listbox1,'String', list, 'Value', 1);


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

% Remove element from monitor list

index = get(handles.listbox2,'Value');
list = get(handles.listbox2,'String');

n_old = length(list);
j = 0;
for i = 1:n_old
   if (i ~= index)
       j=j+1;
       list_new{j} = list{i};
   end
end

set(handles.listbox2,'String', list_new, 'Value', 1); 
 

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

% Apply   

% Save new lists into the storing_and_plottingm file
 
    param_dir = handles.param_dir;

    plot_file = fullfile(param_dir,'storing_and_plotting.m');
    temp_file = fullfile(param_dir,'plot.tmp');
    
    fout = fopen(temp_file,'w');
  if fout == -1
            errordlg('Cannot open plot.tmp file','Open File Error!')
            return
    end
        
    fin = fopen(plot_file);
    if fin == -1
            errordlg('Cannot open storing_and_plotting.m file','Open File Error!')
            return
    end
% Get new lists from GUI
    list_to_monitor = get(handles.listbox1,'String');
    list_to_plot = get(handles.listbox2,'String');
    n_to_monitor = length(list_to_monitor);
    n_to_plot = length(list_to_plot);
% Create new file    
    
    a = fgets(fin); 
    if isempty(strfind(a,'GUI'))
        fprintf(fout,'%% File created by GUI      \n\n'); 
    end
   
     while (a ~= -1)
            if strncmp(a,'monitor_cmpds',13) == 1
                fprintf(fout,'monitor_cmpds = {\n');
       % Save new list_to_monitor
                for i=1:n_to_monitor
                    fprintf(fout,'          ''%s'';\n',list_to_monitor{i});
                end
                fprintf(fout,'          };\n');
                while (a ~= -1)
                   a = fgets(fin);
                   if ~isempty(strfind(a,'};'))
                       break;
                   end
               end
                       a = fgets(fin);
            end
            
               if strncmp(a,'plot_cmpds',10) == 1
                
       % Save new list_to_plot
                for i=1:n_to_plot
                    fprintf(fout,'plot_cmpds{%d} = {',i);
                    rem = list_to_plot{i};
        % Tokenize the string            
                
                while true
                   if isempty(rem)
                       break;
                   end
                 [name, rem] = strtok(rem, ',');
                    fprintf(fout,'''%s'' ',name);
               end       
                    fprintf(fout,'};\n');
                end
               
               
                while (a ~= -1)
                   a = fgets(fin);
                   if isempty(strfind(a,'plot_cmpds'))
                       break;
                   end
                end
                    if (a ~= -1)
                       fprintf(fout,'%s',a); 
                    end
                       a = fgets(fin);
            end
            if (a ~= -1)
         fprintf(fout,'%s',a); 
            end
         a = fgets(fin);
       end

   fclose(fin);
   fclose(fout);
   
   movefile(temp_file,plot_file);
   
delete(handles.figure1);

% --- Executes on button press in pushbutton6.
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)

% Reset
global dir_info
param_dir = handles.param_dir;

cd (param_dir);
storing_and_plotting

cd (dir_info.code_dir);

set(handles.listbox1, 'String', monitor_cmpds);

load_plot_cmpds(plot_cmpds,handles)



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

delete(handles.figure1);


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


% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(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)


