function [obs,obs_labels] = LY2Ain(L,LY)
% Transform LY output structure from meq simluation to input of the TCV
% control system.
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
assert(isequal(L.P.tokamak,'TCV'),'Only defined for TCV')

% matrices to connect RZIP outputs to Hybrid controller

%%
mdsconnect('tcvdata.epfl.ch');
mdsopen('pcs',L.P.shot);
Amat_in_labels = mdsvalue('\pcs::phys_mat_a_inputs');

Amat_fl_int     = contains(Amat_in_labels,"CTLINT:VLOOP"); 
Amat_fl_int_rel = contains(Amat_in_labels,"CTLINT:RVLOOP"); 
Amat_bpol_int   = contains(Amat_in_labels,'CTLINT:BPOL_AVG'); 
Amat_iE         = contains(Amat_in_labels,"IPOL_E"); 
Amat_iF         = contains(Amat_in_labels,"IPOL_F"); 
Amat_iOH        = contains(Amat_in_labels,"IPOL_OH"); 
Amat_iG         = contains(Amat_in_labels,'IPOL_G_001'); 

Amat_bpol_amp   = contains(Amat_in_labels,'CTLAMP:BPOL_AVG'); 
Amat_dioh       = contains(Amat_in_labels,'CTLAMP:IPOL_DOH'); 
Amat_fl_amp     = contains(Amat_in_labels,'CTLAMP:VLOOP'); 

% Not all Bpol_amp are actually acquired - get indices those acquired as
% A matrix input

iAmat_bpol_amp = find(Amat_bpol_amp);
indbp_Amat = zeros(numel(iAmat_bpol_amp),1); % init
for ii=1:numel(iAmat_bpol_amp)
  mylabel = deblank(Amat_in_labels{iAmat_bpol_amp(ii)});
  indbp_Amat(ii) = str2double(mylabel(end-2:end));
end

% index of one directly acquired vloop
mylabel = deblank(Amat_in_labels{Amat_fl_amp});
indvloop_Amat(1) = str2double(mylabel(end-2:end));

%% Assign to outputs in same order as A matrix inputs
obs = zeros(120,numel(LY.t)); % init

obs(Amat_fl_int,:)     = LY.Ff(1,:);
obs(Amat_fl_int_rel,:) = LY.Ff(2:end,:)-LY.Ff(1,:);
obs(Amat_bpol_int,:)   = LY.Bm;
obs(Amat_iE,:)         = LY.Ia(contains(L.G.dima,'E_'),:);
obs(Amat_iF,:)         = LY.Ia(contains(L.G.dima,'F_'),:);
obs(Amat_iG,:)         = LY.Ia(contains(L.G.dima,'G_'),:);
obs(Amat_iOH,:)        = LY.Ia(contains(L.G.dima,'OH_'),:);
obs(Amat_dioh,:)       = -diff(obs(Amat_iOH,:),[],1); % OH1-OH2
obs(Amat_bpol_amp,:)   = [zeros(numel(indbp_Amat),1),diff(LY.Bm(indbp_Amat,:),[],2)./diff(LY.t)]; % derivative by finite difference
obs(Amat_fl_amp,:)     = [zeros(numel(indvloop_Amat),1),diff(LY.Ff(indvloop_Amat,:),[],2)./diff(LY.t)]; % derivative by finite difference

obs_labels = Amat_in_labels;
end
