%measure 1 dB saturation power
clear all

%start and stop points:
% Pstart = -30;   %dBm
% Pstop = -28;     %dBm
% Pstep = 1;      %dB
% Pvec = Pstart:Pstep:Pstop;
% load('P_inputs');
% Pvec = [-20,-18,-16,-14,-12,-10,-8,-6,-4,-2,0];
%Pvec = [5,5,6,7,8,9,10,11,11.5,12,13,13.5,14,14.5,15,15.5,16,16.5,17];

%Vector of powers to measure at:
Pvec = [8,8,9,10,11,12,13,14,15,16,17,18,19,20,21,21.5,22,22.5,23,23.5,24,24.5];
pse = 2;        %number of seconds to wait in between changing attenuator power
compliance = 100e-3;     %in A

%Spectrum analyzer settings:
resBW = 1e6;                %#ok<NASGU>     (Hz) 
sweepcount = 3;             %number of sweeps
span = 50e6;                %Hz
freq = 3;                   %GHz

%GPIB addresses:
SpecAnGPIB = 21;
AttGPIB = 20;
meterGPIB = 30;

%initialize attenuator + set power to Pstart:
address2 = strcat('GPIB0::', num2str(AttGPIB), '::INSTR');
att = visa('ni', address2);
fopen(att)
fprintf(att, 'OUTP1:CHAN1:POW %d dBm', Pvec(1));
fprintf(att, 'OUTP1 ON')

%initialize source meter
address = strcat('GPIB0::', num2str(meterGPIB), '::INSTR');
source = visa('ni', address);
fopen(source)
fprintf(source, ':SENS:CURR:PROT %e', compliance);
fprintf(source, ':READ?')
current_holder = str2num(fscanf(source));
current = current_holder(2);


    for j = 1:length(Pvec)
        fprintf(att, 'OUTP1:CHAN1:POW %d dBm', Pvec(j));
        pause(pse);
        fprintf(source, ':READ?')
        current_holder = str2num(fscanf(source));
        Itot(j) = current_holder(2);
        Pwr(j) = sensitiveReadSpectrum(SpecAnGPIB, freq, span, resBW, sweepcount);
        semilogx(-1*Itot(1:j), Pwr(1:j), 'x-');
    end
fprintf(att, 'OUTP1:CHAN1:POW 0 dBm');
fclose(att);
fclose(source);
clear att
clear source

uisave();