% GPIB to R&S FSU ESA| Grab current data set
clear all;close all; instrreset;
cd('C:\Daryl_Main\Research\Prog, Instr,Parts,Trainings\ESA R&S FSU');
screen='A'; % A or B screen (A is default)
filename='FreqDiv4_E8257D_5Vreg_20G_n10dBm_10Hz-100MHz_PM';
if strcmpi(screen,'A')
    scr=1;
elseif strcmpi(screen,'B')
    scr=2;
else
    error('Enter screen A or B!');end
esa=gpib('ni',0,29);
esa.InputBufferSize=1000000;
fopen(esa);
% fprintf(esa,'*RST');
% fprintf(esa, 'INP:GAIN:STAT ON');       %Turn on Preamp
fprintf(esa, 'SYSTem:DISPlay:UPDate  0'); %Keep screen off during testing
% fprintf(esa, 'INIT:CONT OFF;*WAI');


    Fc=str2num(query(esa, sprintf('SENS%d:FREQ:CENT?',scr)));
    pts=str2num(query(esa, sprintf('SENS%d:SWE:POIN?',scr)));
    fstart=str2num(query(esa, sprintf('SENS%d:FREQ:STAR?',scr)));
    fstop=str2num(query(esa, sprintf('SENS%d:FREQ:STOP?',scr)));
    freq = linspace(fstart, fstop, pts);
    fprintf(esa,'UNIT:POW DBM');
    fprintf(esa,'FORM ASCII');
    pow=query(esa,sprintf('TRACE%d? TRACE1',scr));
    d=sscanf(pow,'%f,')';
%     save([filename datestr(now,30)],'freq','d');
    % fprintf(esa,'SENS:SWE:POIN 30001');     %Set sweep points: max: 30001, ~300kB files
    fclose(esa);
    H1=figure;
    plot(freq-mean(freq),d,'.-');title(sprintf('Current Dataset\nCenter:%9.9fGHz',mean(freq)*1e-9));
    xlabel('RF Frequency (Hz)');
    ylabel('RF Power (dBm)');axis tight;
   %%
   save([filename '_' datestr(now,30) '.txt'],'freq','d', '-ASCII','-double');
    saveas(H1, [filename '_' datestr(now,30) '.png']); 
    saveas(H1, [filename '_' datestr(now,30) '.fig']); 
    