%--------------------------------------------------------------------------
% Copyright 2012
% Sudharshan Varadarajan, H. M. N. Dilum Bandara and Anura P. Jayasumana,
% Colorado State University, Fort Collins, CO.
% http://www.cnrl.colostate.edu/
%
%  Licensed under the Apache License, Version 2.0 (the "License");
%  you may not use this file except in compliance with the License.
%  You may obtain a copy of the License at
% 
%      http://www.apache.org/licenses/LICENSE-2.0
% 
%  Unless required by applicable law or agreed to in writing, software
%  distributed under the License is distributed on an "AS IS" BASIS,
%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%  See the License for the specific language governing permissions and
%  limitations under the License.
%--------------------------------------------------------------------------

function varargout = QueryGen(varargin)

% QUERYGEN M-file for QueryGen.fig
%      QUERYGEN, by itself, creates a new QUERYGEN or raises the existing
%      singleton*.
%
%      H = QUERYGEN returns the handle to a new QUERYGEN or the handle to
%      the existing singleton*.
%
%      QUERYGEN('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in QUERYGEN.M with the given input arguments.
%
%      QUERYGEN('Property','Value',...) creates a new QUERYGEN or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before QueryGen_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to QueryGen_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 QueryGen
% Last Modified by GUIDE v2.5 13-Jul-2012 10:54:12
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @QueryGen_OpeningFcn, ...
    'gui_OutputFcn',  @QueryGen_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

% GLOBAL VARIABLE FOR SELECTED STATES
global Final_list_States;
low_level_states_mat = [];
global invisble;

% --- Executes just before QueryGen is made visible.
function QueryGen_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 QueryGen (see VARARGIN)

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

%Track ECDF values & sub-states
handles.queryData = struct('numResECDF', {}, 'subStates', {}, ...
    'stateTransitions', {});
guidata(hObject, handles); % Update handles structure

% UIWAIT makes QueryGen wait for user response (see UIRESUME)
% uiwait(handles.figure1);
set(handles.radioECDF, 'Value', get(handles.radioECDF,'Max'));


% --- Outputs from this function are returned to the command line.
function varargout = QueryGen_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 EditBxFileOpen_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxFileOpen (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 during object creation, after setting all properties.
function listbox_Attr_list_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox_Attr_list (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


% --- Executes on button press in BTNFileOpen.
function BTNFileOpen_Callback(hObject, eventdata, handles)
% hObject    handle to BTNFileOpen (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[fileName, pathName] = uigetfile('*.txt', 'Text Files (*.txt)', ...
    'Select query states file');
if isequal(fileName, 0)
    set(handles.EditBxFileOpen, 'String', '');
    return;
end

queryFileName = fullfile(pathName, fileName);
set(handles.EditBxFileOpen, 'String', queryFileName);
    
%Make sure file is a '.txt'
[tok, remain]= strtok(fileName, '.');
if (~strcmpi(remain, '.txt'))
    h = errordlg('Invalid input file.');
    uiwait(h);
    set(handles.EditBxFileOpen, 'String', '');
    return;
end
    
numResECDF = []; %empirical CDF of no of resources requested by query
fileState = ''; %what's being read from file
error = 0; %Error code
states = {};
subStates = {};
stateTransitions = [];

%Read one line at a time
fid = fopen(queryFileName);
line = fgetl(fid);  % Get first line of File
if(isempty(line))
    h = errordlg('Empty query states file. Closing query generator');  
    uiwait(h);
    set(handles.EditBxFileOpen, 'String', '');
    return;
end
        
while (line ~= -1)
    if strcmp(line(1), '#') %Skip comment lines starting with '#'
        line = fgetl(fid);
        continue;
    end
    
    if strcmpi(line, 'ECDF') %state of what's being read
        fileState = 'ECDF';
        line = fgetl(fid);
        continue;
    elseif strcmpi(line, 'STATES')
        fileState = 'STATES';
        line = fgetl(fid);
        continue;
    end
    
    r = regexp(line,'\t','split'); % Tokenize based on tab
    [m, n] = size(r);

    if strcmpi(fileState, 'ECDF') %Empirical CDF of no of resources
        if n ~= 2 %Colums for CDF values not 2
            error = -1;
        else
            numRes = str2num(char(r(1)));
            value = str2num(char(r(2)));
            numResECDF = [numResECDF; [numRes, value]];
        end
    elseif strcmpi(fileState, 'STATES')
        if n ~= 3 %Colums for states not 3
            error = -2;
        else
           %extract attribute name
           tmpAtts1 = regexp(char(r(1)), '_', 'split');
           tmpAtts2 = regexp(char(r(2)), '_', 'split');
           idx1 = -1; %Index for attribute 1
           idx2 = -1; %Index for attribute 2
           [mStates, nStates] = size(states); %No of states
           if nStates == 0 %Empty states list
               states{1} = tmpAtts1{1};
               states{2} = tmpAtts2{1};
           else %Search to see whether state is already in
               for i = 1:nStates
                   if strcmpi(states{i}, tmpAtts1{1})
                       idx1 = i;
                   elseif strcmpi(states{i}, tmpAtts2{1})
                       idx2 = i;
                   end
                   if (idx1 > 0) & (idx2 > 0) %Found both indexes
                       break;
                   end
               end
               if idx1 == -1 %No such state. Add new one
                   states{nStates + 1} = tmpAtts1{1};
               end
               if idx2 == -1 %No such state. Add new one
                   [mStates, nStates] = size(states); %No of states 
                   states{nStates + 1} = tmpAtts2{1};
               end
           end
           
           %Track sub-states
           idx1 = -1; %Index for attribute 1
           idx2 = -1; %Index for attribute 2
           [mStates, nStates] = size(subStates); %No of states
           if nStates == 0 %Empty sub-states list
               subStates{1} = char(r(1));
               subStates{2} = char(r(2));
               idx1 = 1;
               idx2 = 2;
           else %Search to see whether state is already in
               for i = 1:nStates
                   if strcmpi(subStates{i}, char(r(1)))
                       idx1 = i;
                   elseif strcmpi(subStates{i}, char(r(2)))
                       idx2 = i;
                   end
                   if (idx1 > 0) & (idx2 > 0) %Found both indexes
                       break;
                   end
               end
               if idx1 == -1 %No such state. Add new one
                   idx1 = nStates + 1; %Increment no of states
                   subStates{idx1} = char(r(1));
               end
               if idx2 == -1 %No such state. Add new one
                   [mStates, nStates] = size(subStates); %No of states
                   idx2 = nStates + 1; %Increment no of states
                   subStates{idx2} = char(r(2));
               end
           end
           %Append to list of state tranisions
           tmpState = [idx1, idx2, str2num(char(r(3)))];
           stateTransitions = [stateTransitions; tmpState];
        end
    else
        error = -3; %Unknown state
    end
               
    if error < 0
        h = '';
        if error == -1
            h = errordlg('Error in ECDF data. No of columns != 2.');
        elseif error == -2
            h = errordlg('Error in STATES data. No of columns != 3.');
        else
            h = errordlg(['Unknown tag in query state file.', line]);
        end
        uiwait(h);
        return;
    end
    
    line = fgetl(fid); % Get next Line from the File
end

fclose(fid); %close file
    
% Display unique states to user. Skip START & FINISH states
[mStates, nStates] = size(states); %No of states
tmpStates = {};
count = 1;
for i = 1:nStates
    if ~strcmpi(states{i}, 'START') & ~strcmpi(states{i}, 'FINISH')
        tmpStates{count} = states{i};
        count = count + 1;
    end
end
set(handles.lstboxUserStatesDisp, 'String', tmpStates);

%Update status
tmpStr = strcat('No of attributes in file: ', int2str(nStates - 2));
[m, n] = size(numResECDF);
if n > 0
    tmpStr = strcat(tmpStr, ...
        '. Has empirical CDF of number of resources to query. Max: ');
    tmpStr = strcat(tmpStr, int2str(numResECDF(m, n - 1)));
end
set(handles.EditBxStatus, 'String', tmpStr);

%guidata(hObject, handles); %Make public within GUI
handles.queryData = struct('numResECDF', {numResECDF}, ...
    'subStates', {subStates}, 'stateTransitions', {stateTransitions});
guidata(hObject,handles)


% --- Executes during object creation, after setting all properties.
function EditBxQuery_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxQuery (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 during object creation, after setting all properties.
function EditBxFileoutput_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxFileoutput (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 during object creation, after setting all properties.
function lstboxUserStatesDisp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lstboxUserStatesDisp (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


% --- Executes on button press in BTNSelect.
function BTNSelect_Callback(hObject, eventdata, handles, CallBack)
% hObject    handle to BTNSelect (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.EditBxStatus,'String','Generating queries.');%Update status

statesSelected = get(handles.lstboxUserStatesDisp, 'Value');
numStatesSelected = numel(statesSelected);
if numStatesSelected == 0
    h = errordlg('No states are selected. Select at least one state.');
    uiwait(h);
    return;
end

numQueries = str2num(get(handles.EditBxQuery, 'String'));
if numQueries <= 0
    h = errordlg('No of queries must be > 0.');
    uiwait(h);
    return;   
end

%Set seed
seed = str2num(get(handles.EditBxSeed, 'String'));
rand('twister', seed); %Set random seed.

outFileName = get(handles.EditBxFileoutput, 'String');
states = cellstr(get(handles.lstboxUserStatesDisp, 'String'));

%Find how to generate no of resources specified in a query
numResState = -1; %Use a state variable to track
param1 = -1; %Any parameters associated with state
param2 = -1;
if (get(handles.radioECDF, 'Value') == get(handles.radioECDF, 'Max'))
    numResState = 1;
elseif (get(handles.radioECDFInt, 'Value') == ...
        get(handles.radioECDFInt, 'Max'))
    numResState = 2;
elseif (get(handles.radioFixed, 'Value') == ...
        get(handles.radioFixed, 'Max'))
    numResState = 3;
    param1 = str2num(get(handles.EditBxFixed, 'String'));
elseif (get(handles.radioUniform, 'Value') == ...
        get(handles.radioUniform, 'Max'))
    numResState = 4;
    param1 = str2num(get(handles.EditBxUniMin, 'String'));
    param2 = str2num(get(handles.EditBxUniMax, 'String'));
    if param2 <= param1
        h = errordlg('Invalid range for ~Uniform(min, max), max <= min');
        uiwait(h);
        return;
    end
elseif (get(handles.radioGaus, 'Value') == ...
        get(handles.radioGaus, 'Max'))
    numResState = 5;
    param1 = str2num(get(handles.EditBxGausMean, 'String'));
    param2 = str2num(get(handles.EditBxGausStd, 'String'));
    if param2 < 0
        h = errordlg('Invalid STD for ~Gaussian(mean, std)');
        uiwait(h);
        return;
    end    
elseif (get(handles.radioExpo, 'Value') == ...
        get(handles.radioExpo, 'Max'))
    numResState = 6;
    param1 = str2num(get(handles.EditBxExpoMean, 'String'));
    if param1 < 0
        h = errordlg('Invalid mean for ~Exponential(mean).');
        uiwait(h);
        return;
    end    
else
    h = errordlg('Unknown option selected "No of resources per query".');
    uiwait(h);
    return;
end

selecStateTransi = []; %Selected state transitions
idxStart = -1; %index realted to START state
idxFinish = -1; %index realted to FINISH state

[mStateTrans, nStateTrans] = size(handles.queryData.stateTransitions);
%Pick sub-states based on states that user selects. Make sure both
%sub-states are selcted by user except when START & FINISH is involved
for i = 1:mStateTrans
    idx1 = handles.queryData.stateTransitions(i, 1);
    idx2 = handles.queryData.stateTransitions(i, 2);
    subState1 = regexp(handles.queryData.subStates(idx1), '_', 'split');
    subState2 = regexp(handles.queryData.subStates(idx2), '_', 'split');
    in1 = 0; %Are attributes selected by user
    in2 = 0;
    for j = 1:numStatesSelected
        stateSelectedStr = char(states(statesSelected(j)));
        if strcmpi(stateSelectedStr, subState1{1}{1})
            in1 = 1;
        elseif strcmpi('START', subState1{1}{1})
            in1 = 1;
            idxStart = idx1;
        end
        if strcmpi(stateSelectedStr, subState2{1}{1})
            in2 = 1;
        elseif strcmpi('FINISH', subState2{1}{1})
            in2 = 1;
            idxFinish = idx2;
        end
        if in1 & in2
            break;
        end
    end
    if in1 & in2%Are both attribue names in sub-states selected by user
        %Append to list of state tranisions
        tmpState = [idx1, idx2, handles.queryData.stateTransitions(i, 3)];
        selecStateTransi = [selecStateTransi; tmpState];
    end
end

%Find most occuring state & no of occurances
freqState = mode(selecStateTransi(:, 1)); %Most frequent state
tmpMtx = find(selecStateTransi(:, 1) == freqState); %List of index
%Largest no of sub-states ending from most frequent starting sub-state
maxNumEndStates = numel(tmpMtx);
%Find distinct start sub-states & no of them
startSubStates = unique(selecStateTransi(:, 1));
numStartStates = numel(startSubStates); %No

%Format of lookup matrix. Initialize with -1
%start-state|count|end state 1|count 1|end state 2|count 2|...|
%So no of columns = 2 + 2 * numSubStates
%No of rows = numStartStates
lookupMatrx = ones(numStartStates, (2 + 2 * maxNumEndStates)) * -1;

%Populate lookup matrix------------------------------------------------
for i = 1:numStartStates %Loop through each unique start sub-state
    tmpStartSubState = startSubStates(i, 1);
    tmpMtx = find(selecStateTransi(:, 1) == tmpStartSubState);
    lookupMatrx(i, 1) = tmpStartSubState; %Set as start state
    count = 0;
    for j = 1:numel(tmpMtx)
        lookupMatrx(i, 2 * j + 1) = selecStateTransi(tmpMtx(j), 2);
        count = count + selecStateTransi(tmpMtx(j), 3);
        lookupMatrx(i, 2 * j + 2) = count;
    end
    lookupMatrx(i, 2) = count;
end

%Query generation & dumping to file------------------------------------
eCDF = handles.queryData.numResECDF;
n = size(eCDF, 1);
fid = fopen(outFileName, 'w'); %Open output file
for i = 1:numQueries
    if mod(i, 1000) == 0 %Update status after every 1000 queries
        statusStr = strcat('No of queries generated: ', num2str(i));
        set(handles.EditBxStatus, 'String', statusStr);
    end
    m = -1; %No of resources per query
    %First generate no of resources
    if numResState == 1 %Inverse from ECDF
        rndNum = rand();
        for j = 1:n
            if rndNum <= eCDF(j, 2)
                m = eCDF(j, 1);
                break
            end
        end
    elseif numResState == 2 %Inverse from ECDF with interpolation
        m = round(interp1(eCDF(:, 2), eCDF(:, 1), rand()));
    elseif numResState == 3 %Fixed
        m = param1;
    elseif numResState == 4 %Uniform [param1, param2]
        m = round(param1 + rand()*(param2 - param1));
    elseif numResState == 5 %Gaussian
        m = round(normrnd(param1, param2));
    elseif numResState == 6 %Exponential
        m = round(exprnd(param1));
    end
    if m < 1 %make sure m is at least 1
        m = 1;
    elseif isnan(m)
        m = 1;
    end
    
    tmpStr = strcat('m_', num2str(m));
    idx = find(lookupMatrx(:, 1) == idxStart); %Index of START.
    if isempty(idx)
        h = errordlg('No valid state transitions available for selected states.');
        uiwait(h);
        return;
    end
    
    idxStartCopy = idx; %Copy for START index
    nextState = -1;
    while 1
        maxRange = lookupMatrx(idx, 2); %Find max range
        rndNum = rand()*maxRange;
        for j = 1:maxNumEndStates
            if rndNum <= lookupMatrx(idx, 2 + 2 * j)
                nextState = lookupMatrx(idx, 1 + 2 * j);
                break; %Found what's needed so stop
            end
            assert(lookupMatrx(idx, 2 + 2 * j) > 0);
        end
        if nextState == idxFinish %Reach end of sequence of states
            idx = idxStartCopy; %This speeds up rather than search again
            break;
        end
        tmpStr = strcat(tmpStr, '_');
        tmpStr = strcat(tmpStr, handles.queryData.subStates(nextState));
        idx = find(lookupMatrx(:, 1) == nextState); %Index
        %Check whether next state abrupty terminated because only
        %subset of the states are selected by users
        %If so, terminate current query
        if isempty(idx)
            idx = idxStartCopy; %This speeds up rather than search again
            break;
        end
    end
    %Dump query to file after replacing '_' with tab
    %MATLAB doesn't allow writing '\t' tags in siring
    splitTmpStr = regexp(char(tmpStr), '_', 'split');
    x = numel(splitTmpStr);
    for s = 1:x
        if s == x
            fprintf(fid, '%s\n', splitTmpStr{s}); %No tab for last line
        else
            fprintf(fid, '%s\t', splitTmpStr{s});
        end
    end
end

fclose(fid); %Close file
set(handles.EditBxStatus, 'String', 'Query generation complete.');


% --- Executes on button press in BTNBack.
function BTNBack_Callback(hObject, eventdata, handles)
% hObject    handle to BTNBack (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close all;
currentFolder = pwd;
file_url = [currentFolder '\ResQue.fig'];
backbtn = open(file_url);


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


% --- Executes on button press in BTNOutputFileBrowse.
function BTNOutputFileBrowse_Callback(hObject, eventdata, handles)
% hObject    handle to BTNOutputFileBrowse (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[fileName, pathName] = uiputfile('queries.txt', 'Save file name');
if isequal(fileName, 0)
    set(handles.EditBxFileoutput, 'String', 'Cancel selected');
else
    set(handles.EditBxFileoutput, 'String', fullfile(pathName, fileName));
    set(handles.BTNSelect, 'Enable', 'on')
end


% --- Executes during object creation, after setting all properties.
function EditBxStatus_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxStatus (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 during object creation, after setting all properties.
function EditBxSeed_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxSeed (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 during object creation, after setting all properties.
function EditBxUniMin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxUniMin (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 during object creation, after setting all properties.
function EditBxUniMax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxUniMax (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 during object creation, after setting all properties.
function EditBxFixed_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxFixed (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 EditBxExpoMean_Callback(hObject, eventdata, handles)
% hObject    handle to EditBxExpoMean (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 EditBxExpoMean as text
%        str2double(get(hObject,'String')) returns contents of EditBxExpoMean as a double


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


% --- Executes during object creation, after setting all properties.
function EditBxGausMean_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxGausMean (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 during object creation, after setting all properties.
function EditBxGausStd_CreateFcn(hObject, eventdata, handles)
% hObject    handle to EditBxGausStd (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 selected object is changed in panelNumRes.
function panelNumRes_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in panelNumRes 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
set(handles.EditBxFixed, 'Enable', 'off')
set(handles.EditBxUniMin, 'Enable', 'off')
set(handles.EditBxUniMax, 'Enable', 'off')
set(handles.EditBxGausMean, 'Enable', 'off')
set(handles.EditBxGausStd, 'Enable', 'off')
set(handles.EditBxExpoMean, 'Enable', 'off')
switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
    case 'radioFixed'
        set(handles.EditBxFixed, 'Enable', 'on')
    case 'radioUniform'
        set(handles.EditBxUniMin, 'Enable', 'on')
        set(handles.EditBxUniMax, 'Enable', 'on')        
    case 'radioGaus'
        set(handles.EditBxGausMean, 'Enable', 'on')
        set(handles.EditBxGausStd, 'Enable', 'on')
    case 'radioExpo'
        set(handles.EditBxExpoMean, 'Enable', 'on')
end
