function mdsip_shared(varargin)
% Create/remove local link mdsipmex.mexa64 to point to shared version of mdsip
%
% Usage:
% mdsip_shared; % (or mdsip_shared('create')): create link
% mdsip_shared('remove'); % remove link
%
% Static version: mdsipmex compiled without MDSplus libararies.
% Dynamic version: mdsipmex compiled linking to MDSplus libaries, has more
%       functionality but requires MDSplus to be installed.
%
% To access local trees you need the dynamic version. An example;
%
% mdsip_shared; % create link to shared mdsipmex.mexa64
%
% mdsconnect('local');
% mdsopen('tree_name',shot);
% mdsvalue(...)
% mdsdisconnect
%
% mdsip_shared('remove'); % remove link

% F. Felici SPC 2018
%% inputs
action='create'; % default
if numel(varargin)>=1 && ~isempty(varargin)
    action=varargin{1};
end

%%
% check if local mdsipmex exists
mymexa64 = which('./mdsipmex.mexa64');
[s,link] = unix(sprintf('readlink %s',mymexa64));

switch action
    case 'remove'
        if isempty(mymexa64)
            fprintf('no local link found, type mdsip_shared(''create'') to create it\n');
            return
        elseif s~=0
            fprintf('local mdsipmex.mexa64 is not a link, so I won''t remove it\n');
            return
        end
        % local link exists, remove it
        clear mdsipmex;
        remove_link(link);
    case 'create'
        if ~isempty(mymexa64)
            fprintf('mdsip_shared: local mdsipmex.mexa64 alrady exists:\n %s; type mdsip_shared(''remove''); to remove it.\n',mymexa64);
            return
        end
        create_link;
    otherwise
        error('invalid action %s',action)
end
end

function remove_link(link)
[s,w] = unix(sprintf('rm ./mdsipmex.mexa64'));
assert(~s,'error removing file\n %s',w);
fprintf('removed link ./mdsipmex.mexa64 -> %s\n',link);
end


function create_link
assert(~~exist('mdsipmex','file'),'no mdsipmex found in path');
mdsip_path = fileparts(which('mdsipmex'));
mdsipmex_shared = sprintf('%s/mdsipmex.mexa64_shared',mdsip_path);
assert(~~exist(mdsipmex_shared,'file'),'%s does not exist. Maybe another mdsipmex is shadowing the crpptbx one',...
    mdsipmex_shared);
[s,w]=unix(sprintf('ln -sf %s mdsipmex.mexa64',mdsipmex_shared));
if s==0
    fprintf('created link ./mdsipmex.mexa64-> %s\n',mdsipmex_shared);
else
    error('could not create link. Unix error: \n %s',w);
end
end
