%Minh Tran
%09-29-2014
%Program to get RIN noise with frequency sweeps on HP 700001A SYSTEM with 70004A DISPLAY
clear all;clc;close all;
instrreset;
ESA = gpib('NI', 0, 18);
ESA.Timeout=1000;
ESA.InputBufferSize=200000;
ESA.OutputBufferSize=20000;
%CENTERFREQ = 500E6; %Hz
%SPAN = 500E6; %Hz
%RESOLUTION = 1E6; %Hz
fopen(ESA)
%fprintf(ESA,'CF 9GHZ'); %Set center frequency
%fprintf(ESA,'SP 18GHZ'); %Set span
%fprintf(ESA,'RB 300KHZ'); %Set rbw
%fprintf(ESA,'RL -20DBM'); %ref level setting

POWER = str2num(query(ESA,'OPTPWR?'))%dBm %Read the optical Average Power received by the analyzer
ATTENUATOR = str2num(query(ESA,'AT?'))%(dBm) %Read the attenuation
SPAN=str2num(query(ESA,'SP?')) % Read frequency span
RBW=str2num(query(ESA,'RB?')) % Read resolution bandwidth
REF=str2num(query(ESA,'RL?')) % Read reference level
CFREQ=str2num(query(ESA,'CF?')) %Read center fruequency
%Read the received power
POW=str2num(query(ESA,'TRA?'));

% Start sweeping the marker. Each time read the RIN laser, RIN system,thermal noise and shot noise. After finishing, move the marker to the next point

i =1;
while i <4
    str1=sprintf('MKP %d',i*4); %Choose the marker position
    fprintf(ESA,str1);
    FREQ(i,1)=str2num(query(ESA,'MKF?')); % Read the frequency at the marker
    noise(i,:)=str2num(query(ESA,'RIN?')); % Read RIN laser, RIN system,thermal noise and shot noise respectively 
    i=i+1;
end

%Close the communication with the equipments
fclose(ESA);
delete(ESA);
clear ESA;

%Data process

RINLASER = noise(:,1);
RINSYS = noise (:,2);
THERMALNOISE = noise(:,3);
SHOTNOISE = noise(:,4);

%Plotting commands
figure(1);
hold on;
plot(FREQ,RINLASER,'b.-');
plot(FREQ,RINSYS,'o-');
plot(FREQ,THERMALNOISE,'square-');
plot(FREQ,SHOTNOISE,'diamond-');
grid on
xlabel('Frequency (Hz)')
ylabel('Amplitude (dB/Hz)')

filename = input('Save file name: ','s');
if ~isempty(filename)

%Output data file handling
H1 = gcf;
        saveas(H1, [filename '_' datestr(now,30) '.png']); 
        saveas(H1, [filename '_' datestr(now,30) '.fig']); 
        dlmwrite([filename '_' datestr(now,30) '.txt'],[FREQ;RINLASER;RINSYS;THERMALNOISE;SHOTNOISE]','delimiter','\t','precision','%18.20f');
        save(filename);
end;