function [estimat, jacksamp] = Ejackknif(jackfun,d1,d2,d3,d4,d5)
%   [estimat, jacksamp] = jackknif(fun,d1,d2,d3,d4,d5)
%   produces jackknife-estimates
%       References:
%         [1] B. Efron & R.J Tibshirani, "An Introduction to the Bootstrap"
%
% Input:
% jackfun=function used for estimation
% d1-d5=data or parameters for function jackfun
% These must be scalars (parameters) or vectors of n elements ("observations") 
% or matrices (vectors of "observations") of n rows
% 
%   [estimat,jacksamp] = jackknif(...) Each row of JACKSAMP contains
%   the results of JACKFUN on each jackknife-sample. 
%   If JACKFUN returns a matrix,
%   then this output is converted to a long vector for storage in JACKSAMP.
%   

% Output:
% estimat=estimate of the parameter based on the whole sample
% jacksamp=vector of estimates based on the jackknife-samples (i.e. with observation i deleted) 


scalard=zeros(nargin-1,1);

ds='d';
c=',';

for k=2:nargin
	dk=[ds, num2str(k-1)];
	[row, col]=size(eval(dk));

	if max(row,col)==1
		scalard(k-1)=1;
	end

	if row==1 & scalard(k-1)==0
		eval([dk,'=',dk,'(:);']);
		row=col;
	end
	
	if k==2
		pstring=['(', dk, '(val,:)'];
	nrow=row;
	elseif scalard(k-1)==0
		pstring=[pstring, c, dk, '(val,:)'];
	else pstring=[pstring, c, dk ];
	end

	if k==nargin 
		pstring=[pstring, ')'];
	end
end

% Create the array s which holds the trial values
for j=1:nrow
        % Separate out all values except the j-th
        if j==1
                val = [2:nrow];
        elseif j==nrow
                val = [1:nrow-1];
        else 
                val = [1:j-1, j+1:nrow];
        end
	% evaluate estimate for j:th jackknife-sample
	t=eval([jackfun, pstring]); 
	t=t';
	t=t(:);
	% store estimate for j:th jackknife-sample
	jacksamp(j,:) = t';
end

val=1:nrow;
% calculate original estimate using all data
estimat=eval([jackfun, pstring]); 
estimat=estimat';
estimat=estimat(:)';
