function [trace,error,varargout]=loadJETdata(shot,data_type,varargin)
%
% data_type:
% 'Ip'   =  current
% 'zmag' =  vertical position of the center of the plasma (magnetic axis)
% 'rmag' =  radial position of the center of the plasma 
% 'qrho' =  q profile on rho mesh
% 'neint' =  line-integrated electron density [m/m^3]
% 'ne'= ne raw profile on (R,t). ADD error bars in .std
% 'te'= Te raw profile on (R,t). ADD error bars in .std
% 'nerho'= ne profile on (rho=sqrt(psi),time) mesh.Note rho is a 2D array as depends on time. ADD error bars in .std
% 'terho'= Te profile on (rho=sqrt(psi),time) mesh.Note rho is a 2D array as depends on time. ADD error bars in .std
%          Now, use CHAIN2 lid2/neo and teo for nerho, terho
% 'ece'  =  electron cyclotron emission
% 'sxr'  =  soft x-ray emission 
% 'sxR'  =  soft x-ray emission with varargout{1} option (requires varargin{5}!)
%
% Special case compatible with old gdat.m allows (JET related):
%     gdat(51994,'ppf','efit/xip',...)
%
% INPUT:
% shot: shot number
% data_type: type of the required data.
%
% Allows extension for uid and seq number a la RDA: ?uid=jetthg+seq=110
% examples:
%
%                          data_type='Ip?uid=jetthg+seq=110'
%                          data_type='ppf','efit/xip?uid=jetthg+seq=110'
%
% for EFIT traces, allows keyword extension '_m' to get data from ppf/efitm instead of ppf/efit
% examples:
%
%                          data_type='Ip_m?uid=jetthg+seq=110'
%                          data_type='ppf','efitm/xip?uid=jetthg+seq=110'
%
% Meaning of varargin depends on data_type:
%
% data_type=sxr or ece:
%                  varargin{1}:  [i1 i2] : if not empty, assumes need many chords from i1 to i2
%                  varargin{2}:  channel status: 1=unread yet, 0=read
%                                (for traces with many channel, enables to load additional channels,
%                                 like SXR, ECE, etc.)
%                  varargin{3}:  zmag for varargout{1} computation
%
%
% OUTPUT:
% trace.data:   data structure
% trace.t:      time of reference 
% trace.x:      space of reference 
% error:        error in loading signal (0=> OK, 1=> error)
%
% Additional Output arguments depending on data_type
%
% data_type=sxR:
%                varargout{1}: intersection of the view lines with magnetic axis
%
% functions needed: jetreaddata or mdsplus routines
%
% Example:
%         [zmag,error]=loadJETdata(shot,'zmag');
%

varargout=cell(1,1);
error=1;

% To allow multiple ways of writing a specific keyword, use data_type_eff within this routine

data_type_eff=data_type;

i_efitm=0;
i_ext=length(data_type_eff)+1;
name_ext='';
if size(data_type_eff,1)==1
  i=findstr('?',data_type_eff);
  if ~isempty(i)
    i_ext=i;
    name_ext=data_type_eff(i_ext:end);
  end
  data_type_eff_noext=data_type_eff(1:i_ext-1);
  i=findstr('_m',data_type_eff_noext);
  if ~isempty(i)
    i_efitm=1;
    data_type_eff_noext=data_type_eff(1:i-1);
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'ip'} {'i_p'} {'xip'}],'exact'))
    data_type_eff_noext='Ip';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'Te'} {'t_e'} {'TE'} {'T_e'}],'exact'))
    data_type_eff_noext='te';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'Ne'} {'n_e'} {'NE'} {'N_e'}],'exact'))
    data_type_eff_noext='ne';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'Terho'}],'exact'))
    data_type_eff_noext='terho';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'SXR'}],'exact'))
    data_type_eff_noext='sxr';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'ECE'}],'exact'))
    data_type_eff_noext='ece';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'Rmag'}],'exact'))
    data_type_eff_noext='rmag';
  end
  if ~isempty(strmatch(data_type_eff_noext,[{'Zmag'}],'exact'))
    data_type_eff_noext='zmag';
  end
else
  i_ext=length(data_type_eff{2})+1;
  name_ext='';
  i=findstr('?',data_type_eff{2});
  if ~isempty(i)
    i_ext=i;
    name_ext=data_type_eff{2}(i_ext:end);
  end
  data_type_eff_noext=data_type_eff{2}(1:i_ext-1);
end

% all keywords and corresponding case to run below
JETkeywrdall=[{'Ip'} {'zmag'} {'rmag'} {'qrho'} {'neint'} ...
      {'ne'} {'te'} {'nerho'} {'terho'} ...
      {'sxr'} {'sxR'} {'ece'}];
JETsig.iip=strmatch('Ip',JETkeywrdall,'exact');
JETsig.izmag=strmatch('zmag',JETkeywrdall,'exact');
JETsig.irmag=strmatch('rmag',JETkeywrdall,'exact');
JETsig.iqrho=strmatch('qrho',JETkeywrdall,'exact');
JETsig.ineint=strmatch('neint',JETkeywrdall,'exact');
JETsig.ine=strmatch('ne',JETkeywrdall,'exact');
JETsig.ite=strmatch('te',JETkeywrdall,'exact');
JETsig.inerho=strmatch('nerho',JETkeywrdall,'exact');
JETsig.iterho=strmatch('terho',JETkeywrdall,'exact');
JETsig.isxr=strmatch('sxr',JETkeywrdall,'exact');
JETsig.isxR=strmatch('sxR',JETkeywrdall,'exact');
JETsig.iece=strmatch('ece',JETkeywrdall,'exact');

% For each keyword, specify which case to use. As most common is 'simplereaddata', fill in with this and change
% only indices needed. Usually use name of case same as keyword name
JETkeywrdcase=cell(size(JETkeywrdall));
JETkeywrdcase(:)={'simplereaddata'};
JETkeywrdcase(JETsig.iqrho)=JETkeywrdall(JETsig.iqrho); % special as efit q on psi
JETkeywrdcase(JETsig.ine)=JETkeywrdall(JETsig.ine); % special as adds error bars
JETkeywrdcase(JETsig.ite)=JETkeywrdall(JETsig.ite); % idem
JETkeywrdcase(JETsig.inerho)=JETkeywrdall(JETsig.inerho); % idem
JETkeywrdcase(JETsig.iterho)=JETkeywrdall(JETsig.iterho); % idem
JETkeywrdcase(JETsig.isxr)=JETkeywrdall(JETsig.isxr);
JETkeywrdcase(JETsig.isxR)=JETkeywrdall(JETsig.isxR);
JETkeywrdcase(JETsig.iece)=JETkeywrdall(JETsig.iece);

% Information about which dimension has time, always return 2D data as (x,t) array
% as most are 1D arrays with time as first index, fill in with ones and change only those needed
JETsigtimeindx=ones(size(JETkeywrdall));

% For the 'simplereaddata' cases, we need the full node in case gdat was called with full location directly
% for the other cases, leave this location empty
JETsiglocation=cell(2,size(JETkeywrdall,2));
JETsiglocation(:)={''};
JETsiglocation(:,JETsig.iip)={'ppf'; 'efit/xip'};
JETsiglocation(:,JETsig.izmag)={'ppf'; 'efit/zmag'};
JETsiglocation(:,JETsig.irmag)={'ppf'; 'efit/rmag'};
JETsiglocation(:,JETsig.ineint)={'ppf'; 'kg1v/lid3'};

% initialize order of substructures and allows just a "return" if data empty
trace.data=[];
trace.x=[];
trace.t=[];
trace.dim=[];
trace.dimunits=[];

% find index of signal called upon
if size(data_type_eff,1)==2
  % in case node name was given in 2 parts directly (as old way)
  ii1=strmatch(data_type_eff(1),JETsiglocation(1,:),'exact');
  index=find(strmatch(data_type_eff_noext,JETsiglocation(2,ii1),'exact'));
  if isempty(index)
    disp('********************')
    disp('trace not yet registered.')
    disp('If standard data, ask andrea.scarabosio@epfl.ch or olivier.sauter@epfl.ch to create a keyqord entry for this data')
    eval(['!mail -s ''' data_type_eff{1} ' ' data_type_eff{2} ' ' num2str(shot) ' ' ...
          getenv('USER') ' JET'' olivier.sauter@epfl.ch < /dev/null'])
    disp('********************')
    % temporarily add entry in arrays, so can work below
    index=length(JETkeywrdall)+1;
    JETkeywrdall(end+1)={'new'};
    JETkeywrdcase(end+1)={'simplereaddata'};
    JETsiglocation(1:2,end+1)=[data_type_eff(1) ; {data_type_eff_noext}];
    JETsigtimeindx(end+1)=0;
  elseif ~strcmp(JETkeywrdcase{index},'simplereaddata')
    msgbox(['Problem in loadJETdata with data_type_eff = ' char(data_type_eff(end)) ...
          '. Full paths of nodes should only be for case simplereaddata'],'in loadJETdata','error')
    error('in loadJETdata')
  end
else
  index=strmatch(data_type_eff_noext,JETkeywrdall,'exact');
  if isempty(index)
    disp(' ')
    disp('********************')
    disp(['no such keyword: ' data_type_eff(1:end-i_23)])
    disp(' ')
    disp('Available keywords:')
    JETkeywrdall(:)
    disp('********************')
    return
  end
end
disp(' ')
disp(['loading' ' ' char(data_type_eff(end)) ' from JET shot #' num2str(shot)]); 
disp(['case ' JETkeywrdcase{index}])
disp(' ')
switch JETkeywrdcase{index}

  %&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  case 'simplereaddata'

    ppftype=JETsiglocation{1,index};
    if i_efitm; 
      tracename=['eftm' JETsiglocation{2,index}(5:end) name_ext];
    else
      tracename=[JETsiglocation{2,index} name_ext];
    end
    [a,x,t,d,e]=rda_eff(shot,ppftype,tracename);
    trace.data=a;
    trace.x=x;
    trace.t=t;
    clear error
    error=e;
    if length(size(trace.data))==1 | (length(size(trace.data))==2 & size(trace.data,2)==1)
      trace.dim=[{trace.t}];
      trace.dimunits(1)={'time [s]'};
    elseif length(size(trace.data))==2
      trace.dim=[{trace.x} ; {trace.t}];
      trace.dimunits=[{'R [m] or rho=sqrt(psi_norm)'} ; {'time [s]'}];
    else
      disp('how to deal with 3D arrays?')
      trace.dim=[{trace.x} ; {trace.t} ; {d}];
      trace.dimunits=[{'R [m] or rho=sqrt(psi_norm)'} ; {'time [s]'} ; {'d'}];
      trace.d=d;
    end

  %&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  case {JETkeywrdall{JETsig.ine} , JETkeywrdall{JETsig.ite}}
    %  ne, te raw data from LIDR vs R,t. Add error bars
    ppftype='ppf';
    if strcmp(JETkeywrdcase{index},JETkeywrdall{JETsig.ine})
      tracename=['LIDR/NE' name_ext];
    else
      tracename=['LIDR/TE' name_ext];
    end
    [a,t,x,d,e]=jetreaddata(['http://data.jet.uk/' ppftype '/' num2str(shot) '/' tracename]);
    trace.data=a';
    trace.x=x;
    trace.t=t;
    trace.dim=[{trace.x} ; {trace.t}];
    trace.dimunits=[{'R [m]'} ; {'time [s]'}];
    clear error
    error=e;

  %&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  case {JETkeywrdall{JETsig.inerho} , JETkeywrdall{JETsig.iterho}}
    %  ne, te on rho mesh. use lid2, thus need chain2 to have been run. Add error bars
    ppftype='ppf';
    if strcmp(JETkeywrdcase{index},JETkeywrdall{JETsig.inerho})
      tracename=['LID2/NEO' name_ext];
    else
      tracename=['LID2/TEO' name_ext];
    end
    [a,t,x,d,e]=jetreaddata(['http://data.jet.uk/' ppftype '/' num2str(shot) '/' tracename]);
    trace.data=a';
    trace.x=x;
    trace.t=t;
    trace.dim=[{trace.x} ; {trace.t}];
    trace.dimunits=[{'rho=sqrt(psi)'} ; {'time [s]'}];
    clear error
    error=e;


  %&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  case {'sxr','sxR'}
    %  LOAD MULTI CHANNEL DATA    
    %  load JET soft x-ray data 
    % parameters needed for correct convertion of JET Sxr data
    vconvert=   [1.379 1.311 1.249 1.191 1.139 1.093 1.049 ...
                 1.011 0.975 0.945 0.917 0.893 0.873 0.856 ...
                 0.842 0.829 0.821 0.815 0.821 0.829 0.842 ...
                 0.856 0.873 0.894 0.918 0.946 0.976 1.012 ...
                 1.050 1.094 1.141 1.193 1.251 1.313 1.382];
    if  nargin>=3 & ~isempty(varargin{1})
      starti=varargin{1}(1);
      endi=varargin{1}(2);
    else
      starti=1;
      endi=24;
    end
    if  nargin>=4 & ~isempty(varargin{2})
      status=varargin{2};
    else
      status=ones(endi-starti+1,1);
    end
    for i=starti:endi
      % Read channels from lowchannel to upchannel if necessary
      if status(i)==1
        % Status=1 => Not Read Yet
        % vertical SXR chords
        ppftype='jpf';
        tracename=['db/j3-sxr<v' num2str(i) '''''/1' name_ext];
        [a,t,x,d,e]=jetreaddata(['http://data.jet.uk/' ppftype '/' num2str(shot) '/' tracename]);
        % Convert from raw sxr data to W/m^2
        trace.data(i,:) = a' * vconvert(i);
        trace.t=t;
        trace.x(i,:)=x; 
        error=e;
      end  
      trace.dim=[{[starti:endi]'} ; {trace.t}];
      trace.dimunits=[{'channels'} ; {'time [s]'}];
    end
    % calculating intersection of the view lines with magnetics axis 
    if strcmp(data_type_eff_noext,'sxR')
      if nargin>=5 & ~isempty(varargin{3})
        zmag=varargin{3};
      else
        zmag=loadJETdata(shot,'zmag');
      end
      zmageff=interpos(13,zmag.t,zmag.data,trace.t);
      for i=starti:endi
        radius(i,:)=2.848 + (2.172-zmageff') .* tan(-4.5/180.*3.14159 - atan2(0.99.*(i-18),35.31));
      end
      varargout={{radius}}; 
    end

  %&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
  case 'ece'
    if  nargin>=3 & ~isempty(varargin{1})
      starti=varargin{1}(1);
      endi=varargin{1}(2);
    else
      starti=1;
      endi=24;
    end
    if nargin>=4 & ~isempty(varargin{2})
      status=varargin{2};
    else
      status=ones(endi-starti+1,1);
    end
    % Read channels from lowchannel to upchannel if necessary     
    for i=starti:endi
      if status(i)==1
        % ECE, te0
        % Status=1 => Not Read Yet
        ppftype='ppf';
        tracename=['kk3/te' num2str(i,'%2.2d') name_ext];
        [a,t,x,d,e]=jetreaddata(['http://data.jet.uk/' ppftype '/' num2str(shot) '/' tracename]);
        trace.data(i,:)=a';
        trace.t=t;
        trace.x(i,:)=x'; 
        error=e;
        ppftype='ppf';
        tracename=['kk3/rc' num2str(i,'%2.2d') name_ext];
        [a,t,x,d,e]=jetreaddata(['http://data.jet.uk/' ppftype '/' num2str(shot) '/' tracename]);
        radius.data(i,:)=a';
        radius.t=t;
        radius.x(i,:)=x'; 
      end
    end 
    trace.dim=[{[starti:endi]'} ; {trace.t}];
    trace.dimunits=[{'channels'} ; {'time [s]'}];
    varargout={{radius}}; 

  otherwise
    disp('case not yet defined')
    
end