function [x,range,maxlag] = db2dp(this,d,range,varargin)
% dp2db  Convert database to bkwmodel-specific datapack.
%
% Backend IRIS function.
% No help provided.

%**************************************************************************

maxlag = size(this.occur,3) - 1;
available = false([1,length(this.name)]);
for i = find(this.nametype <= 3)
   available(i) = ...
      isfield(d,this.name{i}) && isa(d.(this.name{i}),'tseries');
end

if isinf(range(1))
   startdate = autostartdate_();
else
   startdate = range(1);
end
if isinf(range(end))
   enddate = autoenddate_();
else
   enddate = range(end);
end

if isinf(startdate) || isnan(startdate)
   utils.error('bkwmodel', ...
      'Cannot determine the start-date of the range.');
end
if isinf(enddate) || isnan(enddate)
   utils.error('bkwmodel', ...
      'Cannot determine the end-date of the range.');
end

range = startdate : enddate;
nper = length(range);
nalt = size(this.Assign,3);
nx = sum(this.nametype == 1);
nz = sum(this.nametype == 2);
ne = sum(this.nametype == 3);
np = sum(this.nametype == 4);

x = nan([nx+nz+np,nper,1]);
for i = find(this.nametype <= 3)
   if available(i)
      temp = rangedata(d.(this.name{i}),range);
   else
      temp = nan([nper,nalt]);
   end
   nx = size(x,3);
   ntemp = size(temp,2);
   if ntemp < nalt
      temp(:,end+1:nalt) = temp(:,end*ones([1,nalt-end]));
      ntemp = nalt;
   end
   if nx < ntemp
      x(:,:,end+1:ntemp) = x(:,:,end*ones([1,ntemp-end]));
   end
   if this.nametype(i) == 3
      temp(isnan(temp)) = 0;
   end
   x(i,:,:) = permute(temp,[3,1,2]);
end

ndata = size(x,3);
for i = find(this.nametype == 4)
   temp = this.Assign(1,i,:);
   temp = temp(1,ones([1,nper]),:);
   ntemp = size(temp,3);
   if ntemp < ndata
      temp(:,:,end+1:ndata) = temp(:,:,end*ones([1,ndata-end]));
   end
   x(i,:,:) = temp;
end

% Nested functions follow.

   %***********************************************************************
   % Nested function.
   function startdate = autostartdate_()
      startdate = [];
      for i = find(this.nametype <= 2)
         if available(i)
            thismaxlag = find(any(this.occur(:,i,:),1),1,'last') - 1;
            if ~isempty(thismaxlag)
               startdate(end+1) = ...
                  get(d.(this.name{i}),'start') + thismaxlag;
            end
         end
      end
      startdate = max(startdate);% - maxlag;
   end
   % End of nested function autostartdate_().

   %***********************************************************************
   % Nested function.
   function enddate = autoenddate_()
      enddate = Inf;
      for i = find(this.nametype <= 2)
         if available(i)
            enddate = min([enddate,get(d.(this.name{i}),'end')]);
         end
      end
   end
   % End of nested function autoenddate_().

end