function  dataOut = diode_gpib_meas(modeFlag, iterMax, fName, varargin)
%Automates the data collecting and recording process for diode
%measurements.
%
%
%INPUTS:
%
%modeFlag                   Integer
%                           1 for 'alone' mode
%                           2 for 'follow' mode
%
%iterMax                    Integer
%                           In 'alone' mode, iterMax = number of data points
%                           to take
%                           In 'follow' mode, iterMax = temperature
%                           measurement cutoff for either thermometer
%
%fName                      String
%                           Name of output file (Not full path)               
%
%OPTIONAL INPUTS:
%
%initCurrent                Integer
%                           Initial current (A)?
%                           Default = 0
%
%measDelay                  Integer
%                           Matlab time delay between measurements
%                           (seconds)
%                           Default = 0.1
%
%dvmRange                   Integer
%                           DVM Range?
%                           Default = 10
%
%maxComp                    Integer
%                           Max out Compliance
%                           Default = 105
%
%OUTPUTS:
%
%dataOut                    N x 4 Matrix (N is number of data points)
%                           Column 1: Current (A)
%                           Column 2: Applied Voltage (V)
%                           Column 3: Temperature 1 (K)
%                           Column 4: Temperature 2 (K)
%                           
%Sky Cheung

%Input Checking
if modeFlag ~= 1 && modeFlag ~= 2
    error('modeFlag must be 1 or 2.'); 
end
if iterMax <= 0
    error('iterMax must be positive.');
end
%Sanity Check for 'follow' mode temperature cutoff
if modeFlag == 2 && itermax >= roomT
    error('Cutoff temperature is above room temperature.');
end
%Declare Optional Inputs
initCurrent = 0;
measDelay = 0.1;
dvmRange = 10;
maxComp = 105;
%Switch to apply optional inputs (if necessary)
switch (nargin - 3)
    case 0
        disp('No Optional Inputs Entered.');
    case 1
        initCurrent = varargin{1};
    case 2
        initCurrent = varargin{1};
        measDelay = varargin{2};
    case 3
        initCurrent = varargin{1};
        measDelay = varargin{2};
        dvmRange = varargin{3};
    case 4
        initCurrent = varargin{1};
        measDelay = varargin{2};
        dvmRange = varargin{3};
        maxComp = varargin{4};
    otherwise
        error('Too many optional inputs.');
end  %End of switch


%Hard Coded Output File Path (save is at the end)
fileDirectory = 'C:\Documents and Settings\Student\My Documents\repar\'; 
fullPathTxt = [fileDirectory, fName, '.txt'];
fullPathMat = [fileDirectory, fName, '.mat'];

%Activating Pause
pause on
hold on

%Close figures and windows
close all

%Configuration reset
delete(instrfind);



%*************************************************************************
%Create and open instrument objects, and echo their names
lakeshore = visa('ni','gpib0::12::INSTR');
fopen(lakeshore);
fprintf(lakeshore,'*IDN?');
lakeshoreName = fscanf(lakeshore);

keithley1 = visa('ni','gpib0::13::INSTR');
keithley2 = visa('ni','gpib0::14::INSTR');
fopen(keithley1);
fprintf(keithley1,'*IDN?');
keithley1Name = fscanf(keithley1);
fopen(keithley2);
fprintf(keithley2,'*IDN?');
keithley2Name = fscanf(keithley2);

disp('Successfully connected to:');
disp(lakeshoreName(1:end-2)); %eliminates trailing whitespace
disp(keithley1Name(1:end-2));  
disp(keithley2Name(1:end-2));
disp(' ');

%*****************************************************************************
%Initialize the 6220&2182
fprintf(keithley1,'*RST');
fprintf(keithley1,'SOUR:CURR:COMP %e', maxComp);
fprintf(keithley1,'SOUR:CURR:RANG:AUTO ON');
fprintf(keithley2,'*RST');	
fprintf(keithley2,'*CLS');

fprintf(keithley2,'SAMP:COUN 1');
fprintf(keithley2,'READ?');
testVolts=fscanf(keithley2,'%e');
disp(['testVolts = ', num2str(testVolts)]);

%*******************************************************************************	
%Strike key to begin measurement	
disp('Strike any key...');
pause

fprintf(keithley1,'OUTP ON');
%Set the current and turn on the 6220
fprintf(keithley1,'SOUR:CURR %e',initCurrent);

%Switch for 2 modes
switch modeFlag
    case 1 %Alone Mode
        %Preallocate data storage
        dataOut = zeros(iterMax,4);
        
        %For loop to take data
        for i = 1:iterMax
            %Temperature from Thermometer 1
            fprintf(lakeshore,'KRDG?a');
            newT1 = fscanf(lakeshore,'%f');
            %Temperature from Thermometer 2
            fprintf(lakeshore,'KRDG?b');
            newT2 = fscanf(lakeshore,'%f');
            %Measure Applied Voltage
            fprintf(keithley2,'READ?');
            newV = fscanf(keithley2,'%e');
            %Average Temperature
            newT = newT1 + newT2;
            
            disp(['Temperature 1: ', num2str(newT1)]);
            disp(['Temperature 2: ', num2str(newT2)]);
            disp(['Temperature Avg: ', num2str(newT)]);
            disp(['Measured Volts: ',num2str(newV)]);
            disp(['Current: ', num2str(initCurrent)]);
            
            %Real-time update of plot (V vs T)
            plot(newT, newV,'*');
            
            %Writing data to output
            dataOut(i,:) = [initCurrent, newV, newT1, newT2];
            
            %Optional Delay between measurements
            pause(measDelay);
            
        end  %End of for loop
        
    case 2 %Follow Mode
        %Initial temperature readings
        %Temperature from Thermometer 1
        fprintf(lakeshore,'KRDG?a');
        newT1 = fscanf(lakeshore,'%f');
        %Temperature from Thermometer 2
        fprintf(lakeshore,'KRDG?b');
        newT2 = fscanf(lakeshore,'%f');
        %Average Temperature
        newT = newT1 + newT2;
        
        disp(['Temperature 1: ', newT1]);
        disp(['Temperature 2: ', newT2]);
        disp(['Temperature Avg; ', newT]);
        
        %Data Counter
        dataCount = 1;
        %Preallocate storage (start with 500)
        dataOut = zeros(500,4);
        
        %While loop for follow mode (initial temperature discarded)
        while newT <= iterMax
            
            %Temperature from Thermometer 1
            fprintf(lakeshore,'KRDG?a');
            newT1 = fscanf(lakeshore,'%f');
            %Temperature from Thermometer 2
            fprintf(lakeshore,'KRDG?b');
            newT2 = fscanf(lakeshore,'%f');
            %Measure Applied Voltage
            fprintf(keithley2,'READ?');
            newV = fscanf(keithley2,'%e');
            %Average Temperature
            newT = newT1 + newT2;
            
            disp(['Temperature 1: ', num2str(newT1)]);
            disp(['Temperature 2: ', num2str(newT2)]);
            disp(['Temperature Avg: ', num2str(newT)]);
            disp(['Measured Volts: ',num2str(newV)]);
            disp(['Current: ', num2str(initCurrent)]);
            
            %Real-time update of plot (V vs T)
            plot(newT, newV,'*');
            
            %Writing data to output
            dataOut(dataCount,:) = [initCurrent, newV, newT1, newT2];
            
            %Optional Delay between measurements
            pause(measDelay);
            
            %If statement to append to dataTemp if necessary
            if mod(dataCount,500) == 0
                %Add 500 more rows
                dataOut = [dataTemp, zeros(500,4)];
            end  %End of if statement
            
        end %End of while loop
        
        %Data collection phase is complete
        %Removing blank rows from dataOut
        dataOut = dataOut( any(dataOut,2), :);
        
end  %End of switch Statement

%Closing streams
fprintf(keithley1,'OUTP OFF');
fprintf(keithley1,'SOUR:CLE');

%Regenerating average from data for plot
TAvg = 0.5 * ( dataOut(:,3) + dataOut(:,4) );
%Completing Plot
plot( TAvg, dataOut(:,2), 'd','Color','r');

%Writing output text file
disp('Writing output file.');
dlmwrite (fullPathTxt, dataOut, '-append','delimiter','\t',...
    'precision',10,'newline','pc');
disp('Output file saved.');

%Saving data in .mat file
save(fullPathMat, 'dataOut');

%close instrument objects and delete them
fclose(lakeshore);
fclose(keithley1);
fclose(keithley2);
delete(instrfind);


%End timer
tEnd = toc(tStart);
disp(['diode_gpib_meas.m took ', num2str(tEnd), ' seconds.']);
end
     