function [tip,dtip_dx] = eval_tip(x,g,v,model,gauss)
% function [tip,dtip_dx] = eval_tip(x,g,model,whichgrid)
% #codegen
use_core_spline_base = hmode_spline_base_active(v,model);

if nargout>1
  % init
  if ~gauss
    dtip_dx = zeros(model.rgrid.nrho,numel(x)); % init
  else
    dtip_dx = zeros(model.rgrid.nrhogauss,numel(x)); % init
  end
end


switch model.ti.method
  case 'tescal'
    % tip is scaled version of tep.
    % scaling of x coefficients is stored in v
    tep = eval_tep(x,g,v,model,gauss);
    
    if gauss
      scal = model.ti.Lamgauss*v(model.ti.vind,:);
    else
      scal = model.ti.Lam*v(model.ti.vind,:);
    end
    tip =  scal.*tep;
    
    if nargout>1
      [~,dtep_dx] = eval_tep(x,g,v,model,gauss);
      dtip_dx = bsxfun(@times,scal,dtep_dx);
    end
  case 'direct'
    % ti is directly specified by v
    if gauss
      tip = model.ti.Lampgauss*v(model.ti.vind,:);
    else
      tip = model.ti.Lamp*v(model.ti.vind,:);
    end
  case 'state'
    % ti is in state
    if ~use_core_spline_base
      if gauss
        dtip_dtihat = model.ti.Lampgauss;
      else
        dtip_dtihat = model.ti.Lamp;
      end
      tip = dtip_dtihat * x(model.ti.xind,:);
      
      if nargout==2 % optinal derivative
        dtip_dx(:,model.ti.xind) = dtip_dtihat;
      end
    else
      if size(v,2)>1 
        if any(v(model.hmode.vind.activation, :)) && ~all(v(model.hmode.vind.activation, :))
          error('eval_tip for time dependent V not implemented for varying spline basis')
        end
      end
      if gauss
        dtip_dxx = model.ti.Lampgauss_hmode;
      else
        dtip_dxx = model.ti.Lamp_hmode;
      end
      xx = [x(model.ti.xind,:); v(model.hmode.vind.ti_rhoedge,:)./model.ti.scal];
      tip = dtip_dxx*xx;
      dtip_dtihat = dtip_dxx(:, 1:end-1);
      dtip_dx(:,model.ti.xind) = dtip_dtihat;
    end
    
  otherwise
    error('not implemented yet')
end

return
