function [ok] = tempCtl(tempMatrix)
% [ok] = tempCtl(tempMatrix)
%
%Starts the heater loop for the superconductivity experiment.
%
%Input: setMatrix:  A three-column matrix.  The first column is target
%temperatures, the second is the ramp rate when approaching that target.
%The final column indicates how many seconds to wait after reaching each
%target setpoint.
%
%IMPORTANT: In order to collect data while the temperature is ramping, 
%this program is designed so the last command leaves the Lakeshore
%controller running toward a target temperature.  This is so this program
%may be exited, returning the user to the command prompt, and the data
%collection can be started while the controller is ramping.  In other
%words, the last column of the last row can be anything.  This program will
%then leave the controller at the new setpoint.
%
%If the program exits with errors, call delete(instrfind) at the command
%prompt to reset the hardware connections.
%
%David Tam, Columbia University Dept. of Physics, May 2010
%tam@phys.columbia.edu

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

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

%check matrix
if size(tempMatrix,2)~=3
    disp('Incorrect matrix form.  Type "help tempCtl".')
    return
end

%set heater range
fprintf(lakeshore,'*RST')
fprintf(lakeshore,'RANGE 1,1\n')



%perform each controlled step
for step=1:size(tempMatrix,1)
    
    controlVec = tempMatrix(step,:);
    
    %set ramp rate
    fprintf(lakeshore,'RAMP 1,1,%s\n',num2str(controlVec(2)))
    
    %set target
    fprintf(lakeshore,'SETP 1,%s\n',num2str(controlVec(1)))
    
    if step==size(tempMatrix,1)
        break
    end
    
    fprintf(lakeshore,'KRDG?');
    newTemp = fscanf(lakeshore,'%f');
    tempSign = sign(newTemp-controlVec(1));
    
    newTempSign=tempSign;
    while isequal(newTempSign,tempSign)

        fprintf(lakeshore,'KRDG?');
        newTemp = fscanf(lakeshore,'%f');
        
        pause(1)
        
        newTempSign = sign(newTemp-controlVec(1));
    end
    
    pause(controlVec(3))
    
end

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

disp('The program was successfully closed.')

end