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

% Last Modified by GUIDE v2.5 23-May-2018 14:31:29

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

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

% Update handles structure
guidata(hObject, handles);

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



% Figure adjustments
screensize = get( groot, 'Screensize' ); % getting screen size
set(handles.figure1,'Name','Continuous Counting Altera','numbertitle','off','Position',screensize,'color',[0.7 0.7 0.7]);
pause(1);
% setting initial time interval
set(handles.time_edit8,'Value', 1);
set(handles.time_edit8,'string',num2str(get(handles.time_edit8,'Value')));
set(handles.time_edit8,'Fontsize',16,'FontName','Times New Roman')
% 
% axes('position',[left bottom width height])
% Set the axes settings
% Axes 1
% set(get(handles.axes1,'title'),'background','y')
handles.axes1.XLim = [0 inf];
handles.axes1.YLim = [0 inf];
grid(handles.axes1,'on');
hold(handles.axes1,'on');
% Axes 2
handles.axes2.XLim = [0 inf];
handles.axes2.YLim = [0 inf];
grid(handles.axes2,'on');
hold(handles.axes2,'on');
% Axes 3
handles.axes3.XLim = [0 inf];
handles.axes3.YLim = [0 inf];
grid(handles.axes3,'on');
hold(handles.axes3,'on');

% Credit Behzad Khajavi
axcredit=axes('position',[0.87 0.0 0.1 0.05],'visible','off');
axcredit.Title.Visible = 'on';
set(get(gca,'title'),'color','w','background','b')% figure header text:white, background:blue
descr2 = 'by: Behzad Khajavi';
title(axcredit,descr2,'FontWeight','bold','FontSize',10,'FontName','TimesNew Roman')

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

% --- Outputs from this function are returned to the command line.
function varargout = ContinuousCounting_Altera_OutputFcn(~, ~, 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 Clearplotbutton.
function Clearplotbutton_Callback(~, ~, handles)
% hObject    handle to Clearplotbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% clearing axes (don't want to see the preious data points)
% Clear Axes 1
axes(handles.axes1)
cla reset % Do a complete and total reset of the axes.
grid(handles.axes1,'on');
hold(handles.axes1,'on');
handles.axes1.XLim = [0 inf];
handles.axes1.YLim = [0 inf];
% Clear Axes 2
axes(handles.axes2)
cla reset % Do a complete and total reset of the axes.
grid(handles.axes2,'on');
hold(handles.axes2,'on');
handles.axes2.XLim = [0 inf];
handles.axes2.YLim = [0 inf];
% Clear Axes 3
axes(handles.axes3)
cla reset % Do a complete and total reset of the axes.
set(handles.accidentalsedit6,'String','')
grid(handles.axes3,'on');
hold(handles.axes3,'on');
handles.axes3.XLim = [0 inf];
handles.axes3.YLim = [0 inf];
%%%

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

clc;
% Setting the initial states of the buttons; Run, Stop, and Pause
set(handles.Run,'String','Running','Foregroundcolor',[0 0.5 0],'FontWeight','Bold','FontName','Times New Roman')
set(handles.Stop_pushbutton3,'String','Stop','Foregroundcolor','r','FontWeight','Bold','FontName','Times New Roman')
set(handles.Pause_pushbutton4,'String','Pause','Foregroundcolor',[0.5 0.5 0.5],'FontWeight','Bold','FontName','Times New Roman')
% Clear Axes 1
axes(handles.axes1)
cla reset % Do a complete and total reset of the axes.
grid(handles.axes1,'on');
hold(handles.axes1,'on');
handles.axes1.XLim = [0 inf];
handles.axes1.YLim = [0 inf];
% Clear Axes 2
axes(handles.axes2)
cla reset % Do a complete and total reset of the axes.
grid(handles.axes2,'on');
hold(handles.axes2,'on');
handles.axes2.XLim = [0 inf];
handles.axes2.YLim = [0 inf];
% Clear Axes 3
axes(handles.axes3)
cla reset % Do a complete and total reset of the axes.
grid(handles.axes3,'on');
hold(handles.axes3,'on');
handles.axes3.XLim = [0 inf];
handles.axes3.YLim = [0 inf];
%%%
set(handles.accidentalsedit6,'String','')
% Parameters
timeinterval = str2double(get(handles.time_edit8,'String')); % time interval for each measurement in seconds
% timeinterval = 1; % time interval for each measurement in seconds
% myData = zeros(timeinterval*512,1);
% deltat=40e-9; % pulse width to calculate accidental coincidences
% myDatadimension=41*(timeinterval*10)+40; % timeinterval*10=timeinterval in seconds 
% cleandatadimension=41*(timeinterval*10);
% myData=zeros(myDatadimension,1);
count=0; time=0;
comportnum=get(handles.comport,'String');
s = serial(comportnum,'BaudRate',19200,'DataBits',8,'StopBits',1,'Parity','none');
% disp(strcat('before the loop ->',num2str(get(handles.Run,'Value'))))
fopen(s);  % open the serial port before the inner loop begins.

%****************************************************************************
%% Programming the Coincidence Detector Board


%% Loop
% Defining global variables for the Stop and Pause buttons
global stopbuttonvalue
stopbuttonvalue = 0;
global pausebuttonvalue
pausebuttonvalue = 0;
while stopbuttonvalue == 0
% while get(hObject,'Value')
    count=count+1;
    myDatadimension=41*(timeinterval*10)+40; % timeinterval*10=timeinterval in seconds 
    cleandatadimension=41*(timeinterval*10);
    myData=zeros(myDatadimension,1);
%   Serial data acquisition 
    for i=1:timeinterval
         myData1 = fread(s,512,'uint8'); % reading # of bytes
         myData(1,(i-1)*512+1:i*512) = myData1';
    end 
    % finding terminationbyte if the 41th element of myData is not 255
    tbi=0;
    if myData(1,41)~=255
        for i=1:40
           if myData(1,i)==255
               terminationbyteindex=i;
           end
        end 
        tbi=terminationbyteindex;
    end 
    cleandata=myData(1,tbi+1:tbi+cleandatadimension);
    numofcounts=zeros(1,8);
    CD=cleandata; % just to use a shorthand notation CD
    kmax=timeinterval*10; % loop repetation number for each counter
    L=0;
    for i=1:8
        j=0;
        for k=1:kmax   
            numofcounts(1,i)=numofcounts(1,i)+CD(1,1+j+L)+2^7*CD(1,2+j+L)+2^14*CD(1,3+j+L)+2^21*CD(1,4+j+L)+2^28*CD(1,5+j+L);     
            j=j+41; % the corresponding figure after a tenth of a second
        end
        L=L+5; % next counter partition starts at the next 5th byte
    end 
    numofcountsA = numofcounts(1,1);
    numofcountsB = numofcounts(1,2);
    numofcountsAB = numofcounts(1,5);
    
     %% Calculating and then Showing Accidentals
    deltat=str2double(get(handles.Deltatedit7,'String'));
    acc=numofcountsA*numofcountsB*deltat*0.000000001;
    pause(0.01);
   strcat('Pausebuttonvalue in Pause push button->',num2str(pausebuttonvalue));
    if mod(pausebuttonvalue,2) == 0
%% plotting the data points on different subplots
    time = time + timeinterval; % x-axis (time) in seconds
    % plotting A
    axes(handles.axes1);
    plot(time,numofcountsA,'. b','MarkerSize',20);
    descriptionA = num2str(numofcountsA);
    title(descriptionA,'FontWeight','bold','FontSize',40,'FontName','Times New Roman')
    set(get(gca,'title'),'background','y')
    xlabel({'time (Sec)','',''},'FontWeight','bold','FontSize',14,'FontName','Times New Roman');
    ylabel('Singles A','FontWeight','bold','FontSize',25,'FontName','Times New Roman');
    %%%%%%%%%%%%%%%%%%%%%%
    % plotting B
    axes(handles.axes2);
    plot(time,numofcountsB,'. b','MarkerSize',20);
    descriptionB = num2str(numofcountsB);
    title(descriptionB,'FontWeight','bold','FontSize',40,'FontName','Times New Roman')
    set(get(gca,'title'),'background','y')
    xlabel({'time (Sec)','',''},'FontWeight','bold','FontSize',14,'FontName','Times New Roman');
    ylabel('Singles B','FontWeight','bold','FontSize',25,'FontName','Times New Roman');
    %%%%%%%%%%%%%%%%%%%%%%
    % plotting AB    
    axes(handles.axes3);
    plot(time,numofcountsAB,'. b','MarkerSize',20);
    descriptionAB = num2str(numofcountsAB);
    title(descriptionAB,'FontWeight','bold','FontSize',40,'FontName','Times New Roman')
    set(get(gca,'title'),'background','y')
    set(handles.accidentalsedit6,'String',num2str(acc))%displays accidentals (here to be simultaneously shown)
    drawnow
    xlabel({'time (Sec)','',''},'FontWeight','bold','FontSize',14,'FontName','Times New Roman');
    ylabel('Coinc. AB','FontWeight','bold','FontSize',25,'FontName','Times New Roman');
    
    end
    %%%%
end
% assignin('base','time1',time)
% time=get(time1,'Value');
fclose(s);  % close the serial port after the inner loop ends.
clear s;
% disp(strcat('after the loop ->',num2str(get(handles.Run,'Value'))))
% set(handles.Run,'String','RUN','Foregroundcolor',[0 0.5 0],'FontWeight','Bold','FontName','Times New Roman')

function comport_Callback(~, eventdata, handles)
% hObject    handle to comport (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 comport as text
%        str2double(get(hObject,'String')) returns contents of comport as a double


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


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




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


% --- Executes during object creation, after setting all properties.
function time_edit8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to time_edit8 (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 on button press in Stop_pushbutton3.
function Stop_pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to Stop_pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% global
global stopbuttonvalue 
stopbuttonvalue = 1;
disp(strcat('stopbuttonvalue in stop push button->',num2str(stopbuttonvalue)))
set(handles.Stop_pushbutton3,'String','Stopped','Foregroundcolor','r','FontWeight','Bold','FontName','Times New Roman')
set(handles.Run,'String','Run','Foregroundcolor',[0 0.5 0],'FontWeight','Bold','FontName','Times New Roman')
disp('Stopped')
guidata(hObject,handles);


% --- Executes on button press in Pause_pushbutton4.
function Pause_pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to Pause_pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global pausebuttonvalue
pausebuttonvalue = pausebuttonvalue + 1;
guidata(hObject, handles);
disp(strcat('Pausebuttonvalue in Pause push button->',num2str(pausebuttonvalue)))
% pause(0.01)
if mod(pausebuttonvalue,2)==1
set(handles.Pause_pushbutton4,'String','Paused','Foregroundcolor','r','FontWeight','Bold','FontName','Times New Roman')
disp('Paused')
else
    set(handles.Pause_pushbutton4,'String','Pause','Foregroundcolor',[0.5 0.5 0.5],'FontWeight','Bold','FontName','Times New Roman')
    disp('Un-paused')
end
