function varargout = decon(varargin)
%DECON M-file for decon.fig
%      DECON, by itself, creates a new DECON or raises the existing
%      singleton*.
%
%      H = DECON returns the handle to a new DECON or the handle to
%      the existing singleton*.
%
%      DECON('Property','Value',...) creates a new DECON using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to decon_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      DECON('CALLBACK') and DECON('CALLBACK',hObject,...) call the
%      local function named CALLBACK in DECON.M with the given input
%      arguments.
%
%      *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 decon

% Last Modified by GUIDE v2.5 23-Feb-2010 10:00:41

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @decon_OpeningFcn, ...
                   'gui_OutputFcn',  @decon_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


function decon_OpeningFcn(hObject, eventdata, handles, varargin)

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

set(hObject,'toolbar','figure');

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes decon wait for user response (see UIRESUME)
% uiwait(handles.figure1);


function varargout = decon_OutputFcn(hObject, eventdata, handles)

% Get default command line output from handles structure
varargout{1} = handles.output;


%------------CALLBACKS----------
function edit_inputfile_measurements_Callback(hObject, eventdata, handles)

function edit_inputfile_PDF_Callback(hObject, eventdata, handles)

function pushbutton_inputbrowse1_Callback(hObject, eventdata, handles)
[soubor,cesta]=uigetfile('*.*');
s=strcat(cesta, soubor);
set(handles.edit_inputfile_measurements,'String',s);
inputE =load(s);
%Show text onscreen
set(handles.listbox_input,'String', inputE);
%Show text_log
t=strcat('Input file selected: ' ,soubor);
set(handles.text_log,'String', t );
guidata(hObject, handles); %updates the handles


function pushbutton_inputbrowse2_Callback(hObject, eventdata, handles)
[soubor,cesta]=uigetfile('*.*');
s=strcat(cesta, soubor);
set(handles.edit_inputfile_PDF,'String',s);
inputPDF =load(s);
%Show text_log
t=strcat('Experimental PDF file selected: ' , soubor);
set(handles.text_log,'String', t );
%Show text onscreen
kat=inputPDF(:,1);
exp_pdf=inputPDF(:,2);
set(handles.listbox_kategorie,'String', kat);
set(handles.listbox_PDF,'String', exp_pdf);
guidata(hObject, handles); %updates the handles


function edit_outputfilename_Callback(hObject, eventdata, handles)

function pushbutton_outputbrowse_Callback(hObject, eventdata, handles)
[soubor,cesta]=uiputfile('*.*');
s=strcat(cesta, soubor);
set(handles.edit_outputfilename,'String',s);
%Show text_log
t=strcat('Output file selected: ' , soubor);
set(handles.text_log,'String', t );
guidata(hObject, handles); %updates the handles


function edit7_max_iter_Callback(hObject, eventdata, handles)

function edit3_precision_Callback(hObject, eventdata, handles)

function edit2_M_Callback(hObject, eventdata, handles)

function listbox_input_Callback(hObject, eventdata, handles)

function listbox_kategorie_Callback(hObject, eventdata, handles)

function listbox_PDF_Callback(hObject, eventdata, handles)

function pushbutton_stop_Callback(hObject, eventdata, handles)
 set(handles.text_resume,'String','Click on graph to resume'); %change text
 w = waitforbuttonpress;
 set(handles.text_resume,'String',''); %change text

 
function pushbutton_calculate_Callback(hObject, eventdata, handles)

E =load(get(handles.edit_inputfile_measurements,'String'));%load property, e.g. E[GPa], save to vector E
exphist=load(get(handles.edit_inputfile_PDF,'String'));%load experimental probability density function
M=str2double(get(handles.edit2_M,'String')); %Number of phases
maxiter=str2double(get(handles.edit7_max_iter,'String')); %max number of iterations
limit=str2double(get(handles.edit3_precision,'String')); %precision

%----------------
%---Deconvolution algorithm
%-----------------
norma2=1;
minnorma=1;
%minmeze=1;
%minprumer=1;
%minstddev=1;
%minf=1;
iter=0;

maxE=max(E); %maximum value in E vector
N=length(E); %dimension of E vector

while( (norma2>limit) && (iter<=maxiter))
    r=rand(M-1,1); %nahodny vektor M-1 cisel 0,1
    r=sort(r); %vzestupne serazeny vektor r
    meze(1)=0;  %prvni mez je na nule
    pom= maxE .* r; % generace M-1 mezi z nahodneho vektoru 
    for i=1:M-1; 
    meze(i+1)=pom(i);  % generace M-1 mezi
    end
    meze(M+1)=maxE; %posledni mez

    sE=sort(E); %vzestupne serazeny vektor E

    for i=1:M+1
     index_meze(i)=N; %naplni vektor indexu maximalni hodnotou
    end
    index_meze(1)=0; %index pred prvni mezi je nula

    j=2; %zacinam od druhe meze (prvni je nula)
    mez=meze(j);

    for i=1:N %cyklus pres vsechny hodnoty
      if (sE(i) > mez) 
          index_meze(j)=i-1; %ulozi index hodnoty, ktera lezi pod mezi
          j=j+1;
          mez=meze(j);
      end
    end
    
    x=exphist(1,1); %prvni kategorie
    for i=1:M %cyklus pres faze
        vektor=sE(index_meze(i)+1:index_meze(i+1));
        if (length(vektor)>1)
          prumer(i) = mean(vektor);
          stddev(i) = std(vektor);
         else
          prumer(i) = 0;
          stddev(i) = 0;
        end
          f(i)=length(vektor)/N; %fraction      
    end

    for j=1:M %cyklus pres faze
       x=exphist(1,1);
       if (prumer(j)~=0)
         %p(1,j)=cdf('normal',x,prumer(j), stddev(j)); %cdf pro prvni kategorii
         p2(1,j)=pdf('normal',x,prumer(j), stddev(j)); %pdf
       else 
         %p(1,j)=0;
         p2(1,j)=0;
       end

       for i = 2 : length(exphist)  %cyklus pres vsechny kategorie
        x_prev=exphist(i-1,1);
        x=exphist(i,1);
        if (prumer(j)~=0)
         p2(i,j)=pdf('normal',x,prumer(j), stddev(j))*f(j);
         else 
        p2(i,j)=0;
       end
       end

    end

    norma2=0;
    for i = 1 : length(exphist)
      p_all2(i)=0;
      for j=1:M %cyklus pres faze
       p_all2(i)=p_all2(i)+p2(i,j);
      end
      norma2=norma2+(exphist(i,2)-p_all2(i))^2 * exphist(i,2)^2;
    end
    
    iter=iter+1;
    
    %onscreen output during iteration
    
    %Show text
    %t=strcat('Iteration: ' , num2str(iter))
    set(handles.text25_iter,'String',num2str(iter-1) );
    set(handles.text28_norm,'String', num2str(norma2) );
    drawnow;
    
    if(norma2<minnorma)
        % output if precision was reached
        minnorma=norma2;
        minmeze=meze;
        minprumer=prumer;
        minstddev=stddev;
        minf=f;
        %Show text output and graph
        axes(handles.graf_decon); %plots the x and y data
        cla;
        plot(exphist(:,1), exphist(:,2),'-ko');
        hold on; %legend ('show');

        %delete all lists
        set(handles.dist1,'String', '-' );
        set(handles.dist2,'String', '-' );
        set(handles.dist3,'String', '-' );
        set(handles.dist4,'String', '-' );
        set(handles.dist5,'String', '-' );
        set(handles.dist6,'String', '-' );

        for  j=1:M
         t=sprintf('%8.3f\n%8.3f\n%8.3f\n', minprumer(j), minstddev(j), minf(j));
         switch j
             case 1 
                 set(handles.dist1,'String', t ); plot(exphist(:,1),p2(:,1),'b');
             case 2
                 set(handles.dist2,'String', t ); plot(exphist(:,1),p2(:,2),'r');
             case 3
                 set(handles.dist3,'String', t ); plot(exphist(:,1),p2(:,3),'g');
             case 4
                 set(handles.dist4,'String', t ); plot(exphist(:,1),p2(:,4),'y');
             case 5
                 set(handles.dist5,'String', t ); plot(exphist(:,1),p2(:,5),'m');
             case 6
                 set(handles.dist6,'String', t ); plot(exphist(:,1),p2(:,6),'c');
             otherwise ;   
         end
        end
        drawnow;
        
        %graphical output
        %plot sum of all distributions
        plot(exphist(:,1),p_all2,':'); 
        switch M
            case 1
              legend ('Experiment','#1','Overall PDF');
            case 2
              legend ('Experiment','#1','#2','Overall PDF');
            case 3
              legend ('Experiment','#1','#2','#3','Overall PDF');
            case 4
              legend ('Experiment','#1','#2','#3','#4','Overall PDF');
            case 5
              legend ('Experiment','#1','#2','#3','#4','#5','Overall PDF');
            case 6
              legend ('Experiment','#1','#2','#3','#4','#5','#6','Overall PDF');
            otherwise ;   
        end
        %adds a title, x-axis description, and y-axis description
        %title('PDF');
        xlabel('Property');
        ylabel('Frequency density');
    end %end of if(norma2<minnorma)
 
end %end of iteration loop

%write to file
  soubor= get(handles.edit_outputfilename,'String');
  f=fopen(soubor, 'wt');
    fprintf(f,'Decon 3.0 ----Output----\n');
    fprintf(f,'Calculated on %s\n', datestr(now));
    fprintf(f,'Input file with the property: %s \n', get(handles.edit_inputfile_measurements,'String'));
    fprintf(f,'Input file with experimental PDF: %s \n', get(handles.edit_inputfile_PDF,'String'));
    fprintf(f,'\n-------------------\n');
    fprintf(f,'Number of iterations: %d\n',iter-1);
    fprintf(f,'Required norm= %e \n',limit);
    fprintf(f,'Resulting norm= %e \n',minnorma);
    fprintf(f,'\n-------------------\n');
    for j=1:M
     fprintf(f,'Distribution #%d \n',j);
     fprintf(f,'Mean %f\n',minprumer(j));
     fprintf(f,'St. Dev. %f\n',minstddev(j));
     fprintf(f,'Fraction %f\n',minf(j));
     fprintf(f,'-------------------\n');
    end
    fprintf(f,'\n------- End -------\n');
    fclose(f);
    %Show text_log
    t=strcat('Output file written to: ', soubor);
    set(handles.text_log,'String', t );

guidata(hObject, handles); %updates the handles

%----------------
%----end of Deconvolution algorithm
%-----------------



%----------------------------
%---------------Create functions------------------------
%------------------------------

function uipanel2_CreateFcn(hObject, eventdata, handles)

function text21_CreateFcn(hObject, eventdata, handles)

function text22_CreateFcn(hObject, eventdata, handles)

function text23_CreateFcn(hObject, eventdata, handles)

function pushbutton_inputbrowse1_CreateFcn(hObject, eventdata, handles)

function edit_inputfile_measurements_CreateFcn(hObject, eventdata, handles)

% 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 edit_inputfile_PDF_CreateFcn(hObject, eventdata, handles)

% 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 uipanel6_CreateFcn(hObject, eventdata, handles)

function text2_CreateFcn(hObject, eventdata, handles)

function edit_outputfilename_CreateFcn(hObject, eventdata, handles)

% 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 pushbutton_outputbrowse_CreateFcn(hObject, eventdata, handles)

function text6_CreateFcn(hObject, eventdata, handles)

function text12_CreateFcn(hObject, eventdata, handles)

function text7_CreateFcn(hObject, eventdata, handles)

function text8_CreateFcn(hObject, eventdata, handles)

function listbox_input_CreateFcn(hObject, eventdata, handles)

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function listbox_kategorie_CreateFcn(hObject, eventdata, handles)

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function listbox_PDF_CreateFcn(hObject, eventdata, handles)

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function text9_CreateFcn(hObject, eventdata, handles)

function text_log_CreateFcn(hObject, eventdata, handles)

function uipanel1_CreateFcn(hObject, eventdata, handles)

function edit7_max_iter_CreateFcn(hObject, eventdata, handles)

% 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 edit3_precision_CreateFcn(hObject, eventdata, handles)

% 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 text5_CreateFcn(hObject, eventdata, handles)

function edit2_M_CreateFcn(hObject, eventdata, handles)

% 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 pushbutton_calculate_CreateFcn(hObject, eventdata, handles)

function pushbutton_stop_CreateFcn(hObject, eventdata, handles)

function text3_CreateFcn(hObject, eventdata, handles)

function text4_CreateFcn(hObject, eventdata, handles)

function pushbutton_inputbrowse2_CreateFcn(hObject, eventdata, handles)





