close all
clear all

%%%% Trigger rates and their relations ##################
base_machine_freq = 928471.429;
subharmonics = [1  2 4 5 7 8 10 13 14 16 20 25 26 28 35 40 50 52 56 65 70 80 91 100 104 112 125 130 140 175 182 200 208 250 260 280 325 350 364 400 455 500 520 560 625 650 700 728 875 910 1000 1040 1250 1300 1400 1456 1625 1750 1820 2000 2275 2500 2600 2800 3250 3500 3640 4375 4550 5000 5200 6500 7000 7280 8125 8750 9100 10000 11375 13000 14000 16250 17500 18200 22750 26000 32500 35000 36400 45500 56875 65000 70000 91000 113750.00 130000.00 182000.00 227500.00 455000.00 910000.00];
machine_frequencies = base_machine_freq./subharmonics;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Detector register settings %%%%%%%%%%%%%%%%%%%%%%%%
ACQ_delay = (12+1)*1e-6;
ACQ_width = 24e-6;
SRO_delay = 1e-6;
Serdes_clock = 260; %MHz
margin = 3e-6; 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Calculate the maximum runtrigger frequency you can have %%%%%%%
if Serdes_clock == 320
    readout_time = 146e-6;
elseif Serdes_clock == 310
    readout_time = 150.71e-6;
elseif Serdes_clock == 300
    readout_time = 155.73e-6;
elseif Serdes_clock == 260
    readout_time = 179.69e-6;
end
Total_readout_time = ACQ_delay+ACQ_width+SRO_delay+readout_time+margin;
disp(['The full read cycle takes: ', num2str(Total_readout_time/1e-6), ' us.'])
Maximum_frequency_detector = 1/Total_readout_time;
disp(['Maximum frequency (Trigger rate) the ePixHR can run with these settings: ', num2str(Maximum_frequency_detector), 'Hz.'])

%%%%%%%%%% check for  specific run trigger rate: %%%%%%%%%%%%%%%%%
Run_trigger = machine_frequencies(32); % 4642.4 Hz
%Run_trigger = machine_frequencies(31) % 5101.5 Hz
%Run_trigger = machine_frequencies(30) % 5305.6 Hz
if Run_trigger > Maximum_frequency_detector
    disp('The detector can NOT run at this trigger rate using these settings!')
end
if Run_trigger < Maximum_frequency_detector
    disp('The detector can run at this trigger rate using these settings.')
end


Fit = machine_frequencies./Run_trigger;
x=1;
for i=1:1:100
    if rem(Run_trigger, machine_frequencies(1,i)) == 0
        allowed_frequencies(1,x)= machine_frequencies(1,i);
        x=x+1;
    end
end

disp(['Allowed ACQ_triggers when Run trigger is ', num2str(Run_trigger), ': '])   
num2str(allowed_frequencies)

%%%%%%%%% Produce file over a number of frequencies %%%%%%%%%%%%%%%%%
y=1;
for j=1:1:100
    Run_trigger = machine_frequencies(j);
    allowed_array(1,y) = Run_trigger;
    x=2;
    for i=1:1:100
        if rem(Run_trigger, machine_frequencies(1,i)) == 0
            allowed_array(x,y)= machine_frequencies(1,i);
            x=x+1;
        end
    end
    y=y+1;
end