%This function reads the spectrum about a center frequency and returns
% two column vectors with the frequencies and trace data
% Inputs:
%   Addr: GPIB address of the device (integer 0 to 26)
%   CFreq: Center frequency (in GHz)
%   span: span (in Hz)
% Outputs:
%   freq: 1x401 (usually) vector with x-axis values for frequency (Hz)
%   trace: 1x401 (usually) trace data (dBm)
% Equipment it works on:
%   Rohde&Schwarz FSU50

function [peak] = sensitiveReadSpectrum(Addr, CFreq, span, resBW, sweepcount)

%create VISA object (within Matlab operating environment)
%and open it (connect to actual instrument)
address = strcat('GPIB0::', num2str(Addr), '::INSTR');
%SpecAnalyzer = visa('ni', address);
SpecAnalyzer=gpib('ni', 0, Addr);
fopen(SpecAnalyzer);
SpecAnalyzer.timeout = 100;

%set data format to 32-bit floating point number
fprintf(SpecAnalyzer, 'FORM REAL, 32');

%set center frequency
fprintf(SpecAnalyzer, 'FREQ:CENTER %.9f GHz;*WAI', CFreq)

%set frequency span
fprintf(SpecAnalyzer, 'FREQ:SPAN %f Hz;*WAI', span)

%set resolution bandwidth
fprintf(SpecAnalyzer, 'BAND %f Hz;*WAI', resBW)

%set reference level to 0 dBm
fprintf(SpecAnalyzer, 'DISP:WIND:TRAC:Y:RLEV 20 dBm');
%turn preamp on
%fprintf(SpecAnalyzer, 'INP:GAIN:STAT ON');

%clear data & reset reference level
% fprintf(SpecAnalyzer, 'SWEEP:COUNT 2; *WAI');
% fprintf(SpecAnalyzer, 'DISP:WIND:TRAC1:MODE AVER;*WAI');
% fprintf(SpecAnalyzer, 'INIT:CONT OFF');
% fprintf(SpecAnalyzer, 'ABOR;INIT:IMM;*WAI');
% 
% %move marker to peak
fprintf(SpecAnalyzer, 'CALC:MARKER ON;MARKER:MAX;*WAI');
% %move reference level to marker level+20 dBm
% fprintf(SpecAnalyzer, 'CALC:MARK:MAX;Y?;*WAI')
% peak = str2num(fscanf(SpecAnalyzer));
% fprintf(SpecAnalyzer, 'DISP:WIND:TRAC:Y:RLEV %d dBm', peak+20);

%set sweep count high again, start sweep
fprintf(SpecAnalyzer, 'SWEEP:COUNT %d; *WAI', sweepcount);
fprintf(SpecAnalyzer, 'INIT; *WAI');

%move marker to peak (again) and get peak value
fprintf(SpecAnalyzer, 'CALC:MARK:MAX;Y?;*WAI')
peak = str2num(fscanf(SpecAnalyzer));

%close connection to instrument
fclose(SpecAnalyzer);