% The following function header is used with minT to minimize
% the maximum wall temperature. Uncomment to use it.
%
%function [Ceq, dCeqdX] = condif(desvar, lb, ub, Tlim)
%
% The following function header is used with optliner.m
% to minimize mass flow subject to a maximum wall temperature.
% Uncomment to use it.

function [C, Ceq, dCdX, dCeqdX] = condif(desvar, lb, ub, Tlim)

dvscal = 0.5*(ub - lb);

Ucool = lb(1) + (desvar(1)+1)*dvscal(1); % m/sec
h     = lb(2) + (desvar(2)+1)*dvscal(2); % Height of liner cooling hole entrance in meters

Uhot  = 100.0; % m/sec

Thot  = 2200; % Kelvin
Tcool =  800; % Kelvin

kg = 0.1;  % Gas thermal diffusion coefficient in W/(m Kelvin)
kw = 26.0; % Wall thermal diffusion coefficient in W/(m Kelvin)

L  = 0.3000;    % Axial spacing between liner cooling holes in meters
tw = 0.0015;    % Thickness of liner wall in meters
h0 = 0.0030;    % Nominal height of liner cooling hole entrance in meters

params = [Uhot, Ucool, Thot, Tcool, kg, kw, L, tw, h, h0];

gridgen;

Nx = imax;
Ny = jmax;

for ii = 1:Nx+1,
  for jj = 1:Ny+1,

    x(ii,jj) = xloc(ii);
    y(ii,jj) = yloc(jj);
    dy_dh(ii,jj) = dyloc_dh(jj);
    
    [u(ii,jj), du_dUcool(ii,jj)] = uinlet(y(ii,jj),params);
    
    T(ii,jj) = Tinlet(y(ii,jj),params);

  end
end

% Calculate residual (r) and Jacobian matrix (A)

condif_res;

% Solve for dT

dT = -A\r;

% Update T

for ii = 1:Nx+1,
  for jj = 1:Ny+1,

    kk0 = ii   + (jj-1)*(Nx+1);
    T(ii,jj) = T(ii,jj) + dT(kk0);

  end
end

% Find drdX for solution

condif_res;

% Calculate output (temperature on upper surface at outlet)

Ceq = T(Nx+1,jupper)/Tlim - 1;

dCeqdU = zeros(N,1);
kkmax  = Nx+1   + (jupper-1)*(Nx+1);
dCeqdU(kkmax) = 1.0/Tlim;


Atran = A';
adj = Atran\dCeqdU;

dCeqdX = zeros(2,1);
dCeqdX(1) = -(adj')*drdX(:,1)*dvscal(1);
dCeqdX(2) = -(adj')*drdX(:,2)*dvscal(2);

C = [];
dCdX = [];

%fprintf(1,'Ucool, h, f(x) = %9.4f %7.5f %10.4f\n',Ucool,h,Ceq);












