function varargout = ForensicAnalyzer(varargin)
%----------------------------------------------------------------------    
%             [ Forensic Analyser GUI Application ]
%
%  Propose: To indentify the acquisition history of a query image  
%  Important inputs:    1) Dictionary Database
%                       2) Query Image
%
% Last mofification: 20 January 2013  
% Programmed by Thirapiroon Thongkamwitoon 
% Communications and Signal Processing Research Group
% Department of Electrical and Electronic Engineering
% Imperial College London, South Kensington Campus, London SW7 2AZ
%
% Email : tt1410@imperial.ac.uk, thirapiroon@yahoo.com 
%======================================================================

% Last Modified by GUIDE v2.5 18-Feb-2013 18:34:32

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

% Choose default command line output for ForensicAnalyzer

%========== GUI Intialization ============
handles.output = hObject;
clc;
axes(handles.DisplayImage);
cla;
set(gca,'XTick',[],'YTick',[]);

axes(handles.ShowSelectedArea);
cla;
set(gca,'XTick',[],'YTick',[]);

axes(handles.ShowClassConfidence);
cla;
set(gca,'XTick',[],'YTick',[]);

set( handles.ShowDictName, 'String', 'NULL');
set( handles.ShowNoOfElements, 'String', '0');
%=========================================
% Decoration==============

axes(handles.RewindLogo);
set(gca,'XTick',[],'YTick',[]);
logofile=strcat(pwd,'\GUI_data\rewind_logo.png');
 imREWINDlogo= imread(logofile);
imshow(imREWINDlogo);

axes(handles.ImperialLogo);
set(gca,'XTick',[],'YTick',[]);
logofile=strcat(pwd,'\GUI_data\ic_logo.png');
 imREWINDlogo= imread(logofile);
imshow(imREWINDlogo);

%========================

addpath('Functions');

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = ForensicAnalyzer_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 on button press in LoadDictButton.
function LoadDictButton_Callback(hObject, eventdata, handles)
%--------------------------------------------------------
%  This function is in action when the "Load" button is pressed. 
%  
%  It loads a dictionary file in order to build the create dictionary for classification. 
%--------------------------------------------------------

[Myfile,MyPath] = uigetfile('*.mat','Load Dictionary');
filename=strcat(MyPath,Myfile);
global CurrentDict;
CurrentDict = importdata(filename);


global nDictionary;

nDictionary=GenerateDictionary(CurrentDict,512,1);

set( handles.ShowDictName, 'String',Myfile);

set( handles.ShowNoOfElements, 'String', num2str(size(CurrentDict,1)));

return

% --- Executes on button press in LoadImageButton.
function LoadImageButton_Callback(hObject, eventdata, handles)
% hObject    handle to LoadImageButton (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('*.tif', 'Select a Query Image File');

if isequal(filename,0)
   disp('User selected Cancel')
else
   disp(['Input Image: ', fullfile(pathname, filename)])
    
    global QueryImage;
    QueryImage= imread(fullfile(pathname, filename));

    axes(handles.DisplayImage);
    
    imshow(QueryImage);
    
      global h;
    
    h = imrect(gca, [638 901 127 99]);  %--- (x,y) top corner and width/height
    setResizable(h,false);
    
    addNewPositionCallback(h,@(p) title(['Current ROI: ',mat2str(p,3)]));
    
end

return


% --- Executes on button press in SelectROIButton.
function SelectROIButton_Callback(hObject, eventdata, handles)
% hObject    handle to SelectROIButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global h;
    ROIposition=getPosition(h);
    ImROI=[round(ROIposition(1)) round(ROIposition(1))+ROIposition(3) round(ROIposition(2)) round(ROIposition(2))+ROIposition(4)];
    
    global QueryImage;
    global sQueryImage;
    sQueryImage=QueryImage(ImROI(3):ImROI(4),ImROI(1):ImROI(2));
    
    axes(handles.ShowSelectedArea);
    imshow(sQueryImage);

    
     set(handles.RecaptureResult,'String','NULL');
     set(handles.IdenResult,'String','NULL');  
     set(handles.DispConf,'String','NULL');
    
    set(handles.AnalyzeButton,'enable','on');
    axes(handles.ShowClassConfidence);
    cla;

return


% --- Executes on button press in AnalyzeButton.
function AnalyzeButton_Callback(hObject, eventdata, handles)
% hObject    handle to AnalyzeButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 global sQueryImage;
 global nDictionary;
 disp('Calculating...');
 
 
set(handles.AnalyzeButton,'enable','off');


 %-- Call a library "BlockClassification" in order to classify the block
 [ oClass MeanArr ConfHist vSError]= BlockClassification(sQueryImage,nDictionary);
 
 
  disp(['Classification Result: ', num2str(oClass)]);
  disp('Histogram of Confidence:');
  for i=1:8
   disp(['C',num2str(i),': ', num2str(ConfHist(i)),' %']);    
  end

  
 
  
 axes(handles.ShowClassConfidence);
 bar(1:8,ConfHist); 
 
 if (oClass) <4
        set(handles.RecaptureResult,'String','Single Capture');
    else
        set(handles.RecaptureResult,'String','Recapture');
 end
 
 MaxConf=max(ConfHist);   
 ConfStr=[num2str(MaxConf),'%'];
 set(handles.DispConf,'String',ConfStr);
 
  IdClass={ 'C1: Canon EOS400D';
          'C2: Canon XS200';
          'C3: Olympus EP2';
          'Recapture C1-C1  ';
          'Recapture C1-C2  ';
          'Recapture C1-C3  ';
          'Recapture C2-C1  ';
          'Recapture C3-C1  '};
      
    set(handles.IdenResult,'String',IdClass(oClass));  
      
  
return
