function opt=rjxoptions(options,argin)
% RJXOPTIONS(options,argin)
%   This function overwrites the default values
%   specified in 'options', a cell matrix, by those nonempty
%   values that are specifyed by the cellvector 'argin'. 'argin' is 
%   of the form {'Property1',Propertyvalue1,'Property2',Propertyvalue2 ...}
%   'argin' can also contain packages (cellvectors) of various
%   settings, usable if one is often having the same parameters in 
%   program calling for instance rjxsurfline.
%
%   Example>>
%   
%   Defaultfile={'Hubba',1;'Bubba',2;'Toy',3;'Extra',4};
%   packagelist={'Hubba',7,'Toy',8};
%   rjxoptions(Defaultfile,{'settings',packagelist,'Extra',1000})
%  
%   ans = 
% 
%     [   7]
%     [  14]
%     [   8]
%     [1000]
%
%   But equivalently we could substitute the last line with:
%   rjxoptions(Defaultfile,{packagelist{:},'Extra',1000})
%
% Notice that 'Options' is a cell-matrix whereas the 'argin'
% and possible 'settings' within 'argin' should be simple
% cell-vectors. 

if rem(length(argin),2)==1
   error('RJ: Property value pairs expected.')
end

if size(argin,1)>1 & size(argin,2)>1;
    error('RJ: Settings must be a vector-list')
end

%%%%% Unpacking 'settings' from the argin   %%%%%%%%%%%%%%%%%%
%%%%% Notice the difference between { and ( %%%%%%%%%%%%%%%%%%

list=argin;
i=1;
while i<length(list)
    if isequal(list{i},'settings')
        temp=list{i+1};
        if rem(length(temp),2)==1;
            error('RJ: Property value pairs in ''settings'' expected.')
        end
        if size(temp,1)~=1 & size(temp,2)~=1
            error('RJ: ''settings'' must be a vector-list')
        end
        list=[list(1:i-1), temp, list(i+2:length(list))];
    else
        i=i+2;
    end
end

%%%%% Overwriting the defaultvalues according to list %%%%%%%%

opt=options(:,2);     
for i=1:2:length(list)-1
    found='false';
    for j=1:size(options,1)
        if isequal(list(i),options(j,1))
            if ~isempty(list{i+1})
                opt(j)=list(i+1);
            end
            found='true';
        end
    end
    if isequal(found,'false')
        if isstr(list{i})
            error(['RJ: Unknown option: ' list{i} ])
        else
            error('RJ: Options must be strings')
        end
    end
end








