function curves = getcurves(fname, nvals)
%  This functions opens the CSV formated file created by the TI 370B curve
%  tracer designated by string in FNAME.  The input  variable NVALS is a
%  vector parameters applied to the third terminal of a 3 terminal device
%  for stepping out the family of curves as in a BJT (base currents) or
%  FET (gate-source voltages).  The fist element of NVALS should be the
%  lowest value used in the sequence of steps. If a 2 terminal device is used,
%  the NVALS variable should be omitted.
%
%        curves = getcurves(fname, nvals)
%
%  The output will be a cell array where each row represents corresponds to 
%  the NVAL value.  Column 1 is the x-axis vectors, Column 2 is the y-axis vectors,
%  and Column 3 is the NVALS values for each curve.  If NVALS was omitted,
%  then CURVES will only have 1 row and 2 columns (x-axis vector and y-axis vector).
%
%  This function needs the function PEAKFIND to run.
%
%  To convert these cell array values into a uniformly sample matrix array,
%  see help on the mfile INTERPCURVES.
%
%    Written by Kevin Donohue 5/2005  donohue@engr.uky.edu


%  Read in CSV file
m = csvread(fname);

% Compute gradient of x-axis to identify places where it does not change
%  must element places where sweep voltage was not changing
h = gradient(m(:,1));
%  Find non-zero gradient samples
kimp = find(abs(h) > eps);  %  All values just above 0.  
%  Trim the sample to eliminating places where sweep had stopped
trm = m(kimp,1:2);
%  Identify places where x-axis change directions from positive to negative
%  (forward sweep end points)
[tf, m1] = peakfind(trm(:,1), [1:length(trm(:,1))]);
%  (reverse sweep end points)
[tb, m1] = peakfind(-trm(:,1), [1:length(trm(:,1))]);

% Determine where the fist peak (fist turnaround) occured beyond the first point
[stp, pt] = min([tf(2), tb(2)]);  %  In the forward or reverse sweep direction
if pt == 1   %  If turnaround first happened in forward direction
    stv = tf(2:end-1);
    edv = tb(2:end-1);
else   %  %  If turnaround first happened in reverse direction
    stv = tb(2:end-1);
    edv = tf(2:end-1);
end

%  If step values are provided extract a curve associated with each
%  step value
if nargin == 2
    len = length(nvals);
else  %  Otherwise assume just one must be extracted
    len = 1;
end

%  Loop to exatract a single curve for each step
for k=1:len
    curves{k,1} = trm(stv(k):edv(k),1);
    curves{k,2} = trm(stv(k):edv(k),2); 
    %  If step values given create a 3rd column to store these values
    if nargin == 2
    curves{k,3} = nvals(k);
    end
end
