
%--------------------------------------------------------------------------
% Program     : Rugosity by boxcounting (main.m)

% Written by  : Maysa Macedo

% email       : marcelo_at_cbpf.br ; maysagm_at_cbpf.br, dario_at_cbpf.br;
% albuquer_at_cbpf.br, luizlima_at_metalmat.ufrj.br

% Copyright(©): Centro Brasileiro de Pesquisas Fisicas - CBPF/MCT/Rio de Janeiro/Brazil

% Version     : 1.0

% Objective   : Rugosity Computing

% Compiler    : Matlab 7.1- R4-SP3

% Project     : -

% Authors     : Marcelo Portes de Albquerque; Maysa Macedo; Dario Oliveira,
% Marcio Portes de Albuquerque; Luiz Lima

% Mode        : In Matlab 7.1- R4-SP3 prompt, at the current directory, you should execute the comand:
% main;

% Comments    : This program is distributed in the hope that it will be useful,
%                but WITHOUT ANY WARRANTY; without even the implied warranty of
%                MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. It is FREEWARE.   
%--------------------------------------------------------------------------
function varargout = main(varargin)


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

% Last Modified by GUIDE v2.5 15-Nov-2006 15:52:47

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @main_OpeningFcn, ...
                   'gui_OutputFcn',  @main_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 main is made visible.
function main_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 main (see VARARGIN)

% Choose default command line output for main
fprintf(' Program     : Rugosity by boxcounting (main.m)\n');
fprintf(' Copyright(©): Centro Brasileiro de Pesquisas Fisicas -\n \t \t \t \t CBPF/MCT/Rio de Janeiro/Brazil- 2006\n');
handles.output = hObject;
handles.counter = 0;
handles.primeiro = 0;
handles.dimensaoFractal=[];
handles.inclinacao=[];
set(handles.axes2,'Visible','off');
axes(handles.axes1);cla reset;
set(handles.activex1,'AllColsText','Imagem;H;D.fractal');
set(handles.activex1,'AllColsWidth','5500;2500;2500','ReadOnly',1);
set(handles.textversao,'String','v061201_14:00')
% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = main_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;


% --------------------------------------------------------------------
function abrir_1_Callback(hObject, eventdata, handles)
% hObject    handle to abrir_1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%dirname = uigetdir('.\');



strOpcao={'AccurexII', 'JPK', 'Imagem'};
[tipoleitura,status] = listdlg('PromptString','Selecione o tipo de imagem:',...
                               'SelectionMode','single',...
                               'ListString',strOpcao,'ListSize',[120 50]);

if(~isempty(tipoleitura))
if tipoleitura==3    
    [filename,path, filterindex] = uigetfile({'*.bmp';'*.jpg';'*gif'},'Abrir Arquivo','..\matlab\imagens\novas imagens\','MultiSelect', 'on');
    
else
    [filename,path, filterindex] = uigetfile('*.txt','Abrir Arquivo','..\matlab\imagens\novas imagens\','MultiSelect', 'on');
    
end
    if (iscell(filename))
        abrirArquivo=1;
    elseif (strcmp(num2str(filename),'0'))
         abrirArquivo=0;
    else     
         abrirArquivo=1;
    end     
    if (abrirArquivo==1)
        bolCell = iscell(filename);
        if tipoleitura==3
            prompt = {'Entre com o tamanho:','Entre com a unidade do tamanho:','Entre com a escala (nm):'};
            dlg_title = 'Dados Imagem';
            num_lines = 1;
            def = {'2000','nm','0.67'};
            respInput = inputdlg(prompt,dlg_title,num_lines,def);
        else
            respInput ='';
        end
        if (bolCell==1)
            tam=size(filename);
        else
            tam=[1 1]; 
        end   
        h = waitbar(0,'Lendo imagem...');    
        for i=1:tam(2)
            strImagem='';
            if (bolCell==1)
                strImagem = strcat(char(path),char(filename(i)));
            else
                strImagem = strcat(char(path),char(filename));
            end  
            %-------------------------------------------
            DadosImagem(i) = LerDoc(strImagem,tipoleitura,respInput);
            %-------------------------------------------
           
            waitbar(i/tam(2));
        end
        close(h);
        handles.counter=0;
        handles.dimensaoFractal=[];
        handles.inclinacao=[];
        diretorio=path;
        posicao = strfind(diretorio,'\');
        indice = numel(posicao);
        if ( indice > 2 )
            caract = posicao(indice-1);
            diretorio=diretorio(caract:end-1);
        end  
        set(handles.text4,'String',strcat('.',diretorio));
        handles.path = path;
        handles.imagens = DadosImagem;
       
        handles.nomeImagens = filename;
        handles.numImagens = tam(2);
        
        set(handles.listbox1,'String',filename);
        set(handles.prox,'Enable','off');
        set(handles.ant,'Enable','off');
        if (handles.counter <= (handles.numImagens-1))
            handles.counter = handles.counter + 1;
        end
        
        if (handles.numImagens>1)
                set(handles.text2,'String',handles.nomeImagens{handles.counter});
                set(handles.txttamanho,'String',strcat(handles.imagens(handles.counter).imagesize,handles.imagens(handles.counter).zunit));
                set(handles.txtresolucao,'String',handles.imagens(handles.counter).imageresolution);
               
                if tipoleitura==3
                  axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);
                  figImagem=figure('Visible','off');
                  figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);
                else
                   axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);
                   figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);
                end
                
                
                matsize=size(handles.imagens(handles.counter).imagem);
                set(handles.prox,'Enable','on');
        else
               set(handles.text2,'String',handles.nomeImagens);
               set(handles.txttamanho,'String',strcat(handles.imagens.imagesize,handles.imagens.zunit));
               set(handles.txtresolucao,'String',handles.imagens.imageresolution);
                
               if tipoleitura==3
                     axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
                     figImagem=figure('Visible','off');
                     figImagem;imshow(handles.imagens.imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
               else
                   axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[-127 255]);
                   figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens.imagem,'DisplayRange',[-127 255]);
               end
              
               
              
               
               matsize=size(handles.imagens.imagem);
               handles.counter=handles.counter+1;
        end

        valorLista = get(handles.listbox1,'String');
        set(handles.BoxCounting1,'Enable','on');
        set(handles.BoxCounting2,'Enable','on');
        handles.figImagem = figImagem;
        set(handles.SalvarImagem,'Enable','on');
        set(handles.botaoSalvarImagem,'Enable','on');
        set(handles.SalvarGrafico,'Enable','off');
        set(handles.GerarRelatorio,'Enable','off');
        set(handles.txtdimfrac,'String','');
        set(handles.txthurst,'String','');
        set(handles.textcor,'BackgroundColor', [0.8784313797950745 0.8745098114013672 0.8901960849761963]); 
        axes(handles.axes1);cla reset;
        set(handles.activex1,'NRows',1);
        set(handles.BoxCounting1,'Checked','off');
        set(handles.BoxCounting2,'Checked','off');
        set(handles.Grid,'Value',0);
        set(handles.txtptSaturacao,'String','');
        set(handles.txtDimFracTotal,'String','');
        set(handles.txtHtotal,'String','');
        set(handles.activex1,'Row',0);set(handles.activex1,'Col',0);set(handles.activex1,'Text','');
        set(handles.activex1,'Row',0); set(handles.activex1,'Col',1); set(handles.activex1,'Text','');
        set(handles.activex1,'Row',0); set(handles.activex1,'Col',2); set(handles.activex1,'Text','');
        handles.legendCor='';
        handles.tipoleitura=tipoleitura;
        % Update handles structure
        guidata(hObject, handles);
    end
end
% --------------------------------------------------------------------

% --- Executes on button press in BoxCounting1.
function BoxCounting1_Callback(hObject, eventdata, handles)
% hObject    handle to BoxCounting1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 set(handles.activex1,'NRows',handles.numImagens);
  set(handles.BoxCounting1,'Checked','on');
  set(handles.BoxCounting2,'Checked','off');
  handles.inclinacao=[];
  handles.counter=1;
     h = waitbar(0,'Calculando...');    
     for i=1:handles.numImagens
       grafico(i) = CalculaRugosidade(handles.imagens(i),1);
       Ajuste=Fitting(grafico(i),2);
       set(handles.activex1,'Row',i-1);
       set(handles.activex1,'Col',0);
       if (handles.numImagens>1)
         set(handles.activex1,'Text',handles.nomeImagens{i});
       else
         set(handles.activex1,'Text',handles.nomeImagens); 
       end  
       set(handles.activex1,'Col',1);
       handles.inclinacao(i) = -Ajuste.linhaFit(2,1)/Ajuste.linhaFit(2,2);
       handles.dimensaoFractal(i) = 3- handles.inclinacao(i);
       set(handles.activex1,'Text',num2str(handles.inclinacao(i))); 
       set(handles.activex1,'Col',2);
       set(handles.activex1,'Text',num2str(handles.dimensaoFractal(i)));
       waitbar(i/handles.numImagens);
       clear Ajuste;
     end
     close(h);
     cores=['c' 'm'];
     Ajuste=Fitting(grafico,2);
     figGrafico = figure('visible','off');
     figGrafico; legendCor=MostraGrafico(grafico,handles.numImagens,handles.nomeImagens);
     hold on
     for(i=2:2)
         fplot(@(x)(-Ajuste.linhaFit(i,1)*x-Ajuste.linhaFit(i,3))/Ajuste.linhaFit(i,2),[Ajuste.minimo Ajuste.maximo],cores(i));
     end
     hold off
     axes(handles.axes1);MostraGrafico(grafico,handles.numImagens,handles.nomeImagens);
     hold on
      for(i=2:2)
         fplot(@(x)(-Ajuste.linhaFit(i,1)*x-Ajuste.linhaFit(i,3))/Ajuste.linhaFit(i,2),[Ajuste.minimo Ajuste.maximo],cores(i));
     end
     hold off
     handles.legendCor = legendCor;
     switch(legendCor(handles.counter))
         case 'b' 
            set(handles.textcor,'BackgroundColor', [0.0 0.0 1.0]); 
         case 'g' 
             set(handles.textcor,'BackgroundColor', [0.0 1.0 0.0]);
         case 'm' 
            set(handles.textcor,'BackgroundColor',[1.0 0.0 1.0]);
         case 'r' 
         set(handles.textcor,'BackgroundColor',[1.0 0.0 0.0]);
         case 'y' 
            set(handles.textcor,'BackgroundColor',[1.0 1.0 0.502]);
         case 'k' 
           set(handles.textcor,'BackgroundColor',[0.0 0.0 0.0]);
     end       
     set(handles.ant, 'Enable', 'off');
     if (handles.numImagens>1 )
         set(handles.txtdimfrac,'String',handles.dimensaoFractal(handles.counter));  
         set(handles.txthurst,'String',handles.inclinacao(handles.counter));
         set(handles.text2,'String',handles.nomeImagens{handles.counter});
         set(handles.txttamanho,'String',strcat(handles.imagens(handles.counter).imagesize,handles.imagens(handles.counter).zunit));
         set(handles.txtresolucao,'String',handles.imagens(handles.counter).imageresolution);
         set(handles.prox, 'Enable', 'on');
         
     else
         set(handles.txtdimfrac,'String',handles.dimensaoFractal);  
         set(handles.txthurst,'String',handles.inclinacao);
         set(handles.text2,'String',handles.nomeImagens);
         set(handles.txttamanho,'String',strcat(handles.imagens.imagesize,handles.imagens.zunit));
         set(handles.txtresolucao,'String',handles.imagens.imageresolution);
         set(handles.prox, 'Enable', 'off');
        
     end    
     set(handles.Grid,'Enable','on');  
     set(handles.SalvarGrafico,'Enable','on');
     set(handles.botaoSalvarGrafico,'Enable','on');
     set(handles.SalvarTela,'Enable','on');
     set(handles.GerarRelatorio,'Enable','on');
     % H é o coeficiente angular da reta 2 (vertical) ,ou seja, letra a de (ax+by+c=0)
     inclinacao=-Ajuste.linhaFit(2,1)/Ajuste.linhaFit(2,2);
     set(handles.txtHtotal,'String',strcat('H Total: ',num2str(inclinacao))); 

     %Dimensão fractal total é 3-H que é o coeficiente angular da reta 2
     %(vertical), ou seja,  -a/b de (ax+by+c=0)
     set(handles.txtDimFracTotal,'String',strcat('Dimensão Fractal Total: ',num2str(3-inclinacao))); 
     set(handles.txtptSaturacao,'String',strcat('Ponto de Saturação: ',num2str(Ajuste.ptSaturacao))); 

   
     
    handles.figGrafico = figGrafico;
      
    % Update handles structure
    guidata(hObject, handles);
   
% -------------------------------------------------------------------- 

% --- 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 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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
%    set(hObject,'BackgroundColor','white');
%end




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

% Hint: get(hObject,'Value') returns toggle state of Grid
  status=get(hObject,'Value');
  axes(handles.axes1);
  
  if (status==1)
      grid on;
      legend(handles.nomeImagens,'Location','SouthEast');
      set(handles.figGrafico,'Visible','on');
      handles.figGrafico;
      grid on;
      legend(handles.nomeImagens,'Location','SouthEast');
      set(handles.figGrafico,'Visible','off');
  else
      grid off;
      legend(handles.nomeImagens,'Location','SouthEast'); 
      set(handles.figGrafico,'Visible','on');
      handles.figGrafico;
      grid off;
      legend(handles.nomeImagens,'Location','SouthEast');
      set(handles.figGrafico,'Visible','off');
     % grid off;
     % legend(handles.nomeImagens,'Location','SouthEast'); 
  end
 %legend(handles.nomeImagens,'Location','SouthEast');
  % Update handles structure
  guidata(hObject, handles);
 
% --------------------------------------------------------------------


function SalvarGrafico_Callback(hObject, eventdata, handles)
% hObject    handle to SalvarGrafico (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    print(handles.figGrafico,'GraficoRugosidade','-depsc','-tiff') % print it
   

% --------------------------------------------------------------------
function SalvarImagem_Callback(hObject, eventdata, handles)
% hObject    handle to SalvarImagem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if handles.numImagens>1
    if handles.counter>handles.numImagens handles.counter=handles.numImagens;
    elseif handles.counter<1
        handles.counter=1;
    end
   
    nome=handles.nomeImagens{handles.counter};
else
    nome=handles.nomeImagens;
end
print(handles.figImagem,nome(1:end-4),'-depsc','-tiff') % print it

% --------------------------------------------------------------------
function SalvarTela_Callback(hObject, eventdata, handles)
% hObject    handle to SalvarTela (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 print -depsc -tiff 'TelaRugosidade' % print it

% --------------------------------------------------------------------

% --- Executes on button press in ant.
function ant_Callback(hObject, eventdata, handles)
% hObject    handle to ant (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if (handles.counter  > 0 && handles.counter<=handles.numImagens+1 )
    if (handles.counter==handles.numImagens+1)
           handles.counter = handles.counter - 2;
    else
           handles.counter = handles.counter - 1;
    end
    
      if (handles.counter <= handles.numImagens)
           set(handles.prox,'Enable','on');
           set(handles.prox,'ForegroundColor',[0.0,0.5019607843137255,1.0])
           set(handles.text2,'String','');
           if (handles.numImagens>1)
               set(handles.text2,'String',handles.nomeImagens{handles.counter});
               set(handles.txttamanho,'String',strcat(handles.imagens(handles.counter).imagesize,handles.imagens(handles.counter).zunit));
               set(handles.txtresolucao,'String',handles.imagens(handles.counter).imageresolution);
               if (~isempty(handles.dimensaoFractal))
                  set(handles.txtdimfrac,'String',handles.dimensaoFractal(handles.counter));  
                  set(handles.txthurst,'String',handles.inclinacao(handles.counter));  
               end
                
                if handles.tipoleitura==3
                  axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);
                  figImagem=figure('Visible','off');
                  figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);    
               else
                   axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);
                   figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);    
               end
               matsize=size(handles.imagens(handles.counter).imagem);
           else
               set(handles.text2,'String',handles.nomeImagens);
               set(handles.txttamanho,'String',strcat(handles.imagens.imagesize,handles.imagens.zunit));
               set(handles.txtresolucao,'String',handles.imagens.imageresolution);
               if (~isempty(handles.dimensaoFractal))
                  set(handles.txtdimfrac,'String',handles.dimensaoFractal);  
                  set(handles.txthurst,'String',handles.inclinacao);  
               end
               figImagem=figure('Visible','off');
                if handles.tipoleitura==3
                     axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
                     figImagem=figure('Visible','off');
                     figImagem;imshow(handles.imagens.imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
              else
                   axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[-127 255]);
                   figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens.imagem,'DisplayRange',[-127 255]);
               end
               matsize=size(handles.imagens.imagem);
           end
           if (strcmp(get(handles.BoxCounting1,'Checked'),'on') || strcmp(get(handles.BoxCounting2,'Checked'),'on'))
           switch(handles.legendCor(handles.counter))
             case 'b' 
                set(handles.textcor,'BackgroundColor', [0.0 0.0 1.0]); 
             case 'g' 
                 set(handles.textcor,'BackgroundColor', [0.0 1.0 0.0]);
             case 'm' 
                set(handles.textcor,'BackgroundColor',[1.0 0.0 1.0]);
             case 'r' 
             set(handles.textcor,'BackgroundColor',[1.0 0.0 0.0]);
             case 'y' 
                set(handles.textcor,'BackgroundColor',[1.0 1.0 0.502]);
             case 'k' 
               set(handles.textcor,'BackgroundColor',[0.0 0.0 0.0]);
           end        
          end  
%          set(handles.text22,'String',strcat(strcat(num2str(matsize(1)),'x'),num2str(matsize(2))));
        
      end
       handles.figImagem=figImagem;  
       if (handles.counter  == 1)
            set(handles.ant,'Enable','off');
            set(handles.ant,'ForegroundColor',[0.0,0.0,0.0])
       end
  
end

% Update handles structure
guidata(hObject, handles);



% --------------------------------------------------------------------
% --- Executes on button press in prox.
function prox_Callback(hObject, eventdata, handles)
	% hObject    handle to prox (see GCBO)
	% eventdata  reserved - to be defined in a future version of MATLAB
	% handles    structure with handles and user data (see GUIDATA)
   
	if (handles.counter <= (handles.numImagens-1))
	    handles.counter = handles.counter + 1;
	end
	
	if (handles.counter <=handles.numImagens)
        
       set(handles.text2,'String','');
       if ( handles.primeiro==0 )
           set(handles.axes2,'Visible','on');
           handles.primeiro=handles.primeiro+1;
       end
       if (handles.numImagens>1)
             set(handles.text2,'String',handles.nomeImagens{handles.counter});
             set(handles.txttamanho,'String',strcat(handles.imagens(handles.counter).imagesize,handles.imagens(handles.counter).zunit));
             set(handles.txtresolucao,'String',handles.imagens(handles.counter).imageresolution);
             if (~isempty(handles.dimensaoFractal))
                 set(handles.txtdimfrac,'String',handles.dimensaoFractal(handles.counter));  
                 set(handles.txthurst,'String',handles.inclinacao(handles.counter));  
             end
            
            if handles.tipoleitura==3
                  axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);
                   figImagem=figure('Visible','off');
                  figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens(handles.counter).imagem(:,:))) max(max(handles.imagens(handles.counter).imagem(:,:)))]);    
            else
                   axes(handles.axes2);imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);
                    figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);    
            end
             
          
             matsize=size(handles.imagens(handles.counter).imagem);
       else
            set(handles.text2,'String',handles.nomeImagens);
            set(handles.txttamanho,'String',strcat(handles.imagens.imagesize,handles.imagens.zunit));
            set(handles.txtresolucao,'String',handles.imagens.imageresolution);
            if (~isempty(handles.dimensaoFractal))
                set(handles.txtdimfrac,'String',handles.dimensaoFractal);  
                set(handles.txthurst,'String',handles.inclinacao); 
            end
           
           if handles.tipoleitura==3
                     axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
                      figImagem=figure('Visible','off');
                     figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[min(min(handles.imagens.imagem(:,:))) max(max(handles.imagens.imagem(:,:)))]);
           else
                   axes(handles.axes2);imshow(handles.imagens.imagem,'DisplayRange',[-127 255]);
                    figImagem=figure('Visible','off');
                   figImagem;imshow(handles.imagens(handles.counter).imagem,'DisplayRange',[-127 255]);
            end
            
           
            matsize=size(handles.imagens.imagem);
       end
       if (strcmp(get(handles.BoxCounting1,'Checked'),'on') || strcmp(get(handles.BoxCounting2,'Checked'),'on'))
         switch(handles.legendCor(handles.counter))
           case 'b' 
            set(handles.textcor,'BackgroundColor', [0.0 0.0 1.0]); 
            case 'g' 
             set(handles.textcor,'BackgroundColor', [0.0 1.0 0.0]);
           case 'm' 
            set(handles.textcor,'BackgroundColor',[1.0 0.0 1.0]);
           case 'r' 
             set(handles.textcor,'BackgroundColor',[1.0 0.0 0.0]);
           case 'y' 
            set(handles.textcor,'BackgroundColor',[1.0 1.0 0.502]);
           case 'k' 
           set(handles.textcor,'BackgroundColor',[0.0 0.0 0.0]);
         end   
       end
       
        set(handles.ant,'Enable','on');
        set(handles.ant,'ForegroundColor',[0.0,0.5019607843137255,1.0]);
        handles.figImagem=figImagem;
        if (handles.counter == handles.numImagens)
                 handles.counter=handles.counter+1;
                 set(handles.prox,'Enable','off');
                 set(handles.prox,'ForegroundColor',[0.0,0.0,0.0])
        end
        
    end
    
   
	% Update handles structure
	guidata(hObject, handles);



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

button = questdlg('Deseja realmente sair?', ...
                            'Sair','Sim','Nao','Nao');
switch button
            case 'Sim',
               close
            case 'Nao',
              quit cancel;
end




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

  set(handles.activex1,'NRows',handles.numImagens);
  set(handles.BoxCounting1,'Checked','off');
  set(handles.BoxCounting2,'Checked','on');
  handles.inclinacao=[];
  handles.dimensaoFractal=[];
  handles.counter = 1;
 
     h = waitbar(0,'Calculando...');    
     for i=1:handles.numImagens
       grafico(i) = CalculaRugosidade(handles.imagens(i),2);
       Ajuste=Fitting(grafico(i),2);
       set(handles.activex1,'Row',i-1);
       set(handles.activex1,'Col',0);
       if (handles.numImagens>1)
         set(handles.activex1,'Text',handles.nomeImagens{i});
       else
         set(handles.activex1,'Text',handles.nomeImagens); 
       end
       handles.inclinacao(i) = -Ajuste.linhaFit(2,1)/Ajuste.linhaFit(2,2);
       handles.dimensaoFractal(i) = 3- handles.inclinacao(i); 
       set(handles.activex1,'Col',1);
       %inclinacao
       set(handles.activex1,'Text',num2str(handles.inclinacao(i))); 
       
       set(handles.activex1,'Col',2);
       %dimensao fractal
       set(handles.activex1,'Text',num2str(handles.dimensaoFractal(i)));
      
       
       waitbar(i/handles.numImagens);
       clear Ajuste;
     end
     
     close(h);
     cores=['c' 'm'];
     Ajuste=Fitting(grafico,2);
     figGrafico = figure('visible','off');
     figGrafico; legendCor=MostraGrafico(grafico,handles.numImagens,handles.nomeImagens);
     hold on
     for(i=2:2)
         fplot(@(x)(-Ajuste.linhaFit(i,1)*x-Ajuste.linhaFit(i,3))/Ajuste.linhaFit(i,2),[Ajuste.minimo Ajuste.maximo],cores(i));
     end
     hold off
     axes(handles.axes1);MostraGrafico(grafico,handles.numImagens,handles.nomeImagens);
     hold on
      for(i=2:2)
         fplot(@(x)(-Ajuste.linhaFit(i,1)*x-Ajuste.linhaFit(i,3))/Ajuste.linhaFit(i,2),[Ajuste.minimo Ajuste.maximo],cores(i));
     end
     hold off
     handles.legendCor=legendCor;
     switch(legendCor(handles.counter))
         case 'b' 
            set(handles.textcor,'BackgroundColor', [0.0 0.0 1.0]); 
         case 'g' 
             set(handles.textcor,'BackgroundColor', [0.0 1.0 0.0]);
         case 'm' 
            set(handles.textcor,'BackgroundColor',[1.0 0.0 1.0]);
         case 'r' 
         set(handles.textcor,'BackgroundColor',[1.0 0.0 0.0]);
         case 'y' 
            set(handles.textcor,'BackgroundColor',[1.0 1.0 0.502]);
         case 'k' 
           set(handles.textcor,'BackgroundColor',[0.0 0.0 0.0]);
     end        
     
     set(handles.ant, 'Enable', 'off');
     if (handles.numImagens>1 )
         set(handles.txtdimfrac,'String',handles.dimensaoFractal(handles.counter));  
         set(handles.txthurst,'String',handles.inclinacao(handles.counter));
         set(handles.text2,'String',handles.nomeImagens{handles.counter});
         set(handles.txttamanho,'String',strcat(handles.imagens(handles.counter).imagesize,handles.imagens(handles.counter).zunit));
         set(handles.txtresolucao,'String',handles.imagens(handles.counter).imageresolution);
         set(handles.prox, 'Enable', 'on');
         
     else
         set(handles.txtdimfrac,'String',handles.dimensaoFractal);  
         set(handles.txthurst,'String',handles.inclinacao);
         set(handles.text2,'String',handles.nomeImagens);
         set(handles.txttamanho,'String',strcat(handles.imagens.imagesize,handles.imagens.zunit));
         set(handles.txtresolucao,'String',handles.imagens.imageresolution);
         set(handles.prox, 'Enable', 'off');
        
     end    
     set(handles.Grid,'Enable','on');  
     set(handles.SalvarGrafico,'Enable','on');
     set(handles.botaoSalvarGrafico,'Enable','on');
     set(handles.SalvarTela,'Enable','on');
     set(handles.GerarRelatorio,'Enable','on');
     

     % H é o coeficiente angular da reta 2 (vertical) ,ou seja, letra a de (ax+by+c=0)
     inclinacao=-Ajuste.linhaFit(2,1)/Ajuste.linhaFit(2,2);
     set(handles.txtHtotal,'String',strcat('H Total: ',num2str(inclinacao))); 

     %Dimensão fractal total é 3-H que é o coeficiente angular da reta 2
     %(vertical), ou seja, letra -a/b de (ax+by+c=0)
     set(handles.txtDimFracTotal,'String',strcat('Dimensão Fractal Total: ',num2str(3-inclinacao))); 
     set(handles.txtptSaturacao,'String',strcat('Ponto de Saturação: ',num2str(Ajuste.ptSaturacao))); 
     
    handles.figGrafico = figGrafico;
      
    % Update handles structure
    guidata(hObject, handles);


% --------------------------------------------------------------------
function GerarRelatorio_Callback(hObject, eventdata, handles)
% hObject    handle to GerarRelatorio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
filename = '';
filename = strcat('Relatorio_',strcat(strrep(strrep(datestr(now),':','_'),' ','_'),'.html'));
mkdir(filename);
cd(filename);
fid = fopen(filename, 'w');
relStr = '<html><table width="670"><tr><td><center><b><font face="verdana" size="3">Relatório Rugosidade - BoxCounting ';
fprintf(fid,relStr);relStr='';
relStr = '</font></b></center><br><font face="verdana" size="1">Data:';
fprintf(fid,relStr);relStr='';
relStr= datestr(now);
fprintf(fid,relStr);relStr='';
relStr = strcat('<br>Diretório: ',strrep(handles.path,'\','/'));
fprintf(fid,relStr);relStr='';
if strcmp(get(handles.BoxCounting1,'Checked'),'on')
   relStr = '<br>Algoritmo: BoxCounting tradicional ';
   fprintf(fid,relStr);relStr='';
else
   relStr = '<br>Algoritmo: BoxCounting 4 camadas ';
   fprintf(fid,relStr);relStr='';
end
relStr = '</font></td></tr><tr><td><table width="670"><tr><td colspan="2" bgcolor="#CCCCCC"><font face="verdana" size="2"> <b>Lista de Imagen(s):</b> </font></td></tr>';
fprintf(fid,relStr);relStr='';
Fighand = figure('visible','off');

clear filename;
for i = 1:handles.numImagens
   figname='';
   figname = strrep(strrep(datestr(now),':','_'),' ','_');
   figname = strcat(strcat('Fig',num2str(i)),figname);
   if handles.tipoleitura==3
       Fighand;imshow(handles.imagens(i).imagem,[min(min(handles.imagens(i).imagem(:,:))) max(max(handles.imagens(i).imagem(:,:)))]);
   else
       Fighand;imshow(handles.imagens(i).imagem,[-127 255]);
   end    
   print(Fighand,figname,'-djpeg') % print it
   relStr=strcat(relStr,'<tr><td valing="top" ><font face="verdana"><img src="');
   fprintf(fid,relStr);   relStr='';
   relStr= strcat(relStr,figname);
   fprintf(fid,relStr);   relStr='';   
   relStr= '.jpg" width="200" height="150" ></td><td backgroundcolor="#ffff06" width="550"><font face="verdana" size="2">Nome: ';
   fprintf(fid,relStr);   relStr='';   
   if (handles.numImagens>1) relStr=cell2mat(handles.nomeImagens(i));else relStr=handles.nomeImagens;end;
   fprintf(fid,relStr);   relStr='';   
   relStr= strcat(relStr,strcat('<br>Resolução: ',num2str(handles.imagens(i).imageresolution)));
   fprintf(fid,relStr);   relStr='';
   relStr= strcat(relStr,strcat('<br>Tamanho: ',handles.imagens(i).imagesize));
   fprintf(fid,relStr);   relStr='';
   relStr= strcat(relStr,strcat(' ',handles.imagens(i).zunit));
   fprintf(fid,relStr);   relStr='';
   relStr= strcat(relStr,strcat('<br>H: ',num2str(handles.inclinacao(i))));
   fprintf(fid,relStr);   relStr='';
   relStr= strcat(relStr,strcat('<br>Dimensão Fractal: ',num2str(handles.dimensaoFractal(i))));
   fprintf(fid,relStr);   relStr='';
   relStr=strcat(relStr,'<br></font></td></tr>');
   fprintf(fid,relStr);   relStr='';
   im=imresize(imread(strcat(figname,'.jpg')),[150 200],'bilinear');
   imwrite(im,strcat(figname,'.jpg'));
   clear im;
   
end
clear figname;
relStr='</table></td></tr><tr><td bgcolor="#CCCCCC" ><font face="verdana" size="2"><b>';
fprintf(fid,relStr);   relStr='';
relStr='Gráfico:</b></td><tr><tr><td><br><center>';
fprintf(fid,relStr);   relStr='';
fignameGraf='';
fignameGraf = strrep(strrep(datestr(now),':','_'),' ','_');
fignameGraf = strcat(strcat('Graf',num2str(i)),fignameGraf);
print(handles.figGrafico,fignameGraf,'-djpeg') % print it
relStr = '<img src="';
fprintf(fid,relStr);   relStr='';
relStr =  strcat(fignameGraf,'.jpg');
fprintf(fid,relStr);   relStr='';
relStr = '"  ></center></td></tr>';
fprintf(fid,relStr);   relStr='';
relStr = '<tr><td><font face="verdana" size="2">';
fprintf(fid,relStr);   relStr='';
relStr =  num2str(get(handles.txtHtotal,'String'));
fprintf(fid,relStr);

relStr = '<br> ';
fprintf(fid,relStr);
relStr = num2str(get(handles.txtDimFracTotal,'String'));
fprintf(fid,relStr);
relStr = '<br>';
fprintf(fid,relStr);
relStr =  num2str(get(handles.txtptSaturacao,'String'));
fprintf(fid,relStr);
relStr = '<br></font><hr><font face="verdana" size="1"><br>Gerado pelo programa BOXCOUNTING produzido no CAT-<b>CBPF</b>-BRASIL</font></td></tr></table></html>';
fprintf(fid,relStr);
fclose(fid);
im=imresize(imread(strcat(fignameGraf,'.jpg')),[500 550],'bilinear');
imwrite(im,strcat(fignameGraf,'.jpg'));
clear im;
cd('..');
clear relStr;clear fignameGraf;clear fid;
