clear all
close all
instrreset

disp('lol')

filename=input('Filename>>','s');

filenames=dir([filename '*']);
ok_write=isempty(filenames)
while ok_write==0
    ok_write=input('File already exists. 1 to overwrite>>');
end

colors=['bgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmyk'];

lstart = 1525; %nm
lstop = 1625;   %nm
amp = -15;      %dBm - ref level
RBW =.05;         %nm = res bandwidth
sensitivity='NORMAL'; %MID, HIGH1, HIGH2, HIGH3, NORMAL
idle_sensitivity='NORMAL';
connector='ANGL'; %NORM or ANGL
speed='2x'; %1x for lasers, 2x for SLI

%% OSA GPIB init
OSAGPIB = 1; %23
Points=10000; %Recommend at least 2*(lstop-lstart)/RBW. Won't go above 10000.
hold_time=60;
%initialize source meter
address = strcat('GPIB0::', num2str(OSAGPIB), '::INSTR');
%OSA = visa('ni', address);
OSA=gpib('ni', 0, OSAGPIB);
OSA.InputBufferSize=300000; %10 characters are required for each trace data point
OSA.Timeout=10;
fopen(OSA)

%% Configure OSA
fprintf(OSA, '*RST')
fprintf(OSA, ':INIT:CONT OFF') %Disable continuous sweep
fprintf(OSA, ':SENS:WAV:STAR %dnm', lstart);
fprintf(OSA, ':SENS:WAV:STOP %dnm', lstop);
fprintf(OSA, [':SENS:SWE:POIN auto']); %num2str(Points)]);
fprintf(OSA, ':SENS:BWID:RES %.2fnm', RBW);
fprintf(OSA, [':SENS:SENS ' sensitivity]);
fprintf(OSA, [':SENS:SETT:FCON ' connector]);
fprintf(OSA, [':SENS:SWE:SPE' speed ]);

%% Collect data
fprintf(OSA, ':init:smode 1'); %Set to single sweep
fprintf(OSA, ':init:imm;');
fprintf(OSA,':TRAC:DATA: Y? TRA;');
power=str2num(fscanf(OSA));
fprintf(OSA,':TRAC:DATA: X? TRA;');
wavelength=str2num(fscanf(OSA));

plot(wavelength*1e9,power)

%% De-initialize

fprintf(OSA, [':SENS:SENS ' idle_sensitivity]);
instrreset