%{ 
%%%%%%%%%%%%%  GPIB code for APEX High Res OSA %%%%%%%%
Daryl Spencer
Grab current trace in dBm x nm units
This machine will GPIB freeze! Be careful to read all data off! 
Run a write command before a query command!
%}
clear all; close all;instrreset;
filename = 'MLL_passive_700mASOA_1p8Vmod_GO1';
sweepnum=1; %Set trace number to save: 1=A ; 2=B ; etc.
obj=gpib('ni',0,8);
set(obj,'EOSMode','write');
obj.InputBufferSize=50000000; %Increase cache to receive data sets
obj.Timeout=8; %8 second timeout

% % % Grab current data and save; user should set to dBm and nm axes
fopen(obj);
% name=query(obj,'*IDN?')
% fprintf(obj,'*CLC');
d=query(obj,sprintf('SPDATAD%d', sweepnum));pause(3); % grab Y data in log scale
w=query(obj,sprintf('SPDATAWL%d',sweepnum));pause(3); %grab X data in wavelength(nm)
fprintf(obj, '*CLC'); %Clear strange binary blocks that come up after wavelength data
fclose(obj);
% Plot,check # Datapoints, and save .png and data
data=str2num(d);y=data(2)
wav=str2num(w);x=wav(2)
H1=figure; plot(wav(2:end),data(2:end),'.-');
title('Current Dataset'); xlabel('Wavelength (nm)');ylabel('Optical Power (dBm)');
fprintf('# Datapoints = %d = %d\nSpacing = %fpm\n',wav(1),data(1),1e-3*(wav(3)-wav(2)))
        x = input('Save fitted image?  (Y/N) \n', 's');
        if strcmpi(x,'Y')
        saveas(H1, [filename datestr(now,30) '.png'],'png'); 
        saveas(H1, [filename datestr(now,30) '.fig'],'fig'); 
        A=[wav', data'];
        save ([filename datestr(now,30) '.txt'], 'A', '-ASCII');
        fprintf(1,'File saved as %s .png\n', filename)
        end