function phidgetInit()
%PHIDGETINIT Initialize the Phidget
%   phidgetInit() loads the loadphidget21 library, creates a global
%   handle to the Phidget, and attempts to connect to an attached Phidget.
%
%   If a connection to an attached Phidget is successful then a global
%   variable PHIDGET is created that is a handle to the attached Phidget.

global PHIDGET;

loadphidget21;

% is there alread a connected Phidget?
if ~isempty(PHIDGET)
    if ~isNull(PHIDGET)
        deviceStatus = libpointer('int32Ptr', -1);
        calllib('phidget21', 'CPhidget_getDeviceStatus', PHIDGET, deviceStatus);
        if deviceStatus.Value == 1
            disp('Phidget InterfaceKit device already connected')
            return
        else
            cleanUp(PHIDGET);
            PHIDGET = [];
        end
    end
end


handle = libpointer('int32Ptr');
calllib('phidget21', 'CPhidgetInterfaceKit_create', handle);
calllib('phidget21', 'CPhidget_open', handle, -1);

if calllib('phidget21', 'CPhidget_waitForAttachment', handle, 2500) == 0    
    PHIDGET = handle;
    disp('Connected to a Phidget InterfaceKit device')
else
    disp('Could not open InterfaceKit')
    cleanUp(handle);
end

end


function cleanUp(handle)
    calllib('phidget21', 'CPhidget_close', handle);
    calllib('phidget21', 'CPhidget_delete', handle);
end
