% pro fbte18,index,pcs_path,ioh1values,nobphi=nobphi
function fbte18(index,pcs_path,ioh1values,nobphi)
% ;ympro fbte18,index,nogas=nogas,nobphi=nobphi
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; As such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ; Updated/Reason:
% ; Sept 98 to add keywords to stop FBTE overwriting the gas/bphi
% 
% ; Controlled by :       Jo
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; *****************************************************
% 
% ; Jo Lister October 1992
% 
% ; Provides a template for interfacing individual algorithms to the
% ; TCV Plasma Control System (PCS)
% 
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; obligatory code is defined like this, between the + and the -
% ;----------------------------------------------------------------
% 
% ; Obligatory user-actions are defined with an end-of-line               ;!!!!!!!!
% 
% ; *****************************************************
% 
% ; F. Hofmann, November 1994
% 
% ; To control a circular plasma corresponding to equilibrium fbte36
% 
% ALGO = 'FBTE18'								;!!!!!!!!
algo = mfilename;
% 
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Obligatory bookkeeping                             ;
% !tcvcs_error = ' '                                              ;
% algo = string(algo)                                             ;
% print,'STARTING '+algo+' @ '+!stime                             ;
% 
% ; check that there is an index argument                         ;
% if (n_params() lt 1) then begin                                 ;
%  print,algo+' takes at least 1 argument'                        ;
%  return                                                         ;
% endif                                                           ;
if nargin < 1, error('fbte18 takes at least 1 argument'), end
% if (not keyword_set(pcs_path)) then begin                       ;
%   pcs_path='hybrid'
% endif
if nargin < 2 || isempty(pcs_path), pcs_path = 'hybrid'; end
% pcs_path=strlowcase(pcs_path)
pcs_path = lower(pcs_path);
% print,'PCS_PATH is '+pcs_path
% ; ########## Get the Mutual Matrix, and use its labelling list  ;
% mds$open,'tcv_shot',-1                                          ;
mdsopen('tcv_shot',-1)
% mds$put,'\PCS::TOP:ID','"""'+algo+'"""'                         ;
mdsput('\PCS::TOP:ID',algo);
% 
% ; initialize the Wavegen masks
% wave_mask=fltarr(128)+1.0
wave_mask = ones(128,1);
% mds$put,'\load_wave_mask','$',wave_mask
mdsput('\load_wave_mask',mdscvt(wave_mask,'f'))
% 
% ; ########## Define the A Matrix lists                          ;
% ;----------------------------------------------------------------
% 
% ; read conmat18.sav 
% 
% ; Set up MGAMS default directory according to Physicien-du-Jour.
% ; if  FH --> USER:[HOFMANN.MGA]
% ; if  HW --> USER:[WEISEN.MGAMS]
% ; if  JM --> USER:[MORET.MGAMS]  
% ; if  CN --> USER:[NIESWAND.MGAMS]
% ; if  YM --> USER:[MARTIN.MGAMS]    
% ;pdj=strupcase(strmid(vcs_sget('OPERATORDB::PDJ:NAME'),0,2))
% ;case pdj of
% ;	'JM': mga_dir='USER:[MORET.MGAMS]' 
% ;	'HW': mga_dir='USER:[WEISEN.MGAMS]' 
% ;	'FH': mga_dir='USER:[HOFMANN.MGA]'
% ;	'CN': mga_dir='USER:[NIESWAND.MGAMS]' 
% ;	'YM': mga_dir='USER:[MARTIN.MGAMS]' 
% ;;	ELSE: mga_dir='USER:[HOFMANN.MGA]' ; !! Too dangerous, better to STOP
% ;	ELSE: begin
% ;		print,'STOPPING: Unknown PdJ - Please specify and retry'
% ;		!tcvcs_error = 'FBTE18: A valid "PdJ" must be specified --> retry'
% ;		return
% ;	      end
% ;endcase
% ;mga_dir='TCV_ROOT:[TCV_OPER.MGAMS]'
% ;print,'Setting MGAMS directory for the PdJ to : ',mga_dir
% ;restore,mga_dir+'CONMAT18.SAV'
% 
% ; instructions for reading from nodes instead (SC, 11/03/11)
% mds$tcl,'set def \mgams.mga'
mdssetdef('\mgams.mga')
% 
% ;; The automatic way below does not work in IDL because:
% ;;   "Do not use EXECUTE to create new variables 
% ;;    inside procedures or functions. Attempts to create 
% ;;    new variables result in the error "Program data area full"."
% ;; However, this can be used as a template for Matlab translation using eval
% ;nodes=mds$value('getnci("\\mgams.mga:*","path")')    
% ;ind=strpos(nodes(0),'MGA:')
% ;for nn=0,n_elements(nodes)-1 do begin
% ;  node=nodes(nn)
% ;  varname=strlowcase(strmid(node,ind+4,strlen(node)-ind-4))
% ;  dummy=execute(varname+' = mds$value(''execute(_nodes['+ii(nn)+'])'')')
% ;endfor
% 
% ; the explicit list below is a block generated by mgaread_generate.pro and
% ;   contained in mgaread.pro
% aaasw = mds$value('aaasw')
aaasw = mdsdata('aaasw');
% aipoft = mds$value('aipoft')
aipoft = mdsdata('aipoft');
% amlsw = mds$value('amlsw')
amlsw = mdsdata('amlsw');
% bzeroft = mds$value('bzeroft')
bzeroft = mdsdata('bzeroft');
% cayref = mds$value('cayref')
cayref = mdsdata('cayref');
% efcur = mds$value('efcur')
efcur = mdsdata('efcur');
% efvolt = mds$value('efvolt')
efvolt = mdsdata('efvolt');
% efwave = mds$value('efwave')
efwave = mdsdata('efwave');
% g1sw = mds$value('g1sw')
g1sw = mdsdata('g1sw');
% g2sw = mds$value('g2sw')
g2sw = mdsdata('g2sw');
% g3sw = mds$value('g3sw')
g3sw = mdsdata('g3sw');
% midplan = mds$value('midplan')
midplan = mdsdata('midplan');
% ;nca = mds$value('nca')
% ;ncg = mds$value('ncg')
% ;ncm = mds$value('ncm')
% ;noht = mds$value('noht')
% ;nra = mds$value('nra')
% ;nrg = mds$value('nrg')
% ;nrm = mds$value('nrm')
% ;nsw = mds$value('nsw')
% ;ntoft = mds$value('ntoft')
% ohcur = mds$value('ohcur')
ohcur = mdsdata('ohcur');
% toft = mds$value('toft')
toft = mdsdata('toft');
% toh = mds$value('toh')
toh = mdsdata('toh');
% zeref = mds$value('zeref')
zeref = mdsdata('zeref');
% ntoft = n_elements(toft)
ntoft = length(toft);
% 
% ; Additional reads from \mgams.data
% mds$tcl,'set def \mgams.data'
mdssetdef('\mgams.data')
% aipgain = mds$value('aipgain')
% % aipgain = mdsdata('aipgain');
% inova = mds$value('inova')
inova = mdsdata('inova');
% iscramb = mds$value('iscramb')
iscramb = mdsdata('iscramb');
% mvloop = mds$value('mvloop')
mvloop = mdsdata('mvloop');
% nfast = mds$value('nfast')
nfast = mdsdata('nfast');
% relovo = mds$value('relovo')
relovo = mdsdata('relovo');
% 
% mds$tcl,'set def \top'
mdssetdef('\top')
% 
% !error=0
% 
% toh2=toh
toh2 = toh;
% 
% ;get real to virtual flux/voltage transformation matrix 
% tfr=mds$value('\MAGNETICS::T_F_R')
tfr = mdsdata('\MAGNETICS::T_F_R');
% 
% ; ##########################################  create the A-Matrix
% 
% ; specify the inputs to be used
% 
% ; MODIFIED TO REMOVE RVLOOP_003
% ; replace CTLAMP:UPOL_G_001 on ch. 118 by 1MM_FRINGE (SC, 27/02/11)
% amat_inputs = [                                            	$  !!!!!!!
%  	'CTLINT:VLOOP_001', 					$
% 	'CTLINT:RVLOOP_'+iii(indgen(37)+2), 			$
%        	'CTLINT:BPOL_AVG_'+iii(indgen(38)+1), 			$
%        	'CTLAMP:IPOL_E_'+iii(indgen(8)+1),			$
%  	'CTLAMP:IPOL_F_'+iii(indgen(8)+1),			$
%  	'CTLAMP:IPOL_OH_'+iii(indgen(2)+1),			$
% 	'CTLAMP:BPOL_AVG_'+iii([2,3,4,5,6,8,11,17,18,19]),	$
% 	'CTLAMP:BPOL_AVG_'+iii([21,22,23,29,32,34,35,36,37,38]), $
%       	'CTLAMP:IPOL_DOH_001',                                  $
%         'FIR_FRINGE',                                           $
%         'CTLAMP:IPOL_G_001',                                    $
%         '1MM_FRINGE','CTLAMP:VLOOP_001','CTLAMP:IPHI_001']
amat_inputs = {
 	'CTLINT:VLOOP_001',...
	'CTLINT:RVLOOP_'+iii(2:38),...
       	'CTLINT:BPOL_AVG_'+iii(1:38),...
       	'CTLAMP:IPOL_E_'+iii(1:8),...
 	'CTLAMP:IPOL_F_'+iii(1:8),...
 	'CTLAMP:IPOL_OH_'+iii([1 2]),...
	'CTLAMP:BPOL_AVG_'+iii([2,3,4,5,6,8,11,17,18,19]),...
	'CTLAMP:BPOL_AVG_'+iii([21,22,23,29,32,34,35,36,37,38]),...
      	'CTLAMP:IPOL_DOH_001',...
        'FIR_FRINGE',...
        'CTLAMP:IPOL_G_001',...
        '1MM_FRINGE','CTLAMP:VLOOP_001','CTLAMP:IPHI_001'};
%                          
% ; specify the outputs to be used				;!!!!!!!!!
% amat_outputs = [				$
%  'cp001', 'cp002', 'cp003', 'cp004', 'cp005',   $	; eps-psi
%  'cp006', 'cp007', 'cp008', 'cp009', 'cp010',   $	; eps-psi
%  'cp011', 'cp020', 'cp019', 'cp014', 'cp015',   $	; eps-psi
%  'cp016', 'cp017', 'cp018',		  	$	; eps-psi
%  'cp013_IP',					$    	; Ip    
%  'cp012_IP*Z',					$    	; Ip*Zp 
%  'cp021_DENS',					$    	; Fringes
%  'cp022', 'cp023', 'cp024']
amat_outputs = {
 'cp001', 'cp002', 'cp003', 'cp004', 'cp005',...
 'cp006', 'cp007', 'cp008', 'cp009', 'cp010',...
 'cp011', 'cp020', 'cp019', 'cp014', 'cp015',...
 'cp016', 'cp017', 'cp018',...
 'cp013_IP',...
 'cp012_IP*Z',...
 'cp021_DENS',...
 'cp022', 'cp023', 'cp024'};
% ; #################################################### GATES
% 
% if midplan ne 8 then begin
if midplan ~= 8
%    if nfast eq 0 then begin
 if nfast == 0
%    if iscramb ne 12 and iscramb ne 15 and iscramb ne 16 and iscramb ne 19 $
% 	and iscramb ne 25 and iscramb ne 26 and iscramb ne 36 $
% 	and mvloop(0) ne 6 then begin
  if iscramb ~= 12 && iscramb ~= 15 && iscramb ~= 16 && iscramb ~= 19 ...
   && iscramb ~= 25 && iscramb ~= 26 && iscramb ~= 36 ...
   && mvloop(0) ~= 6
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','!','!','!']
   amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
               '_DELTA_OH','_DELTA_R','A','A','A','!','!','!'});
%    endif
%    if iscramb eq 12 or iscramb eq 15 or iscramb eq 16 or iscramb eq 19 $
% 	or iscramb eq 25 or iscramb eq 26 or iscramb eq 36 $
% 	or mvloop(0) eq 6 then begin
  else
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','A','!','!']
   amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
              '_DELTA_OH','_DELTA_R','A','A','A','A','!','!'});
%    endif 
  end
%    endif
 end
%    if nfast ne 0 then begin
 if nfast ~= 0
%    if nfast ne -5 then begin
  if nfast ~= -5
%    if iscramb ne 12 and iscramb ne 15 and iscramb ne 16 and iscramb ne 19 $
% 	and iscramb ne 25 and iscramb ne 26 and iscramb ne 36 $
% 	and mvloop(0) ne 6 then begin
   if iscramb ~= 12 && iscramb ~= 15 && iscramb ~= 16 && iscramb ~= 19 ...
    && iscramb ~= 25 && iscramb ~= 26 && iscramb ~= 36 ...
    && mvloop(0) ~= 6
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','!','A','!']
    amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
                '_DELTA_OH','_DELTA_R','A','A','A','!','A','!'});
%    endif
%    if iscramb eq 12 or iscramb eq 15 or iscramb eq 16 or iscramb eq 19 $
% 	or iscramb eq 25 or iscramb eq 26 or iscramb eq 36 $
% 	or mvloop(0) eq 6 then begin
   else
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','A','A','!']
    amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
                '_DELTA_OH','_DELTA_R','A','A','A','A','A','!'});
%    endif 
   end
%    endif else begin
  else
%    if iscramb ne 12 and iscramb ne 15 and iscramb ne 16 and iscramb ne 19 $
% 	and iscramb ne 25 and iscramb ne 26 and iscramb ne 36 $
% 	and mvloop(0) ne 6 then begin
   if iscramb ~= 12 && iscramb ~= 15 && iscramb ~= 16 && iscramb ~= 19 ...
    && iscramb ~= 25 && iscramb ~= 26 && iscramb ~= 36 ...
    && mvloop(0) ~= 6
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','!','A','A']
    amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
                '_DELTA_OH','_DELTA_R','A','A','A','!','A','A'});
%    endif
%    if iscramb eq 12 or iscramb eq 15 or iscramb eq 16 or iscramb eq 19 $
% 	or iscramb eq 25 or iscramb eq 26 or iscramb eq 36 $
% 	or mvloop(0) eq 6 then begin
   else
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','_DELTA_R','A','A','A','A','A','A']
    amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
                '_DELTA_OH','_DELTA_R','A','A','A','A','A','A'});
%    endif 
   end
%    endelse
  end
%    endif
 end
%    
% endif
end
% if mvloop(0) eq 8 then begin
if mvloop == 8
%  amat_outputs = amat_outputs+[replicate('_P',16),            $
%             '_DELTA_OH','A','A','A','A','A','A','!']
 amat_outputs = strcat(amat_outputs,{repmat({'_P'},1,16),...
             '_DELTA_OH','_DELTA_R','A','A','A','A','A','!'});
% endif
end
% ;
% if mvloop(0) eq 18 then begin
if mvloop == 18
%  amat_outputs = amat_outputs+[replicate('!',8),replicate('_P',8),     $
%             '_DELTA_OH','A','A','A','A','A','A','!']
 amat_outputs = strcat(amat_outputs,{repmat({'!'},1,8),repmat({'_P'},1,8),...
             '_DELTA_OH','_DELTA_R','A','A','A','A','A','!'});
% endif 
end
% ;
% ; specify whether the references are 'Ip' or '10V' Volts	;!!!!!!
% amat_refs = replicate('10V',24)
amat_refs = repmat('10V',24,1);
% 
% ; specify the desired output scales in MKSA/Volt
% ; ??  out_scales are twice in_scales to give calibration factor of 0.5
% ;
% if mvloop(0) ne 1 and mvloop(0) ne 11 and mvloop(0) ne 21 and mvloop(0) ne 2 $
% 	and mvloop(0) ne 12 and (mvloop(0) mod 10) ne 5 then begin
if mvloop ~= 1 && mvloop ~= 11 && mvloop ~= 21 && mvloop ~= 2 ...
	&& mvloop ~= 12 && rem(mvloop,10) ~= 5
% ; increased amat_out_scale[22] to 1.7e4(1.4e4) to avoid overflows (SC, 23/04/03)
% ; back to 1.4e4 because 1.7e4 produces overflows for z=0 bd (JMM, 06/05/03)
% ; back to 1.7e4 because 1.4e4 produces overflows for z=0 bd (JMM, 09/05/03)
% ; back to 1.4e4 because 1.7e4 produces overflows for z=0 bd (HW, 09/05/03, late shift)
% ; back to 1.7e4 along with change in feed_gains (see below) (SC, 12/05/03)
% ; increased to 1.8e4 to avoid overflows (SC, 14/05/04)
% ;
% ; increased amat_out_scale[21] to 1.2e4(1.0e4) to avoid overflows (SC, 31/03/05)
% ; increased amat_out_scale[21] to 1.3e4(1.2e4) to avoid overflows (SC, 18/05/05)
% ; increased amat_out_scale[21] to 1.4e4(1.3e4) to avoid overflows (SC, 12/12/05)
% amat_out_scale = [				$
%  replicate(2.200e3,16), 7.48e3,			$	; Amp/volt
%  2.2e3, 1.1e5,					$	; Ip
%  2.7e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  1.4e4,						$	; Amp/volt
%  1.8e4, 240.0e4					]	; Amp*m**2/volt
 amat_out_scale = [
  repmat(2.200e3,1,16), 7.48e3,... % Amp/volt
  2.2e3, 1.1e5,... % Ip
  2.7e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  1.4e4,... % Amp/volt
  1.8e4, 240.0e4					]; % Amp*m**2/volt
% endif  
end
% ;
% if mvloop(0) eq 1 or (mvloop(0) mod 10) eq 5 then begin
if mvloop == 1 || rem(mvloop,10) == 5
% ; increased amat_out_scale[22] to 1.7e4(1.4e4) to avoid overflows (SC, 23/04/03)
% ; back to 1.4e4 because 1.7e4 produces overflows for z=0 bd (JMM, 06/05/03)
% ; back to 1.7e4 because 1.4e4 produces overflows for z=0 bd (JMM, 09/05/03)
% amat_out_scale = [				$  
%  7.48e3, replicate(2.200e3,15), 7.48e3,		$	; Amp/volt
%  2.2e3, 1.1e5,					$	; Ip
%  2.7e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  1.0e4,						$	; Amp/volt
%  1.7e4,120.0e4					]	; Amp*m**2/volt
 amat_out_scale = [
  7.48e3, repmat(2.200e3,1,15), 7.48e3,... % Amp/volt
  2.2e3, 1.1e5,... % Ip
  2.7e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  1.0e4,... % Amp/volt
  1.7e4, 120.0e4					]; % Amp*m**2/volt
% endif
end
% ;
% if (mvloop(0) mod 10) eq 5 then begin
if rem(mvloop,10) == 5
%  if mvloop(0) le 100 then begin
 if mvloop < 100
%    amat_out_scale(18)=1.1e5/1.5;
  amat_out_scale(19) = 1.1e5/1.5;
%  endif else begin
 else
%    amat_out_scale(3)=1.1e5/3;
  amat_out_scale(4) = 1.1e5/3;
%  endelse
 end
% endif
end
% if mvloop(0) eq 6 then begin
if mvloop == 6
%    amat_out_scale(21)=1.4e4;
 amat_out_scale(22) = 1.4e4;
%    amat_out_scale(0)=1.4e4;
 amat_out_scale(1) = 1.4e4;
% endif
end
% ;
% ; Vloop feedback option added (SC, 23/09/03)
% if mvloop(0) eq 11 then begin
if mvloop == 1
% amat_out_scale = [				$  
%  10., replicate(2.200e3,15), 7.48e3,		$	; Amp/volt
%  2.2e3, 1.1e5,					$	; Ip
%  2.7e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  1.0e4,						$	; Amp/volt
%  1.7e4,120.0e4					]	; Amp*m**2/volt
 amat_out_scale = [
  10., repmat(2.200e3,1,15), 7.48e3,... % Amp/volt
  2.2e3, 1.1e5,... % Ip
  2.7e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  1.0e4,... % Amp/volt
  1.7e4, 120.0e4					]; % Amp*m**2/volt
% endif
end
% if mvloop(0) eq 21 then begin
if mvloop == 21
% amat_out_scale = [				$  
%  1., replicate(2.200e3,15), 7.48e3,		$	; Amp/volt
%  2.2e3, 1.1e5,					$	; Ip
%  2.7e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  1.0e4,						$	; Amp/volt
%  1.7e4,120.0e4					]	; Amp*m**2/volt
 amat_out_scale = [
  1., repmat(2.200e3,1,15), 7.48e3,... % Amp/volt
  2.2e3, 1.1e5,... % Ip
  2.7e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  1.0e4,... % Amp/volt
  1.7e4, 120.0e4					]; % Amp*m**2/volt
% endif
end
% ;
% ; Two-component IOH feedback (SC, 06/04/05)
% if mvloop(0) eq 2 or mvloop(0) eq 12 then begin
if mvloop == 2 || mvloop == 12
% ; set amat_out_scale[1] based on actual max current required, to maximize
% ;   resolution (0.85 V -> 8.5 V at G2 input)
% amatout2 = max(abs(ioh1values))/.85;
 amatout2 = max(abs(ioh1values))/.85;
% amat_out_scale = [				$  
%  7.48e3,amatout2, replicate(2.200e3,14), 7.48e3,$	; Amp/volt
%  2.2e3, 1.1e5,					$	; Ip
%  2.7e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  1.0e4,						$	; Amp/volt
%  1.7e4,120.0e4					]	; Amp*m**2/volt
 amat_out_scale = [
  7.48e3,amatout2, repmat(2.200e3,1,14), 7.48e3,... % Amp/volt
  2.2e3, 1.1e5,... % Ip
  2.7e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  1.0e4,... % Amp/volt
  1.7e4, 120.0e4					]; % Amp*m**2/volt
% endif
end
% ;
% ; inova=4 option added (SC, 25/04/05)
% if inova eq 4 then amat_out_scale(2) = 1.7e4		; 
if inova == 4, amat_out_scale(3) = 1.7e4		; end
% ;
% if midplan eq 8 then begin
if midplan == 8
% amat_out_scale = [				$
%  replicate(2.200e3,16), 7.48e3,			$	; Amp/volt
%  1.2e3, 1.0e5,					$	; Ip
%  8.0e3,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  8.0e3,						$	; Amp/volt
%  1.200e3, 2.2e5					]	; Amp*m**2/volt
 amat_out_scale = [
  repmat(2.200e3,1,16), 7.48e3,... % Amp/volt
  1.2e3, 1.0e5,... % Ip
  8.0e3,... % Amp*meter/volt
  4.0,... % Fringes/volt
  8.0e3,... % Amp/volt
  1.200e3, 2.2e5					]; % Amp*m**2/volt
% endif
end
% if midplan eq 9 then begin
if midplan == 9
% amat_out_scale = [				$
%  replicate(2.200e3,16), 7.48e3,			$	; Amp/volt
%  2.2e3, 1.0e5,					$	; Ip
%  2.3e4,						$	; Amp*meter/volt
%  4.0,						$	; Fringes/volt
%  2.2e3,						$	; Amp/volt
%  2.200e3, 2.2e3					]	; Amp*m**2/volt
 amat_out_scale = [
  repmat(2.200e3,1,16), 7.48e3,... % Amp/volt
  2.2e3, 1.0e5,... % Ip
  2.3e4,... % Amp*meter/volt
  4.0,... % Fringes/volt
  2.2e3,... % Amp/volt
  2.200e3, 2.2e3					]; % Amp*m**2/volt
% endif
end
% 
% if iscramb eq 0 then amat_out_scale(17)=7.48e3
if iscramb == 9, amat_out_scale(18) = 7.48e3; end
% 
% a_out_scale = amat_out_scale
% % a_out_scale = amat_out_scale;
% 
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Prepare the A Matrix                               ;
% amat= fltarr(n_elements(amat_outputs),n_elements(amat_inputs),1);
% % amat = zeros(length(amat_outputs),length(amat_inputs),1);
% ; ########## Prepare the A Matrix observer outputs in turn      ;
% ;----------------------------------------------------------------
% 
% ;prepare transformation to virtual flux/voltages
% ;
% ;construct complete transformation matrix
% tf=fltarr(120,120)
tf = zeros(120,120);
% tf(0,0)=tfr
tf(1:size(tfr,1),1:size(tfr,2)) = tfr;
% for i=38,119 do tf(i,i)=1.0
for i = 39:120, tf(i,i) = 1.0; end
% ;
% ;calculate the modified a matrix and convert from 3D to 2D
% a=aaasw(*,*,0)#tf
a = aaasw(:,:,1)*tf;
% g1=g1sw
g1 = g1sw;
% g2=g2sw
g2 = g2sw;
% g3=g3sw
g3 = g3sw;
% aml=amlsw(*,*,0)
aml = amlsw(:,:,1);
% ioh=-1500.
ioh = -1500;
% ioh1=0.
ioh1 = 0;
% if midplan ne 8 then begin
if midplan ~= 8
%  if mvloop(0) ne 1 and mvloop(0) ne 11 and mvloop(0) ne 21 and mvloop(0) ne 2 $
% 	and mvloop(0) ne 12 and (mvloop(0) mod 10) ne 5 then begin
 if mvloop ~= 1 && mvloop ~= 11 && mvloop ~= 21 && mvloop ~= 2 ...
	 && mvloop ~= 12 && rem(mvloop,10) ~= 5
%   if iscramb ne 12 and iscramb ne 15 and iscramb ne 16 and iscramb ne 19 $
% 	and iscramb ne 25 and iscramb ne 26 and iscramb ne 36 $
% 	and mvloop(0) ne 6 then begin
  if iscramb ~= 12 && iscramb ~= 15 && iscramb ~= 16 && iscramb ~= 19 ...
	  && iscramb ~= 25 && iscramb ~= 26 && iscramb ~= 36 ...
	  && mvloop ~= 6
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,3,0],[-0.3,0.01,0.07,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,3,0],[-0.3,0.01,0.07,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8])
%   endif else begin
  else
%   ton=0.3
   ton = 0.3;
%   toff=2.45
   toff = 2.45;
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0,0,0],[-0.3,0.01,0.07,ton,toff,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0,0,0],[-0.3,0.01,0.07,ton,toff,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,4,2,3,2],[-0.3,0.01,0.07,ton,toff,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,4,2,3,2],[-0.3,0.01,0.07,ton,toff,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0,0,0],[-0.3,0.01,0.07,ton,toff,2.7,2.8]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0,0,0],[-0.3,0.01,0.07,ton,toff,2.7,2.8])
%   endelse
  end
%  endif
% ;
%  if mvloop(0) eq 1 or mvloop(0) eq 11 or mvloop(0) eq 21 or mvloop(0) eq 2 or $
% 	mvloop(0) eq 12 or (mvloop(0) mod 10) eq 5 then begin
 else
%   ton=0.4
  ton = 0.4;
%   toff=2.5
  toff = 2.5;
%   if iscramb ne 12 and iscramb ne 15 and iscramb ne 16 and iscramb ne 19 $
% 	and iscramb ne 25 and iscramb ne 26 and iscramb ne 36 then begin
  if iscramb ~= 12 && iscramb ~= 15 && iscramb ~= 16 && iscramb ~= 19 ...
   && iscramb ~= 25 && iscramb ~= 26 && iscramb ~= 36
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,3,2],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,3,2],[-0.3,0.01,0.07,ton,toff])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff])
%   endif else begin
  else
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,4,2],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,1,2,4,2],[-0.3,0.01,0.07,ton,toff])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff]
   wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,ton,toff])
%   endelse
  end
% ;
%  endif
 end
% endif
end
% if midplan eq 8 then begin
if midplan == 8
% wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0],[-0.3,0.01,2.00,2.1]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0],[-0.3,0.01,2.00,2.1])
% wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,2,3,0],[-0.3,0.01,2.00,2.1]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,2,3,0],[-0.3,0.01,2.00,2.1])
% wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0],[-0.3,0.01,2.00,2.1]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0],[-0.3,0.01,2.00,2.1])
% endif  
end
% if iscramb eq 0 then begin
if iscramb == 0
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:A',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:G',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:G',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8])
%   wave_put,'\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8]
 wave_put('\PCS::PHYS_MAT_ADDRESSES:M',[0,0,0,0,0],[-0.3,0.01,0.07,2.7,2.8])
% endif
end
% 
% ; #################################################### GAINS		;!!!!!!
% 
% ; increased feed_gains[22] to 2(1) to avoid overflows (SC, 12/05/03)
% ; increased feed_gains[21] to 2(1) to avoid overflows (SC, 29/09/04)
% ; increased feed_gains[22] to 4(2) to avoid overflows (SC, 30/10/09)
% feed_gains=[1,1,1,1,1,1,1,1,4,4,4,4,4,4,4,4,1,1,1,1,1,4,4,8]
feed_gains = [1,1,1,1,1,1,1,1,4,4,4,4,4,4,4,4,1,1,1,1,1,4,4,8];
% if mvloop(0) eq 11 then feed_gains(0) = 8
if mvloop == 11, feed_gains(1) = 8; end
% if (mvloop(0) mod 10) eq 5 then begin
if rem(mvloop,10) == 5
%   feed_gains(18) = 8
 feed_gains(19) = 8;
%   if mvloop(0) gt 100 then feed_gains(3)=8
 if mvloop > 100, feed_gains(4) = 8; end
% endif
end
% if mvloop(0) eq 6 then feed_gains(0) = 8
if mvloop == 6, feed_gains(1) = 8; end
% 
% ; inova=4 option added (SC, 25/04/05)
% if inova eq 4 then feed_gains(2) = 2		; 
if inova == 4, feed_gains(3) = 2; end
% 
% amat=a
amat = a;
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Put the A-Matrix to the tree, Prepare the refs     ;
% mat_put,'A',amat,amat_inputs,amat_outputs,amat_out_scale        ;
mat_put('A',amat,amat_inputs,amat_outputs,amat_out_scale)
% gmat_inputs = amat_outputs                                      ;
gmat_inputs = amat_outputs;
% set_gains,feed_gains                                            ;
set_gains(feed_gains)
% setup_refs,amat_out_scale,amat_outputs,amat_refs                ;
setup_refs(amat_out_scale,amat_outputs,amat_refs)
% for i=0,n_elements(amat_outputs)-1 do  $                        ;
%         print,amat_outputs(i),amat_refs(i),amat_out_scale(i),$  ;
%         format='(a15,a10,1e12.3)'                               ;
% ; The G-matrices are defined so that output = - G1 * error      ;
% ; ########## Create the G1..3 Matrices variable lists           ;
% ;----------------------------------------------------------------
% 
% ; specify the G Matrix outputs						;!!!!!!!
% gmat_outputs = 'GO'+iii(indgen(22)+1)
gmat_outputs = strcat('GO',iii(1:22));
% 
% ; specify the desired G Matrix output sensitivities
% ; the factor 50, below, divided by the factor 100, which is hard-wired
% ; into mat_do, gives a G matrix calibration of 0.500
% ; If the full_scale of G is changed from 0.5 to 2.0, and the factor 100
% ; in mat_do is changed according to the variable gain setting,the factor
% ; 50 must be adapted!
% ; MAT_OUT_SCALE=MAT_OUT_SCALE/50
%  if nfast eq -5 then begin
if nfast == -5
%  gmat_out_scale = [				$
%  replicate(4.400e1,16), 14.96e1, 14.96e1,	$	; Amp/volt
%  2.0e3,						$	; Ip
%  2.4e2,						$	; Amp*meter/volt
%  0.15,						$	; Fringes/volt
%  88.						]	; Amp/volt
 gmat_out_scale = [				...
 repmat(4.400e1,1,16), 14.96e1, 14.96e1,	...	% Amp/volt
 2.0e3,						...	% Ip
 2.4e2,						...	% Amp*meter/volt
 0.15,						...	% Fringes/volt
 88.						]	; % Amp/volt
%  endif
%  if nfast ne -5 then begin
else
%  gmat_out_scale = [				$
%  replicate(4.400e1,16), 14.96e1, 14.96e1,	$	; Amp/volt
%  2.0e3,						$	; Ip
%  2.4e2,						$	; Amp*meter/volt
%  0.15,						$	; Fringes/volt
%  66.						]	; Amp/volt
 gmat_out_scale = [				...
 repmat(4.400e1,1,16), 14.96e1, 14.96e1,	...	% Amp/volt
 2.0e3,						...	% Ip
 2.4e2,						...	% Amp*meter/volt
 0.15,						...	% Fringes/volt
 66.						]	; % Amp/volt
%  endif 
end
% if (mvloop(0) mod 10) eq 5 then begin
if rem(mvloop,10) == 5
%   gmat_out_scale(0) = 1.e4 ; RHVPS volts/volt
 gmat_out_scale(1) = 1.e4; % RHVPS volts/volt
%   if (mvloop(0) mod 100) eq 25 then gmat_out_scale(1) = 1.e4 ; RHVPS volts/volt
 if rem(mvloop,100) == 25, gmat_out_scale(2) = 1.e4; end % RHVPS volts/volt
% endif
end
% UNTRANSLATED
% if mvloop(0) eq 6 then begin
if mvloop == 6, error('UNSTRANLATED'), end
% ; RHVPS volt/volt or mirror angle/volt
%   for imv=0,1 do begin
%     if mvloop(imv+1) ne 0 then begin
%       if (mvloop(imv+1) mod 10) lt 3 then gmat_out_scale(imv) = 1.e4 else $
% 		       gmat_out_scale(imv) = -2.85
%     endif
%   endfor
%   for imv=2,6 do begin
%     if mvloop(imv+1) ne 0 then begin
%       if (mvloop(imv+1) mod 10) lt 3 then gmat_out_scale(imv+1) = 1.e4 else $
% 		       gmat_out_scale(imv+1) = -2.85
%     endif
%   endfor
% endif
% END UNTRANSLATED
% ; ########## Specify the time constants in the feedback (unused) ;!!!!!!!
% tauint=0
tauint = 0;
% tauprop=0
tauprop = 0;
% taudiff=0
taudiff = 0;
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Prepare the G1 Matrix                              ;
% g1mat=fltarr(n_elements(gmat_outputs),n_elements(gmat_inputs),1);
% % g1mat = zeros(length(gmat_outputs),length(gmat_inputs),1);
% mds$put,'\PCS::LOAD_TAU:D','$',taudiff                          ;
mdsput('\PCS::LOAD_TAU:D',mdscvt(taudiff,'f'))
% mds$put,'\PCS::LOAD_TAU:I','$',tauint                           ;
mdsput('\PCS::LOAD_TAU:I',mdscvt(tauint,'f'))
% mds$put,'\PCS::LOAD_TAU:P','$',tauprop                          ;
mdsput('\PCS::LOAD_TAU:P',mdscvt(tauprop,'f'))
% ; ########## Define the G1 outputs in turn      Integral        ;
% ;----------------------------------------------------------------
% 
% ; extract G1 
% g1mat=g1
g1mat = g1;
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Put the G1 Matrix, Prepare the G2 Matrix           ;
% mat_put,'G1',g1mat,gmat_inputs,gmat_outputs,gmat_out_scale      ;
mat_put('G1',g1mat,gmat_inputs,gmat_outputs,gmat_out_scale)
% g2mat=fltarr(n_elements(gmat_outputs),n_elements(gmat_inputs),1);
% % g2mat = zeros(length(gmat_outputs),length(gmat_inputs),1);
% ; ########## Define the G2 outputs in turn      Proportional    ;
% ;----------------------------------------------------------------
% ; extract G2
% g2mat=g2
g2mat = g2;
% 
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Put the G2 Matrix, Prepare the G3 Matrix           ;
% mat_put,'G2',g2mat,gmat_inputs,gmat_outputs,gmat_out_scale      ;
mat_put('G2',g2mat,gmat_inputs,gmat_outputs,gmat_out_scale)
% g3mat=fltarr(n_elements(gmat_outputs),n_elements(gmat_inputs),1);
% % g3mat = zeros(length(gmat_outputs),length(gmat_inputs),1);
% ; ########## Define the G3 outputs in turn      Derivative      ;
% ;----------------------------------------------------------------
% 
% ; extract G3
% g3mat=g3
g3mat = g3;
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Put the G3 Matrix                                  ;
% mat_put,'G3',g3mat,gmat_inputs,gmat_outputs,gmat_out_scale      ;
mat_put('G3',g3mat,gmat_inputs,gmat_outputs,gmat_out_scale)
% ; ########## Define the M-Matrix                                ;
% ;----------------------------------------------------------------
% 
% ; we use all inputs, by default
% 
% mmat_inputs = [	 gmat_outputs, $
%                  'CTLAMP:IPOL_E_' +iii(indgen(8)+1), $
%                  'CTLAMP:IPOL_F_' +iii(indgen(8)+1), $
%                  'CTLAMP:IPOL_OH_'+iii(indgen(2)+1) ]
mmat_inputs = [	 gmat_outputs, ...
                 {strcat('CTLAMP:IPOL_E_',iii(1:8)), ...
                 strcat('CTLAMP:IPOL_F_',iii(1:8)), ...
                 strcat('CTLAMP:IPOL_OH_',iii([1 2]))}];
% 
% mmat_outputs=['E_001','E_002','E_003','E_004','E_005','E_006','E_007','E_008', $
%               'F_001','F_002','F_003','F_004','F_005','F_006','F_007','F_008', $
%               'OH_001','OH_002','GAS','FAST']
mmat_outputs = {'E_001','E_002','E_003','E_004','E_005','E_006','E_007','E_008', ...
                'F_001','F_002','F_003','F_004','F_005','F_006','F_007','F_008', ...
                'OH_001','OH_002','GAS','FAST'};
% 
% if (mvloop(0) mod 100) eq 5 or (mvloop(0) mod 100) eq 25 then $
if rem(mvloop,100) == 5 || rem(mvloop,100) == 25
% 	mmat_outputs(0)='RHVPSA'
	mmat_outputs(1) = 'RHVPSA';
end
% if (mvloop(0) mod 100) eq 15 then $
if rem(mvloop,100) == 15
% 	mmat_outputs(0)='RHVPSB'
	mmat_outputs(1) = 'RHVPSB';
end
% if (mvloop(0) mod 100) eq 25 then $
if rem(mvloop,100) == 25
% 	mmat_outputs(1)='RHVPSB'
	mmat_outputs(2) = 'RHVPSB';
end
% UNTRANSLATED
% if mvloop(0) eq 6 then begin
if mvloop == 6, error('UNSTRANLATED'), end
%   for imv=0,6 do begin
%     if imv lt 2 then icor=0 else icor=1
%     if mvloop(imv+1) ne 0 then begin
%       if (mvloop(imv+1) mod 10) eq 1 then mmat_outputs(imv+icor)='RHVPSA'
%       if (mvloop(imv+1) mod 10) eq 2 then mmat_outputs(imv+icor)='RHVPSB'
%       if (mvloop(imv+1) mod 10) eq 3 then mmat_outputs(imv+icor)='MIRROR1'
%       if (mvloop(imv+1) mod 10) eq 4 then mmat_outputs(imv+icor)='MIRROR2'
%       if (mvloop(imv+1) mod 10) eq 5 then mmat_outputs(imv+icor)='MIRROR3'
%       if (mvloop(imv+1) mod 10) eq 6 then mmat_outputs(imv+icor)='MIRROR4'
%       if (mvloop(imv+1) mod 10) eq 7 then mmat_outputs(imv+icor)='MIRROR5'
%       if (mvloop(imv+1) mod 10) eq 8 then mmat_outputs(imv+icor)='MIRROR6'
%     endif
%   endfor
% endif
% END UNTRANSLATED
% 
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Prepare the M Matrix                               ;
% mmat=fltarr(n_elements(mmat_outputs),n_elements(mmat_inputs),1) ;
% % mmat = zeros(length(mmat_outputs),length(mmat_inputs),1);
% ; mat_out_scale is defined by the hardware, and is in MAT_DO    ;
% mmat_out_scale = fltarr(n_elements(mmat_outputs))               ;
mmat_out_scale = zeros(length(mmat_outputs));
% ; ########## Fill the M Matrix                                  ;
% ;----------------------------------------------------------------
% 
% ; extract AML- matrix
% 
% ; set up the alim mode + set all of the NECESSARY alims on
% if (mvloop(0) ne 1 and mvloop(0) ne 11 and mvloop(0) ne 21 and mvloop(0) ne 2 $
% 	and mvloop(0) ne 12 and (mvloop(0) mod 10) ne 5 ) or iscramb eq 0 $
% 	then begin
if mvloop ~= 1 && mvloop ~= 11 && mvloop ~= 21 && mvloop ~= 2 ...
 && mvloop ~= 12 && rem(mvloop,10) ~= 5 || iscramb == 0
% if nfast eq 0 then request_modes=[replicate('B',19),'A']
 if nfast == 0, request_modes = {repmat('B',1,19),'A'}; end
% if nfast ne 0 then request_modes=[replicate('B',19),'B']
 if nfast ~= 0, request_modes = {repmat('B',1,19),'B'}; end
% endif
% ;
% if (mvloop(0) eq 1 or mvloop(0) eq 11 or mvloop(0) eq 21 $
% 	or (mvloop(0) mod 10) eq 5) and iscramb ne 0 then begin
else
% if nfast eq 0 then request_modes=['C',replicate('B',18),'A']
 if nfast == 0, request_modes = {'C',repmat('B',1,18),'A'}; end
% if nfast ne 0 then request_modes=['C',replicate('B',18),'B']
 if nfast ~= 0, request_modes = {'C',repmat('B',1,18),'B'}; end
% endif
end
% ;
% if (mvloop(0) mod 100) eq 25 and iscramb ne 0 then begin
if rem(mvloop,100) == 25 && iscramb ~= 0
% if nfast eq 0 then request_modes=['C','C',replicate('B',17),'A']
 if nfast == 0, request_modes = {'C','C',repmat('B',1,17),'A'}; end
% if nfast ne 0 then request_modes=['C','C',replicate('B',17),'B']
 if nfast ~= 0, request_modes = {'C','C',repmat('B',1,17),'B'}; end
% endif
end
% ;
% ; Two-component IOH feedback (SC, 06/04/05)
% if (mvloop(0) eq 2 or mvloop(0) eq 12) and iscramb ne 0 then begin
if mvloop == 2 || mvloop == 12 && iscramb ~= 0
% if nfast eq 0 then request_modes=['C','C',replicate('B',17),'A']
 if nfast == 0, request_modes = {'C','C',repmat('B',1,17),'A'}; end
% if nfast ne 0 then request_modes=['C','C',replicate('B',17),'B']
 if nfast ~= 0, request_modes = {'C','C',repmat('B',1,17),'B'}; end
% endif
end
% ; inova=4 option added (SC, 25/04/05)
% if inova eq 4 and iscramb ne 0 then request_modes(2) = 'C'		; 
if inova == 4 && iscramb ~= 0, request_modes(3) = 'C'; end
% ;
% if (mvloop(0) mod 10) eq 5 and mvloop(0) gt 100 and iscramb ne 0 $
% 	then request_modes(3) = 'C'
if rem(mvloop,10) == 5 && mvloop > 100 && iscramb ~= 0,
	request_modes(4) = 'C';
end
% ;
% UNTRANSLATED
% if mvloop(0) eq 6 then begin
if mvloop == 6, error('UNSTRANLATED'), end
%   for imv=0,6 do begin
%     if imv lt 2 then icor=0 else icor=1
%     if mvloop(imv+1) ne 0 then request_modes(imv+icor) = 'C'
%   endfor
% endif
% END UNTRANSLATED
% ;
% if mvloop(0) eq 18 and iscramb ne 0 then begin
if mvloop == 18 && iscramb ~= 0
% request_modes=[replicate('C',8),replicate('B',11),'A']
 request_modes = {repmat('C',1,8),repmat('B',1,11),'A'};
% endif
end
% ;  
% request_select = [replicate('ON',8),replicate('ON',8),replicate('ON',4)]
request_select = {repmat('ON',1,8),repmat('ON',1,8),repmat('ON',1,4)};
% ;
% ;-----------automatic level setting-----------------------
% ;
% request_levels = [replicate('50',18),'100','75']
request_levels = {repmat('50',1,18),'100','75'};
% lim80  = 0.75*3850.
lim80 = 0.75*3850.;
% lim100 = 0.75*5544.
lim100 = 0.75*5544.;
% oh80   = 27000.*0.5
oh80   = 27000*0.5;
% oh100  = 27000.*0.8
oh100  = 27000*0.8;
% for i=0,15 do if max(abs(efcur(*,i))) gt lim80  then request_levels(i)='80'
for i = 1:16, if max(abs(efcur(:,i))) > lim80, request_levels(i) = '80'; end, end
% for i=0,15 do if max(abs(efcur(*,i))) gt lim100 then request_levels(i)='100'
for i = 1:16, if max(abs(efcur(:,i))) > lim100, request_levels(i) = '100'; end, end
% if max(abs(efcur(*,16))) gt oh80  then request_levels(16)='80'
if max(abs(efcur(:,17))) > oh80, request_levels(17) = '80'; end
% if max(abs(efcur(*,16))) gt oh100 then request_levels(16)='100'
if max(abs(efcur(:,17))) > oh100, request_levels(17) = '100'; end
% if max(abs(efcur(*,16))) gt oh80  then request_levels(17)='80'
if max(abs(efcur(:,17))) > oh80, request_levels(18) = '80'; end
% if max(abs(efcur(*,16))) gt oh100 then request_levels(17)='100'
if max(abs(efcur(:,17))) > oh100, request_levels(18) = '100'; end
% ;
% ;if midplan eq 3 then begin
% ;  request_levels = ['80','50','100','80',replicate('100',4),     $
% ;	    '50','50','80',replicate('50',5),replicate('100',3),'50']
% ;endif
% ;
% ;if midplan eq 37 then begin
% ;  request_levels = ['80','50','80','100','50','100','50','50',  $
% ;		    replicate('50',8),replicate('100',3),'50']
% ;endif 
% ; 
% ;if midplan eq 1 then begin
% ;  request_levels = [replicate('80',2),replicate('100',4),replicate('80',2),  $
% ;		     replicate('50',3),replicate('80',2), replicate('50',3),  $
% ;                    replicate('100',3),'75']
% ;endif
% ;
% ;if midplan eq 8 then begin
% ;  request_levels = [replicate('80',3),replicate('100',2),replicate('50',3),  $
% ;                    replicate('50',3),replicate('100',2),replicate('50',3),  $
% ;                    replicate('100',3),'0']
% ;endif
% ; 
% ;if midplan eq 9 then begin
% ;  request_levels = [replicate('50',3),replicate('80',2),replicate('50',3),  $
% ;                    replicate('50',3),replicate('80',2),replicate('50',3),  $
% ;                    replicate('100',3),'0']
% ;endif 
% 
% ; set up 19 alims only
% ;;;request_levels = request_levels(0:18)
% ;;;request_select = request_select(0:18)
% 
%  mmat=aml
mmat = aml;
% ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
% ; ########## Put the M-Matrix to the tree                       ;
% mat_put,'M',mmat,mmat_inputs,mmat_outputs,mmat_out_scale        ;
mat_put('M',mmat,mmat_inputs,mmat_outputs,mmat_out_scale)
% ; ########## Load the matrices into hardware units              ;
% mat_do,index,pcs_path                                           ;
mat_do(index,pcs_path)
% ; ########## Check on the matrix statistics for the model       ;
% mat_overflow,-1                                                 ;
mat_overflow(-1)
% ;----------------------------------------------------------------
% 
% ; added 3-way switch set-up (SC, 05/05/09)
% switch_status=mds$value('jp_set_sum_sys("'+pcs_path+'")')
switch_status=mdsdata(['jp_set_sum_sys("' pcs_path '")']);
% if (switch_status ne 1) then begin
if switch_status ~= 1
%   print,'THREE-WAY SWITCH SET-UP FAILED'
%   return
  error('THREE-WAY SWITCH SET-UP FAILED')
% endif
end
% 
% ; read currents from file if iscramb=0 and inova=5
% if iscramb eq 0 and inova eq 5 then begin
if iscramb == 0 && inova == 5
 error('UNTRANSLATED')
% UNTRANSLATED
%  openr,unit,'MAC:[PIRAS]TCV_CURRENT_TRACES.DAT',/get_lun
%  readf,unit,nohtf
%  noht=floor(nohtf)
%  toh=fltarr(noht)
%  efcur=fltarr(noht,17)
%  readf,unit,toh
%  readf,unit,efcur
%  free_lun,unit
% END UNTRANSLATED
% endif
end
% ; ########################################### times for the bit set
% 
% UNTRANSLATED
% if iscramb eq 0 and inova eq 5 then begin
%   init_time = [-36.,-30.,-24.]*1.e-3 + min(toh) 
% endif else begin
% END UNTRANSLATED
%   init_time = [-36.,-30.,-24.]*1.e-3 + min(toft) 
  init_time = [-36.,-30.,-24.]*1.e-3 + min(toft) ;
% UNTRANSLATED
% endelse
% END UNTRANSLATED
% init_val  = [0.,1000.,0.]
init_val  = [0.,1000.,0.];
% 
% if (pcs_path eq 'rtdtacq') then begin
if strcmp(pcs_path,'rtdtacq')
% ; adjust the Wavegen masks for real-time
%   wave_mask=[0.,0.,0.,1.,replicate(1.,12),replicate(0.,16), $
% 	     replicate(1.,16),replicate(0.,16), $
% 	     replicate(1.,64)]
  wave_mask=[0.,0.,0.,1.,ones(1,12),zeros(1,16), ...
	     ones(1,16),zeros(1,16), ...
	     ones(1,64)];
%   mds$put,'\load_wave_mask','$',wave_mask
  mdsput('\LOAD_WAVE_MASK',mdscvt(wave_mask,'l'))
% endif
end
% if (pcs_path eq 'rtdtacqden') then begin
if strcmp(pcs_path,'rtdtacqden')
% ; adjust the Wavegen masks for real-time
%   wave_mask=[1.,1.,0.,replicate(1.,125)]
  wave_mask=[1.,1.,0.,ones(1,125)];
%   mds$put,'\load_wave_mask','$',wave_mask
  mdsput('\LOAD_WAVE_MASK',mdscvt(wave_mask,'f'))
% endif
end
% 
% ; ##############################   Load the first waveforms
% 
% ; Put all current references to zero to start with
% vbit=[0.0,0.0]
vbit=[0.0,0.0];
% UNTRANSLATED
% if iscramb eq 0 and inova eq 5 then begin
%   tbit=[min(toh),max(toh)]
% endif else begin
% END UNTRANSLATED
%   tbit=[min([toft,toh]),max([toft,toh])]
  tbit=[min([toft,toh]),max([toft,toh])];
% UNTRANSLATED
% endelse
% END UNTRANSLATED
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_004',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_005',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_006',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_007',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_008',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_001',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_002',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_003',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_004',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_005',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_006',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_007',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_008',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_001',vbit,tbit
% wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_002',vbit,tbit
for n = mdsdata('GETNCI("\\PCS::DRAW_FEEDFOR_" // ["E_I:ALIM*","F_I:ALIM*","OH_I:ALIM*"],"PATH")')
 wave_put(n,vbit,tbit)
end
% 
% 
% signbit = intarr(18)
signbit = zeros(18,1);
% 
% ; load OH1 and OH2
% bit_set = aipoft(13)/abs(aipoft(13))
bit_set = aipoft(13)/abs(aipoft(13));
% UNTRANSLATED
% if iscramb eq 0 and inova eq 5 then begin
%   fbte1,toh,efcur(*,16),tbit,vbit
%   wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_001',vbit,tbit
%   wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_002',vbit,tbit
% endif else begin
% END UNTRANSLATED
%   wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_001',			$
%   	[0.8*init_val*bit_set, 0, -0.8*init_val*bit_set, 0],	$
%         [init_time, min(toft), init_time+0.500, toh(n_elements(toh)-1)]
% ;        [0.8*init_val*bit_set, 0],                           $
% ;        [init_time, min(toft)]
%   wave_put,'\PCS::DRAW_FEEDFOR_OH_I:ALIM_002',			$
% 	[0.8*init_val*bit_set, 0, -0.8*init_val*bit_set, 0],	$
%         [init_time,min(toft), init_time+0.500, toh(n_elements(toh)-1)]
% ;        [0.8*init_val*bit_set, 0],                           $
% ;        [init_time, min(toft)]
for n = mdsdata('GETNCI("\\PCS::DRAW_FEEDFOR_OH_I:ALIM*","PATH")')
  wave_put(n,			...
  	[0.8*init_val*bit_set, 0, -0.8*init_val*bit_set, 0],...
        [init_time, min(toft), init_time+0.500, toh(length(toh))]);
end
% UNTRANSLATED
% endelse
% END UNTRANSLATED
% ;  Initial coil current sign when operating in automatic sign switching mode
% ;    (SC, 05/09/05)
% signbit(16)=init_val(1)*bit_set/abs(init_val(1)*bit_set)
% signbit(17)=init_val(1)*bit_set/abs(init_val(1)*bit_set)
signbit([17 18])=init_val(2)*bit_set/abs(init_val(2)*bit_set);
% 
% 
% ; #######################################  get the E,F requirements
% 
% ; E
% ;
% if (mvloop(0) ne 1 and mvloop(0) ne 11 and mvloop(0) ne 21 and mvloop(0) ne 18 and $
%    mvloop(0) ne 2 and mvloop(0) ne 12 and (mvloop(0) mod 10) ne 5) $
% 	or iscramb eq 0  then begin
if mvloop ~= 1 && mvloop ~= 11 && mvloop ~= 21 && mvloop ~= 18 && ...
   mvloop ~= 2 && mvloop ~= 12 && rem(mvloop,10) ~= 5 ...
	|| iscramb == 0
% fbte1,toh,efcur(*,0),tbit,vbit
[tbit,vbit] = fbte1(toh,efcur(:,1));
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',vbit,tbit
wave_put('\PCS::DRAW_FEEDFOR_E_I:ALIM_001',vbit,tbit)
% endif
end
% ;
% if (mvloop(0) ne 2 and mvloop(0) ne 12 and mvloop(0) ne 25) or iscramb eq 0 $
% 	then begin
if mvloop ~= 2 && mvloop ~= 12 && mvloop ~= 25 || iscramb == 0
% fbte1,toh,efcur(*,1),tbit,vbit
[tbit,vbit] = fbte1(toh,efcur(:,2));
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',vbit,tbit
wave_put('\PCS::DRAW_FEEDFOR_E_I:ALIM_002',vbit,tbit)
% endif
end
% ; inova=4 option added (SC, 25/04/05)
% if inova ne 4 or iscramb eq 0 then begin
if inova ~= 4 || iscramb == 0
% fbte1,toh,efcur(*,2),tbit,vbit
[tbit,vbit] = fbte1(toh,efcur(:,3));
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',vbit,tbit
wave_put('\PCS::DRAW_FEEDFOR_E_I:ALIM_003',vbit,tbit)
% endif
end
% ;
% if (mvloop(0) mod 10) ne 5 or mvloop(0) le 100 or iscramb eq 0 then begin
if rem(mvloop,10) ~= 5 || mvloop <= 100 || iscramb == 0
% fbte1,toh,efcur(*,3),tbit,vbit
[tbit,vbit] = fbte1(toh,efcur(:,4));
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_004',vbit,tbit
wave_put('\PCS::DRAW_FEEDFOR_E_I:ALIM_004',vbit,tbit)
% endif
end
% ;
% if iscramb ne 0 then begin
if iscramb ~= 0
% if mvloop(0) eq 1 or mvloop(0) eq 11 or mvloop(0) eq 21 or mvloop(0) eq 2 or $
% 	mvloop(0) eq 12 or (mvloop(0) mod 10) eq 5 then begin
if mvloop == 1 || mvloop == 11 || mvloop == 21 || mvloop ==  2 || ...
	mvloop == 12 || rem(mvloop,10) == 5
% efcur(1,0) = 50.
% efcur(2,0) = 100.
% efcur(3,0) = 150.
% efcur(4,0) = 200.
% efcur(5,0) = 150.
% efcur(6,0) = 100.
% efcur(7,0) = 50.
efcur(2:8,1) = [50 100 150 200 150 100 50];
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',efcur(*,0),toh)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',efcur(:,1),toh);
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',efcur(*,0),toh
% endif
end
% ;
% ; Two-component IOH feedback (SC, 06/04/05)
% ; or double-RHVPS ECRH feedback (SC, 11/01/07)
% if mvloop(0) eq 2 or mvloop(0) eq 12 or (mvloop(0) mod 100) eq 25 then begin
if mvloop == 2 || mvloop == 12 || rem(mvloop,100) == 25
% efcur(1,1) = 50.
% efcur(2,1) = 100.
% efcur(3,1) = 150.
% efcur(4,1) = 200.
% efcur(5,1) = 150.
% efcur(6,1) = 100.
% efcur(7,1) = 50.
efcur(2:8,2) = [50 100 150 200 150 100 50];
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',efcur(*,1),toh)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',efcur(:,2),toh);
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',efcur(*,1),toh
% endif
end
% ; inova=4 option added (SC, 25/04/05)
% if inova eq 4 then begin
if inova == 4
% efcur(1,2) = 50.
% efcur(2,2) = 100.
% efcur(3,2) = 150.
% efcur(4,2) = 200.
% efcur(5,2) = 150.
% efcur(6,2) = 100.
% efcur(7,2) = 50.
efcur(2:8,3) = [50 100 150 200 150 100 50];
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',efcur(*,2),toh)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',efcur(:,3),toh);
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',efcur(*,2),toh
% endif
end
% ;
% endif
end
% 
% if mvloop(0) eq 18 and iscramb ne 0 then begin
if mvloop == 18 && iscramb ~= 0
% for i=0,7 do begin
% efcur(1,i) = 50.
% efcur(2,i) = 100.
% efcur(3,i) = 150.
% efcur(4,i) = 200.
% efcur(5,i) = 150.
% efcur(6,i) = 100.
% efcur(7,i) = 50.
% endfor
efcur(2:8,1:8) = repmat([50;100;150;200;150;100;50],1,8);
% endif   
end
% ;
% if mvloop(0) ne 18 or iscramb eq 0 then begin
if mvloop ~= 18 || iscramb == 0
% fbte1,toh,efcur(*,4),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_005',vbit,tbit
% fbte1,toh,efcur(*,5),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_006',vbit,tbit
% fbte1,toh,efcur(*,6),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_007',vbit,tbit
% fbte1,toh,efcur(*,7),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_008',vbit,tbit
for k = 5:8
[tbit,vbit] = fbte1(toh,efcur(:,k),tbit,vbit);
wave_put(['\PCS::DRAW_FEEDFOR_E_I:ALIM_00' int2str(k)],vbit,tbit);
end
% endif
end
% ;
% if (mvloop(0) eq 6 and iscramb ne 0) then begin
if mvloop == 6 && iscramb ~= 0
 error('UNTRANSLATED')
% UNTRANSLATED
%   for imv=0,6 do begin
%     if imv lt 2 then icor=0 else icor=1
%     if mvloop(imv+1) ne 0 then begin
% 	efcur(1,imv+icor) = -50.
% 	efcur(2,imv+icor) = -100.
% 	efcur(3,imv+icor) = -150.
% 	efcur(4,imv+icor) = -200.
% 	efcur(5,imv+icor) = -150.
% 	efcur(6,imv+icor) = -100.
% 	efcur(7,imv+icor) = -50.
% ; set 8th track to zero (SC, 21/08/08)
% 	status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	   '\PCS::DRAW_FEEDFOR_E_I:ALIM_'+iii(imv+icor+1),$
% 			efcur(*,imv+icor),toh)
% ;	wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_'+iii(imv+icor+1),$
% ;			efcur(*,imv+icor),toh)
%     endif
%   endfor
% END UNTRANSLATED
% endif
end
% 
% if mvloop(0) eq 18 and iscramb ne 0 then begin
if mvloop == 18 && iscramb ~= 0
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',efcur(*,0),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',efcur(*,1),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',efcur(*,2),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_004',efcur(*,3),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_005',efcur(*,4),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_006',efcur(*,5),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_007',efcur(*,6),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_E_I:ALIM_008',efcur(*,7),toh)
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_001',efcur(*,0),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_002',efcur(*,1),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_003',efcur(*,2),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_004',efcur(*,3),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_005',efcur(*,4),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_006',efcur(*,5),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_007',efcur(*,6),toh
% ;wave_put,'\PCS::DRAW_FEEDFOR_E_I:ALIM_008',efcur(*,7),toh
 for k = 1:8
  mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
  ['\PCS::DRAW_FEEDFOR_E_I:ALIM_00' int2str(k)],efcur(:,k),toh);
 end
% endif
end
% ; F
% 
% fbte1,toh,efcur(*,8),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_001',vbit,tbit
% fbte1,toh,efcur(*,9),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_002',vbit,tbit
% fbte1,toh,efcur(*,10),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_003',vbit,tbit
% fbte1,toh,efcur(*,11),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_004',vbit,tbit
% fbte1,toh,efcur(*,12),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_005',vbit,tbit
% fbte1,toh,efcur(*,13),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_006',vbit,tbit
% fbte1,toh,efcur(*,14),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_007',vbit,tbit
% fbte1,toh,efcur(*,15),tbit,vbit
% wave_put,'\PCS::DRAW_FEEDFOR_F_I:ALIM_008',vbit,tbit
for k = 1:8
 [tbit,vbit] = fbte1(toh,efcur(:,k+8),tbit,vbit);
 wave_PUT(['\PCS::DRAW_FEEDFOR_E_I:ALIM_00' int2str(k)],vbit,tbit)
end
% 
% ;  Initial coil current sign when operating in automatic sign switching mode
% ;    (SC, 05/09/05)
% for i=0,15 do begin
for i = 1:16
%   indcur=where(abs(efcur(*,i)) gt 100)
 indcur = find(abs(efcur(:,i)) > 100);
%   if indcur(0) ne -1 then begin
  if ~isempty(indcur)
%     signbit(i)=efcur(indcur(0),i)/abs(efcur(indcur(0),i))
  signbit(i) = sign(indcur(1),i);
%   endif else begin
  else
%     signbit(i)=1
   signbit(i) = 1;
%   endelse
  end
% endfor
end
% 
% ; ########## Put the ALIM Usage to the tree                     ;
% ;  Added sign bit argument (SC, 26/09/05)
% alim_mode,request_modes,request_levels,request_select,signbit   ;
alim_mode(request_modes,request_levels,request_select,signbit)
% 
% ;  #######################################   now the toroidal field
% 
% radius = 0.88
radius = 0.88;
% constant = 2*!pi*radius/(4*!pi*1.e-7*16*6)
constant = 2*pi*radius/(4*pi*1.e-7*16*6);
% 
% ;bphi= 	abs([0.0, $
% ;        vcs_rget('SHOTDB::SHOT_DESIGN:' + ['BPHI','BPHI']), $
% ;        0.0])
% ;
% ;top_time=vcs_rget('SHOTDB::SHOT_DESIGN:BPHI_FLAT_START_TIME')
% ;start_time = top_time -      $
% ;       bphi(1)/vcs_rget('SHOTDB::SHOT_DESIGN:BPHI_RAMP_RATE')
% ;stop_time=vcs_rget('SHOTDB::SHOT_DESIGN:BPHI_FLAT_END_TIME')
% ;end_time = stop_time +       $
% ;       bphi(1)/vcs_rget('SHOTDB::SHOT_DESIGN:BPHI_RAMP_RATE')
% ;bphi_time=  [start_time,top_time,stop_time,end_time]
% 
%    bphi               = bzeroft*1.02 ; correction for power supply error
bphi               = bzeroft*1.02; % correction for power supply error
%    bphi_time          = toft
bphi_time          = toft;
%    bphi_time(1)       = -0.103
bphi_time(2)       = -0.103;
%    bphi_time(0)       = bphi_time(1) - bphi(1)/1.2
bphi_time(1)       = bphi_time(2) - bphi(2)/1.2;
%    bphi_time(ntoft-1) = bphi_time(ntoft-2) + bphi(ntoft-2)/1.2
bphi_time(ntoft) = bphi_time(ntoft-1) + bphi(ntoft-1)/1.2;
% 
% if(not keyword_set(nobphi)) then begin
if nargin > 3 && nobphi
% ; set 8th track to zero (SC, 21/08/08)
% ; do not set 8th track to zero because it leads to overly abrupt changes 
% ;   (SC, 09/07/09)
% ;  status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% ;  	'\PCS::DRAW_FEEDFOR_TOR_I:ALIM_001',bphi*constant,bphi_time)
% ; remove filtering (SC, 17/02/11)
%   wave_put,'\PCS::DRAW_FEEDFOR_TOR_I:ALIM_001',bphi*constant,bphi_time,'as_is'
  wave_put('\PCS::DRAW_FEEDFOR_TOR_I:ALIM_001',bphi*constant,bphi_time,'as_is')
% endif
end
% 
% ; load the FPS
% 
% ;  ############################################### now the FPS
% fps_u        = [0.0, 0.0]
fps_u        = [0.0, 0.0];
% fps_u_time   = [min(toh),max(toh)]
fps_u_time   = [min(toh),max(toh)];
% 
% ;-----------------square wave for FPS test--------------------
% ; fps_u_p      = [ 0.0, 100.,100.,-100.,-100.,0.0]
% ; fps_u_time_p = [.000,.001,.010,.012,.020,.021]
% ; deltat=.03
% ; ncycle=30
% ; fps_u        = [0.0]
% ; fps_u_time   = [min(toh)]
% ; for i=0,ncycle-1 do begin & $
% ;       fps_u=[fps_u, fps_u_p] & $
% ;  fps_u_time=[fps_u_time, fps_u_time_p+i*deltat] & $
% ; endfor
% ;     fps_u=[fps_u, 0.0]
% ;fps_u_time=[fps_u_time, max(toh)]
% ;------------------------------------------------------------- 
% fps_i        = [0.0, 0.0]
fps_i        = [0.0, 0.0];
% fps_i_time   = [min(toh),max(toh)]
fps_i_time   = [min(toh),max(toh)];
% if nfast eq 0 or iscramb eq 0 then fps_udc      = [1.0,1.0]*350.0
if nfast == 0 || iscramb == 0, fps_udc      = [1.0,1.0]*350.0; end
% if nfast ne 0 then fps_udc      = [1.0,1.0]*270.0
if nfast ~= 0, fps_udc      = [1.0,1.0]*270.0; end
% fps_udc_time = [min(toh)-0.1,max(toh)]
fps_udc_time = [min(toh)-0.1,max(toh)];
% 
% wave_put,'\PCS::DRAW_FPS:UDCREF_001', fps_UDC, fps_UDC_time
wave_put('\PCS::DRAW_FPS:UDCREF_001', fps_udc, fps_udc_time)
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FPS:UREF_001',   fps_U,   fps_U_time)
mdsvalue('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FPS:UREF_001',   fps_u,   fps_u_time);
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FPS:IREF_001',   fps_I,   fps_I_time)
mdsvalue('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FPS:IREF_001',   fps_i,   fps_i_time);
% ;wave_put,'\PCS::DRAW_FPS:UREF_001',   fps_U,   fps_U_time
% ;wave_put,'\PCS::DRAW_FPS:IREF_001',   fps_I,   fps_I_time
% 
% 
% ;  #####################################################   now the GAS
% 
% eps = 1.e-3
% % eps = 1.e-3;
% ; --get Ip flattop start/stop from aipoft trace--
% ind=where((abs(aipoft(1:*)-aipoft(0:*)) lt 10.0) and $
%           (abs(aipoft) gt 0.5*max(abs(aipoft))) )  ; delta Ip lt 10 Amps
ind  =find((abs(aipoft(2:end)-aipoft(1:end-1)) < 10.0) & ...
          (abs(aipoft) > 0.5*max(abs(aipoft))) );  % delta Ip lt 10 Amps
% 
% ; Modified to take into account possibility of no flattop (amagic=0); if
% ;   no Ip flattop is found, flattop is formally described as a 0-length trace
% ;   at the Ip peak (SC, 16/01/03)
% ;nflat=((ntoft-15)/2)+12
% ;if ind(0) eq -1 then begin   ; no Ip flattop (use nflat)
% ;   nipflat1=nflat & nipflat2=nflat+1
% if ind(0) eq -1 then begin
if ~isempty(ind)
%    dummy = max(aipoft,nipflat1)
   [~,nipflat1] = max(aipoft);
%    nipflat2 = nipflat1
   nipflat2 = nipflat1;
% endif else begin
else
%    nipflat1=min(ind) & nipflat2=max(ind)+1
   nipflat1 = min(ind) ; nipflat2 = max(ind)+1;
% endelse
end
% nflat = nipflat1
nflat = nipflat1;
%    
% 
% ; All gas-related lines commented out (SC, 16/01/03)
% ;xtime=  [vcs_rget('SHOTDB::SHOT_DESIGN:' + ['FILL_ON_TIME','FILL_OFF_TIME',$
% ;        'BLEED_ON_TIME','PUFF_ON_TIME','PUFF_OFF_TIME']),toft(nflat+1)]
% ;if (xtime(4) ge xtime(5)-eps) then xtime(4)=xtime(5)-2*eps
% ;
% ;xamp = vcs_rget('SHOTDB::SHOT_DESIGN:' + $
% ;        ['FILL_VOLTS','PEDESTAL_VOLTS','BLEED_VOLTS','PUFF_VOLTS'])
% ;
% ;gas_time = [xtime(0)-eps,xtime(0),xtime(1),xtime(1)+eps,xtime(2),xtime(2)+eps,$ 
% ;        xtime(3),xtime(3)+eps,xtime(4),xtime(4)+eps,xtime(5),xtime(5)+eps]
% ;gas_amp = [0,xamp(0),xamp(0),xamp(1),xamp(1),xamp(2),xamp(2),xamp(3),xamp(3), $
% ;        0.,0.,0.]
% ;
% ;; adjust the gas timing 
% ;gas_time = gas_time - xtime(0) + toft(3) - 0.045
% 
% ;ymif(not keyword_set(nogas)) then begin
%  ;wave_put,'\PCS::DRAW_FEEDFOR_GAS:ALIM_001',gas_amp,gas_time
% ;ym  wave_put,'\PCS::DRAW_FEEDFOR_GAS:ALIM_001',                           $
% ;ym  [0.000, 4.800, 4.800, 1.800, 1.800,3.000,3.000,3.000,3.000,0.000],  $
% ;ym  [-0.046,-0.045,-0.030,-0.029,-0.000,0.001,0.300,0.301,0.7500,0.751]
% ;ymendif	; nogas
% 
% ; set 8th gas track to zero (SC, 08/08)
% gas = mds$value('\PCS::DRAW_FEEDFOR_GAS:ALIM_001');
gas = mdsdata('\PCS::DRAW_FEEDFOR_GAS:ALIM_001');
% tgas = mds$value('dim_of(\PCS::DRAW_FEEDFOR_GAS:ALIM_001)');
tgas = mdsdata('DIM_OF(\PCS::DRAW_FEEDFOR_GAS:ALIM_001)');
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_GAS:ALIM_001',gas,tgas)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_GAS:ALIM_001',gas,tgas);
% 
% ; ##################################################### TIMING
% 
% if iscramb eq 0 and inova eq 5 then begin
if iscramb == 0 && inova == 5
%  pol_start_time = toft(0)
 pol_start_time = toft(1);
%  pol_stop_time  = max(toft)
 pol_stop_time  = max(toft);
% endif else begin
else
%  pol_start_time = toh(0)
 pol_start_time = toh(1);
%  pol_stop_time  = max(toh)
 pol_stop_time  = max(toh);
% endelse
end
% 
% bphi_start_time = bphi_time(0)
bphi_start_time = bphi_time(1);
% bphi_stop_time  = max(bphi_time)
bphi_stop_time  = max(bphi_time);
% 
% ; setup the timing references
% 
% ;x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','ECRH','ECRH_A','ECRH_B','ECRH_C','FLAT','RAMP']+ $
% ;   '_START_REF',[0.,pol_start_time,bphi_start_time,0.,0.,0.,0.,toft(nipflat1),toft(3)])
% 
% ;x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','ECRH','ECRH_A','ECRH_B','ECRH_C','FLAT','RAMP']+ $
% ;   '_STOP_REF',[max(toft),pol_stop_time,bphi_stop_time,0.,0.,0.,0.,toft(nipflat2),toft(nflat)])
% 
% ; JBL Sept 98 remove ecrh
% if iscramb eq 0 and inova eq 5 then begin
if iscramb == 0 && inova == 5
%  x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','FLAT','RAMP']+ $
%    '_START_REF',[0.,pol_start_time,bphi_start_time,toh(0),toh(n_elements(toh)-1)])
 mdsdata('VDBPUT("SHOTDB::SHOT_DESIGN:"//["IP","POL","BPHI","FLAT","RAMP"]//"_START_REF",$)', ...
   [0.,pol_start_time,bphi_start_time,toh(1),toh(end)]);
% 
%  x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','FLAT','RAMP']+ $
%    '_STOP_REF',[max(toft),pol_stop_time,bphi_stop_time,toh(0),toh(n_elements(toh)-1)])
 mdsdata('VDBPUT("SHOTDB::SHOT_DESIGN:"//["IP","POL","BPHI","FLAT","RAMP"]//"_STOP_REF",$)', ...
   [max(toft),pol_stop_time,bphi_stop_time,toh(1),toh(end)]);
% endif else begin
else
%  x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','FLAT','RAMP']+ $
%    '_START_REF',[0.,pol_start_time,bphi_start_time,toft(nipflat1),toft(3)])
 mdsdata('VDBPUT("SHOTDB::SHOT_DESIGN:"//["IP","POL","BPHI","FLAT","RAMP"]//"_START_REF",$)', ...
   [0.,pol_start_time,bphi_start_time,toft(nipflat1),toft(4)]);
% 
%  x=vcs_rput('SHOTDB::SHOT_DESIGN:'+['IP','POL','BPHI','FLAT','RAMP']+ $
%    '_STOP_REF',[max(toft),pol_stop_time,bphi_stop_time,toft(nipflat2),toft(nflat)])
 mdsdata('VDBPUT("SHOTDB::SHOT_DESIGN:"//["IP","POL","BPHI","FLAT","RAMP"]//"_STOP_REF",$)', ...
   [max(toft),pol_stop_time,bphi_stop_time,toft(nipflat2),toft(nflat)]);
% endelse
end
% 
% ; -- delay PID integrator unclamp --
% x=vcs_rput('TIMER3_OPERDB::TIMER_019:ABSOLUTE',-5.00)
mdsdata('VDBPUT("TIMER3_OPERDB::TIMER_019:ABSOLUTE",-5.00)');
% x=vcs_rput('TIMER3_OPERDB::TIMER_01A:ABSOLUTE',-4.00)
mdsdata('VDBPUT("TIMER3_OPERDB::TIMER_01A:ABSOLUTE",-4.00)');
%   x=vcs_rput('TIMER3_OPERDB::TIMER_01B:ABSOLUTE',ton)
mdsdata('VDBPUT("TIMER3_OPERDB::TIMER_01B:ABSOLUTE",$)',ton);
%   x=vcs_rput('TIMER3_OPERDB::TIMER_01C:ABSOLUTE',toff)
mdsdata('VDBPUT("TIMER3_OPERDB::TIMER_01C:ABSOLUTE",$)',toff);
% UNTRANSLATED
% endif else begin
%   x=vcs_rput('TIMER3_OPERDB::TIMER_01B:ABSOLUTE',0.300)
%   x=vcs_rput('TIMER3_OPERDB::TIMER_01C:ABSOLUTE',2.500)
% endelse
% END UNTRANSLATED
% 
% ;set voltage feed_forward signals to zero
% ; and DONT DO VOLTAGE_DO LATER IN SHOT_DESIGN!!!
% 
% alim = strarr(18)
% for i=1,2 do alim(i-1)='\PCS::DRAW_FEEDFOR_OH_U:ALIM_'+iii(i)
% for i=1,8 do alim(i+1)='\PCS::DRAW_FEEDFOR_E_U:ALIM_' +iii(i)
% for i=1,8 do alim(i+9)='\PCS::DRAW_FEEDFOR_F_U:ALIM_' +iii(i)
alim = [strcat('\PCS::DRAW_FEEDFOR_OH_U:ALIM_',iii(1:2));
        strcat('\PCS::DRAW_FEEDFOR_E_U:ALIM_',iii(1:8));
        strcat('\PCS::DRAW_FEEDFOR_F_U:ALIM_',iii(1:8))];
        
% volts=[0.0,0.0]
volts=[0.0,0.0];
% if iscramb eq 0 and inova eq 5 then begin
if iscramb == 0 && inova == 5
%   tvolts=[min(toh),max(toh)]
  tvolts=[min(toh),max(toh)];
% endif else begin
else
%   tvolts=[min([toft,toh]),max([toft,toh])]
  tvolts=[min([toft,toh]),max([toft,toh])];
% endelse
end
% ; set 8th track to zero (SC, 21/08/08)
% for i=0,17 do begin
for i = 1:18
%   status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3),$4),', $
%   	alim(i),volts,tvolts,'as_is')
  mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3),$4),', ...
  	alim(i),volts,tvolts,'as_is');
% endfor
end
% ;for i=0,17 do wave_put,alim(i),volts,tvolts,'as_is'
% 
% ;zero all reference signals to A matrix
% ; Remove 021 if the nogas is defined
% for i=1,20 do wave_put,'\PCS::DRAW_REFS:REF_'+iii(i),   $
%                             volts,tvolts,'as_is'
for i=1:20, wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],   ...
                            volts,tvolts,'as_is'); end
% ;ymif(not keyword_set(nogas) ) then wave_put,'\PCS::DRAW_REFS:REF_021',   $
% ;ym                            volts,tvolts,'as_is'
% for i=22,24 do wave_put,'\PCS::DRAW_REFS:REF_'+iii(i),   $
%                             volts,tvolts,'as_is'
for i=22:24, wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],   ...
                            volts,tvolts,'as_is'); end
% 
% ;zero all perts
% for i=1,24 do wave_put,'\PCS::DRAW_PERTS:PERT_'+iii(i),   $
%                             volts,tvolts,'as_is'
for i=1:24, wave_put(['\PCS::DRAW_PERTS:PERT_' iii(i)],   ...
                            volts,tvolts,'as_is'); end
% 
% ;draw  wavegen references
% ;
% if (mvloop(0) ne 1 and mvloop(0) ne 11 and mvloop(0) ne 21 and mvloop(0) ne 18 and $
%    mvloop(0) ne 2 and mvloop(0) ne 12 and (mvloop(0) mod 10) ne 5) $
% 	or iscramb eq 0 then begin
if mvloop ~= 1 && mvloop ~= 11 && mvloop ~= 21 && mvloop ~= 18 && ...
   mvloop ~= 2 && mvloop ~= 12 && rem(mvloop,10) ~= 5 ...
	|| iscramb == 0
%  if iscramb eq 0 and inova eq 5 then begin
 if iscramb == 0 && inova == 5
%   wave_put,'\PCS::DRAW_REFS:REF_001',efcur(*,0),toh
  wave_put('\PCS::DRAW_REFS:REF_001',efcur(:,1),toh)
%  endif else begin
 else
%   wave_put,'\PCS::DRAW_REFS:REF_001',efwave(*,0),toh
  wave_put('\PCS::DRAW_REFS:REF_001',efwave(:,1),toh)
%  endelse
 end
% endif
end
% ;
% if (mvloop(0) ne 2 and mvloop(0) ne 12) or iscramb eq 0 then begin
if mvloop ~= 2 && mvloop ~= 12 || iscramb == 0
%  if iscramb eq 0 and inova eq 5 then begin
 if iscramb == 0 && inova == 5
%   wave_put,'\PCS::DRAW_REFS:REF_002',efcur(*,1),toh
  wave_put('\PCS::DRAW_REFS:REF_002',efcur(:,2),toh)
%  endif else begin
 else
%   wave_put,'\PCS::DRAW_REFS:REF_002',efwave(*,1),toh
  wave_put('\PCS::DRAW_REFS:REF_002',efwave(:,2),toh)
%  endelse
 end
% endif
end
% ;
% if (mvloop(0) eq 1 or mvloop(0) eq 2 or mvloop(0) eq 12 $
% 	or (mvloop(0) mod 10) eq 5) and iscramb ne 0 then begin
if mvloop == 1 || mvloop == 2 || mvloop == 12 ...
	|| rem(mvloop,10) == 5 && iscramb ~= 0
% ;nn1=where(toh gt ton)
% ;nn2=nn1(0)
% ;ioh=efcur(nn2,16)
% nnn=n_elements(toh)
nnn=length(toh);
% iohref=replicate(ioh,nnn) 
iohref=repmat(ioh,nnn,1); 
% wave_put,'\PCS::DRAW_REFS:REF_001',iohref,toh,'as_is'
wave_put('\PCS::DRAW_REFS:REF_001',iohref,toh,'as_is')
% endif
end
% ;
% if (mvloop(0) eq 11 or mvloop(0) eq 21) and iscramb ne 0 then begin
if mvloop == 11 || mvloop == 21 && iscramb ~= 0
% nnn=n_elements(toh)
nnn=length(toh);
% vlref=replicate(relovo,nnn) 
vlref=repmat(relovo,1,nnn); 
% wave_put,'\PCS::DRAW_REFS:REF_001',vlref,toh
wave_put('\PCS::DRAW_REFS:REF_001',vlref,toh)
% endif
end
% 
% ;
% ; Two-component IOH feedback (SC, 06/04/05)
% if iscramb ne 0 then begin
if iscramb ~= 0
% if mvloop(0) eq 2 then begin
if mvloop == 2
% nnn=n_elements(toh)
nnn=length(toh);
% ioh1ref=replicate(ioh1,nnn) 
ioh1ref=repmat(ioh1,nnn,1); 
% wave_put,'\PCS::DRAW_REFS:REF_002',ioh1ref,toh,'as_is'
wave_put('\PCS::DRAW_REFS:REF_002',ioh1ref,toh,'as_is')
% endif
end
% if mvloop(0) eq 12 then begin
if mvloop == 12
% nnn=n_elements(toh)
nnn=length(toh);
% ioh1ref=replicate(ioh1,nnn)* $
% 	mds$value('\PCS::LOAD_FEED_GAINS[1]*\HYBRID::PID_P[1]')
ioh1ref=replicate(ioh1,nnn,1)* ...
	mdsdata('\PCS::LOAD_FEED_GAINS[1]*\HYBRID::PID_P[1]');
% wave_put,'\PCS::DRAW_PERTS:PERT_002',ioh1ref,toh,'as_is'
wave_put('\PCS::DRAW_PERTS:PERT_002',ioh1ref,toh,'as_is')
% endif
end
% endif
end
% ;
% if mvloop(0) ne 18 or iscramb eq 0 then begin
if mvloop ~= 18 || iscramb == 0
%  if iscramb eq 0 and inova eq 5 then begin
 if iscramb == 0 && inova == 5
%   wave_put,'\PCS::DRAW_REFS:REF_003',efcur(*,2),toh
%   wave_put,'\PCS::DRAW_REFS:REF_004',efcur(*,3),toh
%   wave_put,'\PCS::DRAW_REFS:REF_005',efcur(*,4),toh
%   wave_put,'\PCS::DRAW_REFS:REF_006',efcur(*,5),toh
%   wave_put,'\PCS::DRAW_REFS:REF_007',efcur(*,6),toh
%   wave_put,'\PCS::DRAW_REFS:REF_008',efcur(*,7),toh
  for i = 3:8
   wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],efcur(:,i),toh)
  end
%  endif else begin
 else
%   wave_put,'\PCS::DRAW_REFS:REF_003',efwave(*,2),toh
%   wave_put,'\PCS::DRAW_REFS:REF_004',efwave(*,3),toh
%   wave_put,'\PCS::DRAW_REFS:REF_005',efwave(*,4),toh
%   wave_put,'\PCS::DRAW_REFS:REF_006',efwave(*,5),toh
%   wave_put,'\PCS::DRAW_REFS:REF_007',efwave(*,6),toh
%   wave_put,'\PCS::DRAW_REFS:REF_008',efwave(*,7),toh
  for i = 3:8
   wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],efwave(:,i),toh)
  end
%  endelse
 end
% endif
end
% ;
% if mvloop(0) eq 18 and iscramb ne 0 then begin
if mvloop == 18 && iscramb ~= 0
% nnn=n_elements(toh)
nnn=length(toh);
% zero=replicate(0.0,nnn)
zero=zeros(nnn,1);
% wave_put,'\pcs::draw_refs:ref_001',zero,toh
% wave_put,'\pcs::draw_refs:ref_002',zero,toh
% wave_put,'\pcs::draw_refs:ref_003',zero,toh
% wave_put,'\pcs::draw_refs:ref_004',zero,toh
% wave_put,'\pcs::draw_refs:ref_005',zero,toh
% wave_put,'\pcs::draw_refs:ref_006',zero,toh
% wave_put,'\pcs::draw_refs:ref_007',zero,toh
% wave_put,'\pcs::draw_refs:ref_008',zero,toh
for i = 1:8
  wave_put(['\pcs::draw_refs:ref_' iii(i)],zero,toh)
end
% endif
end
% ;
% if (mvloop(0) eq 6 and iscramb ne 0) then begin
if mvloop == 6 && iscramb ~= 0
 error('UNTRANSLATED')
% UNTRANSLATED
%   volts=[0.0,0.0]
%   tvolts=[min([toft,toh]),max([toft,toh])]
%   wave_put,'\PCS::DRAW_REFS:REF_001',volts,tvolts,'as_is'
%   for imv=1,6 do begin
%     if imv lt 2 then icor=0 else icor=1
%     if mvloop(imv+1) ne 0 then wave_put,'\PCS::DRAW_REFS:REF_'+$
% 			iii(imv+icor+1),volts,tvolts,'as_is'
%   endfor
% END UNTRANSLATED
% endif
end
% ;
% if iscramb eq 0 and inova eq 5 then begin
if iscramb == 0 && inova == 5
%  wave_put,'\PCS::DRAW_REFS:REF_009',efcur(*,8),toh
%  wave_put,'\PCS::DRAW_REFS:REF_010',efcur(*,9),toh
%  wave_put,'\PCS::DRAW_REFS:REF_011',efcur(*,10),toh
%  wave_put,'\PCS::DRAW_REFS:REF_020',efcur(*,11),toh
%  wave_put,'\PCS::DRAW_REFS:REF_019',efcur(*,12),toh
%  wave_put,'\PCS::DRAW_REFS:REF_014',efcur(*,13),toh
%  wave_put,'\PCS::DRAW_REFS:REF_015',efcur(*,14),toh
%  wave_put,'\PCS::DRAW_REFS:REF_016',efcur(*,15),toh
for i = 9:16
 wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],efcur(:,i),toh)
end
% endif else begin
else
%  wave_put,'\PCS::DRAW_REFS:REF_009',efwave(*,8),toh
%  wave_put,'\PCS::DRAW_REFS:REF_010',efwave(*,9),toh
%  wave_put,'\PCS::DRAW_REFS:REF_011',efwave(*,10),toh
%  wave_put,'\PCS::DRAW_REFS:REF_020',efwave(*,11),toh
%  wave_put,'\PCS::DRAW_REFS:REF_019',efwave(*,12),toh
%  wave_put,'\PCS::DRAW_REFS:REF_014',efwave(*,13),toh
%  wave_put,'\PCS::DRAW_REFS:REF_015',efwave(*,14),toh
%  wave_put,'\PCS::DRAW_REFS:REF_016',efwave(*,15),toh
for i = 9:16
 wave_put(['\PCS::DRAW_REFS:REF_' iii(i)],efwave(:,i),toh)
end
% endelse
end
% if iscramb eq 0 then begin
if iscramb == 0
%  wave_put,'\PCS::DRAW_REFS:REF_018',efcur(*,16),toh 
 wave_put('\PCS::DRAW_REFS:REF_018',efcur(:,17),toh) 
% endif else begin
else
%  wave_put,'\PCS::DRAW_REFS:REF_018',efwave(*,17),toh 
 wave_put('\PCS::DRAW_REFS:REF_018',efwave(:,18),toh) 
% endelse
end
% 
% if midplan ne 8 and iscramb ne 0 then begin
if midplan ~= 8 && iscramb ~= 0
%  wave_put,'\PCS::DRAW_REFS:REF_012',zeref,toh
 wave_put('\PCS::DRAW_REFS:REF_012',zeref,toh)
%  wave_put,'\PCS::DRAW_REFS:REF_024',efwave(*,23),toh   
 wave_put('\PCS::DRAW_REFS:REF_024',efwave(:,24),toh)   
%  wave_put,'\PCS::DRAW_REFS:REF_023',efwave(*,22),toh
 wave_put('\PCS::DRAW_REFS:REF_023',efwave(:,23),toh)
% ; Make kappa reference always available (SC, 11/01/07)
% ; if iscramb eq 12 or iscramb eq 15 or iscramb eq 16 or iscramb eq 19 $
% ;	or iscramb eq 25 or iscramb eq 26 or iscramb eq 36 $
% ;	or mvloop(0) eq 6 then $
% 	wave_put,'\PCS::DRAW_REFS:REF_022',cayref,toh
	wave_put('\PCS::DRAW_REFS:REF_022',cayref,toh)
% endif
end
% 
% ;ymif(not keyword_set(nogas)) then begin
% ;ym  wave_put,'\PCS::DRAW_REFS:REF_021',                   $
% ;ym          [0.,0.,3.5,4.5,4.5,0.,0.],[-.28,0.,.2,.4,0.75,1.8,2.1]
% ;         [0.,0.,3.5,3.5,3.5,0.,0.],[-.28,0.,.2,.4,0.75,1.8,2.1]
% ;         [0.,0.,2.5,2.5,2.5,0.,0.],[-.28,0.,.1,.4,0.75,1.8,2.1]
% ;ym  if nfast ne 0 then wave_put,'\PCS::DRAW_REFS:REF_021',aipoft*0.85e-5,toft
% ;ymendif	; nogas
% 
% wave_put,'\PCS::DRAW_REFS:REF_017',ohcur,toft
wave_put('\PCS::DRAW_REFS:REF_017',ohcur,toft)
% wave_put,'\PCS::DRAW_REFS:REF_013',aipoft,toft
wave_put('\PCS::DRAW_REFS:REF_013',aipoft,toft)
% 
% if (mvloop(0) mod 10) eq 5 and mvloop(0) gt 100 then $
% 	wave_put,'\PCS::DRAW_REFS:REF_004',aipoft,toft
if rem(mvloop,10) == 5 && mvloop > 100,
	wave_put('\PCS::DRAW_REFS:REF_004',aipoft,toft), end
% 
% ;   if midplan eq 8 then begin
% ;   wave_put,'\PCS::DRAW_REFS:REF_013',aipoft*0.5,toft
% ;   endif
% 
% if midplan eq 8 and iscramb ne 0 then begin
if midplan == 8 && iscramb ~= 0
%  wave_put,'\PCS::DRAW_REFS:REF_012',efwave(*,19),toh
 wave_put('\PCS::DRAW_REFS:REF_012',efwave(:,20),toh)
%  wave_put,'\PCS::DRAW_REFS:REF_022',efwave(*,21),toh
 wave_put('\PCS::DRAW_REFS:REF_022',efwave(:,22),toh)
%  wave_put,'\PCS::DRAW_REFS:REF_023',efwave(*,22),toh
 wave_put('\PCS::DRAW_REFS:REF_023',efwave(:,23),toh)
%  wave_put,'\PCS::DRAW_REFS:REF_018',efwave(*,17),toh
 wave_put('\PCS::DRAW_REFS:REF_018',efwave(:,18),toh)
% endif
end
% 
% if midplan eq 9 and iscramb ne 0 then begin 
if midplan == 9 && iscramb ~= 0 
%  wave_put,'\PCS::DRAW_REFS:REF_022',efwave(*,21),toh
 wave_put('\PCS::DRAW_REFS:REF_022',efwave(:,22),toh)
%  wave_put,'\PCS::DRAW_REFS:REF_023',efwave(*,22),toh 
 wave_put('\PCS::DRAW_REFS:REF_023',efwave(:,23),toh) 
% endif 
end
% 
% toh=toh2
toh=toh2;
% 
% ; set 8th track to zero (SC, 21/08/08)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\PCS::DRAW_FEEDFOR_OH_U:ALIM_001',efvolt(*,16)+20.,toh)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_OH_U:ALIM_001',efvolt(:,17)+20.,toh);
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_oh_u:alim_002',efvolt(*,17),toh)
mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
	'\PCS::DRAW_FEEDFOR_OH_U:ALIM_002',efvolt(:,18),toh);
% 
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_001',efvolt(*,0),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_002',efvolt(*,1),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_003',efvolt(*,2),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_004',efvolt(*,3),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_005',efvolt(*,4),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_006',efvolt(*,5),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_007',efvolt(*,6),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_e_u:alim_008',efvolt(*,7),toh)
for i = 1:8
 mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
  ['\PCS::DRAW_FEEDFOR_E_U:ALIM_' iii(i)],efvolt(:,i),toh);
end 
% 
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_001',efvolt(*,8),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_002',efvolt(*,9),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_003',efvolt(*,10),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_004',efvolt(*,11),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_005',efvolt(*,12),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_006',efvolt(*,13),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_007',efvolt(*,14),toh)
% status=mds$value('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', $
% 	'\pcs::draw_feedfor_f_u:alim_008',efvolt(*,15),toh)
for i = 1:8
 mdsdata('WAVE_PUT($1,[REPLICATE(SET_RANGE(,1,F_FLOAT($2)),1,7),ZERO(SHAPE($2),F_FLOAT(0.0))],F_FLOAT($3))', ...
  ['\PCS::DRAW_FEEDFOR_F_U:ALIM_' iii(i)],efvolt(:,i+8),toh);
end 
% 
% ;wave_put,'\PCS::DRAW_FEEDFOR_OH_U:ALIM_001',efvolt(*,16)+20.,toh
% ;wave_put,'\pcs::draw_feedfor_oh_u:alim_002',efvolt(*,17),toh
% 
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_001',efvolt(*,0),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_002',efvolt(*,1),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_003',efvolt(*,2),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_004',efvolt(*,3),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_005',efvolt(*,4),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_006',efvolt(*,5),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_007',efvolt(*,6),toh
% ;wave_put,'\pcs::draw_feedfor_e_u:alim_008',efvolt(*,7),toh
% 
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_001',efvolt(*,8),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_002',efvolt(*,9),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_003',efvolt(*,10),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_004',efvolt(*,11),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_005',efvolt(*,12),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_006',efvolt(*,13),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_007',efvolt(*,14),toh
% ;wave_put,'\pcs::draw_feedfor_f_u:alim_008',efvolt(*,15),toh
% ;
% liuqe_params
liuqe_params
% ;
% end
end

function a = iii(n)
a = mdsdata('III($)',n);
end

function wave_put(node,x,t)
mdsdata('WAVE_PUT($1,$2,$3)',node,x,t);
end

% pro mat_put,id,mat,mat_inputs,mat_outputs,mat_out_scale
function mat_put(id,mat,mat_inputs,mat_outputs,mat_out_scale)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : MAT_PUT.pro
% 
% ; PURPOSE :
% ; To load a physical matrix into the PCS tree
% 
% ; ARGUMENTS :
% ; id			'A','G1-3','M'
% ; mat			Physical matrix
% ; mat_inputs		input list
% ; mat_outputs		output list
% ; mat_out_scale		output scales
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ;	Jo Lister Oct 1992	Original
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; First check on the dimensions of the arguments
% s_mat=size(mat)
s_mat = size(mat);
% s_in=size(mat_inputs)
s_in = length(mat_inputs);
% s_out=size(mat_outputs)
s_out = length(mat_outputs);
% s_scale=size(mat_out_scale)
s_scale = length(mat_out_scale);
% 
% if(s_mat(2) ne s_in(1)) or (s_mat(1) ne s_out(1)) or (s_mat(1) ne s_scale(1)) then begin
if s_mat(2) ~= s_in || s_mat(1) ~= s_out || s_mat(1) ~= s_scale
%   print,'Mat_Put '+id+' Errors'
%   help,mat,mat_inputs,mat_outputs,mat_out_scale
%   !tcvcs_error='Mat_Put '+id+' Errors'
%   return
 error(['Mat_Put ' id ' Errors'])
% endif
end
% 
% mds$put,'\pcs::phys_mat_'+id+'_inputs','$',mat_inputs
mdsput(['\pcs::phys_mat_' id '_inputs'],mat_inputs)
% mds$put,'\pcs::phys_mat_'+id+'_outputs','$',mat_outputs
mdsput(['\pcs::phys_mat_' id '_outputs'],mat_outputs)
% mds$put,'\pcs::phys_mat_'+id+'_out_scales','$',mat_out_scale
mdsput(['\pcs::phys_mat_' id '_out_scales'],mdscvt(mat_out_scale,'f'))
% mds$put,'\pcs::phys_mat_'+id,'$',mat
mdsput(['\pcs::phys_mat_' id],mdscvt(mat,'f'))
% 
% end
end

% pro set_gains,gains
function set_gains(gains)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : SET_GAINS.pro
% 
% ; PURPOSE :
% ; Set the 24 loadable gains, according to the user-recipe gains
% 
% ; ARGUMENTS :
% ; gains		gains, with the same number of elements as outputs
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; 	Jo Lister	Aug 1993	Original
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% print,'SET GAINS '+!stime
% 
% mds$put,'\pcs::feed_gains','$',gains
mdsput('\pcs::feed_gains',mdscvt(gains,'f'))
% 
% outputs = 	strupcase(mds$value('\pcs::phys_mat_a_outputs'))
outputs = upper(mdsdata('\pcs::phys_mat_a_outputs'));
% outputs = strmid(outputs,2,3)
outputs = cell2mat(outputs);
outputs = outputs(:,3:5);
% 
% load_gains = intarr(24)+1
load_gains = ones(24,1);
% load_gains(fix(outputs)-1) = gains
load_gains(num2str(outputs)) = gains;
% 
% mds$put,'\pcs::load_feed_gains','$',load_gains
mdsput('\pcs::load_feed_gains',mdscvt(load_gains,'f'))
% 
% end
end

%% SETUP_REFS
% pro setup_refs,inscales,inoutputs,inamat_refs
function setup_refs(inscales,inoutputs,inamat_refs)
%  
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : SETUP_REFS.pro
% 
% ; PURPOSE :
% ; Set up the reference drawables
% 
% ; ARGUMENTS :
% ; scales		A-matrix output scales
% ; outputs		A-Matrix outputs
% ; amat_refs		Reference sources
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; Jo Lister	May 1993	Original
% ; M.J.Dutch	Mar 1995	Set limits for ALL CPs (incl. !xxx)
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% if ( n_elements(outputs) ne n_elements(scales)) then begin
if length(inoutputs) ~= length(inscales)
%   !tcvcs_error = 'SETUP REFS Bad Data'
%   print,!tcvcs_error
%   help
%   return
 error('SETUP REFS Bad Data')
% endif
end
% 
% print,'SETUP REFS and PERTS in the A-Outputs and G2-Inputs '+!STIME
% 
% ; first we set up the 32 vector of reference sources
% refs = replicate('XXX',32)      
refs = repmat({'XXX'},32,1);
% 
% ; render case-insensitive and extract the characters 00n for the wire number
% outputs=strupcase(inoutputs)
outputs = upper(inoutputs);
% 
% ; set limits for ALL specified references (including !xxx)
% strindex = strmid(outputs,2,3)
strindex = cell2mat(outputs);
strindex = strindex(:,3:5);
% index=fix(strindex)
index = str2mat(strindex);
% refs(index-1)=inamat_refs 
refs(index) = inamat_refs;
% mds$put,'\pcs::load_wave_gen_b:refs','build_signal($,*,$)', $  
%         refs,indgen(32)+1                                      
mdsput('\pcs::load_wave_gen_b:refs','build_signal($,*,$)', ...  
        refs,1:32);                                      
% 
% ; now get rid of !xxx references
% keep=where(strpos(outputs,'!') eq -1)
keep = find(~cellfun(@isempty,strfind(outputs,'!')));
% outputs = outputs(keep)
outputs = outputs(keep);
% amat_refs = inamat_refs(keep)
amat_refs = inamat_refs(keep);
% scales = inscales(keep)
% % scales = inscales(keep);
% 
% strindex = strmid(outputs,2,3)
strindex = cell2mat(outputs);
strindex = strindex(:,3:5);
% index=fix(strindex)
index = str2mat(strindex);
% 
% UNTRANSLATED
% ip_index = where(strpos(outputs,'IPLA') ne -1 and $        
%          strpos(outputs,'ABS') eq -1)                      
% ip_index = ip_index(0)                                         
% 
% ; now we apply reasonable limits to the drawables
% limits = scales * 10.0                                  
% count=0
% xxindex = where(amat_refs eq 'IP',count)
% if(count gt 0) then limits(xxindex) =  $                            
%       limits(xxindex)/scales(ip_index)  
% nout = n_elements(outputs)
% 
% ;for i=0,nout-1 do mds$put, $                                    
% ;        '\pcs::draw_refs:ref_'+strindex(i) $
% ;        +':limits','$',limits(i)*[-1,1]                         
% ;for i=0,nout-1 do mds$put, $                                    
% ;        '\pcs::draw_perts:pert_'+strindex(i) $            
% ;        +':limits','$',limits(i)*[-1,1]   
% END UNTRANSLATED
% 
% ; which outputs are unused
% absent 	= indgen(24)+1
absent 	= 1:24;
% absent(index-1)=0
absent(index) = 0;
% count	= 0
% ok	= where(absent ne 0,count)
ok	= find(absent ~= 0);
% 
% ; set any unused nodes off, and labels to inactive
% if(count ne 0) then begin
if ~isempty(ok)
%  absent 	= iii(absent(ok))
 absent = iii(absent(ok));
%  for i=0,n_elements(absent)-1 do begin
 for i = 1:length(absent)
%   mds$tcl,'set node \pcs::draw_refs:ref_'+absent(i)+' /off'
  mdstcl(['set node \pcs::draw_refs:ref_' absent(i) ' /off'])
%   mds$tcl,'set node \pcs::draw_perts:pert_'+absent(i)+' /off'
  mdstcl(['set node \pcs::draw_perts:pert_' absent(i) ' /off'])
%   mds$put,'\pcs::draw_refs:ref_'+absent(i)+':label','$','INACTIVE'
  mdsput(['\pcs::draw_refs:ref_' absent(i) ':label'],'INACTIVE')
%   mds$put,'\pcs::draw_perts:pert_'+absent(i)+':label','$','INACTIVE'
  mdsput(['\pcs::draw_perts:pert_' absent(i) ':label'],'INACTIVE')
%  endfor
 end
% endif
end
% 
% ; set all used refs on, and setup the labels
% for i=0,n_elements(outputs)-1 do begin
for i = 1:length(outputs)
%   mds$tcl,'set node \pcs::draw_refs:ref_'+strindex(i)+' /on'
 mdstcl(['set node \pcs::draw_refs:ref_' strindex(i) ' /on'])
%   mds$tcl,'set node \pcs::draw_perts:pert_'+strindex(i)+' /on'
 mdstcl(['set node \pcs::draw_perts:pert_' strindex(i) ' /on'])
%   mds$put,'\pcs::draw_refs:ref_'+strindex(i)+':label','$','REF_'+outputs(i)+ $
% 	' '+amat_refs(i)
 mdsput(['\pcs::draw_refs:ref_' strindex(i) ':label'],['REF_' outputs(i)  ...
 	' ' amat_refs(i)])
%   mds$put,'\pcs::draw_perts:pert_'+strindex(i)+':label','$','PERT_'+outputs(i) + $
% 	' '+amat_refs(i)
 mdsput(['\pcs::draw_perts:pert_' strindex(i) ':label'],['PERT_' outputs(i) ...
	 ' ' amat_refs(i)])
% endfor
end
% 
% end
end

%% MAT_DO
% pro mat_do,index,pcs_path
function mat_do(index,pcs_path)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : MAT_DO.pro
% 
% ; PURPOSE :
% ; Takes the physics matrices, and puts them into the loadable matrices
% ; we sort the rows and columns into the right hardware positions
% ; we convert the MKSA units into physical gains (V/V)
% 
% ; ARGUMENTS :
% ; index		Address of the matrix in the hybrid system
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; 	Jo Lister October 1992
% ; 	M.Dutch (5/3/93): bpol_AVG probes updated (use gains from sector 3)
% ; 	Jo Lister April 1993	Add output scales, PID scales and intermediate gains
% ; 	Jo Lister Dec 1993	Modify for new PCS
% ;	Jo Lister April 1994	Add fringes
% ;	Jo Lister Aug 1995	Cater for +- plasma currents
% ;	M.Dutch	  Aug 1996	Add the FPS (FAST) outscale
% ;				*** (should be a new node in hybrid tree, 
% ;				*** (but hardwired for now to -27.0 V/V
% ;				*** (actually depends on UDCref!!!!!!)
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% Print,'MAT_DO at index ',index,'  ',!stime
% 
% ; add pcs_path argument (SC, 06/05/10)
% if (not keyword_set(pcs_path)) then begin                       ;
if nargin < 2                       ;
%   pcs_path='hybrid'
  pcs_path = 'hybrid';
% endif
end
% pcs_path=strlowcase(pcs_path)
pcs_path = lower(pcs_path);
% 
% ; #################################################  Prepare the A-matrix
% 
% ; First we check whether the scale for Ip needs changing
% ; The voltage of channel 13 must be positive for the disruption detector
% outscale = 	mds$value('\pcs::phys_mat_a_out_scales')
outscale = mdsdata('\pcs::phys_mat_a_out_scales');
% outputs = 	strupcase(mds$value('\pcs::phys_mat_a_outputs'))
outputs = upper(mdsdata('\pcs::phys_mat_a_outputs'));
% ip_ref = 	mds$value('\pcs::draw_refs:ref_013')
ip_ref = 	mdsdata('\pcs::draw_refs:ref_013');
% ip_index = where(strpos(outputs,'013') ne -1) & ip_index=ip_index(0)
ip_index = find(cellfun(@isemptz,strmatch(outputs,'013')));
if ~isempty(ip_index); ip_index = ip_index(1); end
% if (abs(min(ip_ref)) gt abs(max(ip_ref)) and outscale(ip_index) gt 0 or $
%     abs(min(ip_ref)) lt abs(max(ip_ref)) and outscale(ip_index) lt 0) then begin
if (abs(min(ip_ref)) > abs(max(ip_ref)) && outscale(ip_index) > 0 || ...
    abs(min(ip_ref)) < abs(max(ip_ref)) && outscale(ip_index) < 0)
%     outscale(ip_index)=-outscale(ip_index)
 outscale(ip_index) = -outscale(ip_index);
%     mds$put,'\pcs::phys_mat_a_out_scales','$',outscale
 mdsput('\pcs::phys_mat_a_out_scales',mdscvt(outscale,'f'))
%     print,'Ip Outscale sign changed by MAT_DO to ',outscale(ip_index)
% endif
end
% 
% inputs = 	mds$value('\pcs::phys_mat_a_inputs')
inputs = 	mdsdata('\pcs::phys_mat_a_inputs');
% phys_mat = 	mds$value('\pcs::phys_mat_a')
phys_mat = mdsdata('\pcs::phys_mat_a');
% 
% ; add the rogowski
% add_rog,inputs,outputs,phys_mat
[inputs,phys_mat] = add_rog(inputs,outputs,phys_mat);
% 
% ; add the ZIP
% add_z,inputs,outputs,phys_mat
add_z(inputs,outputs,phys_mat)
% 
% ; add the FRINGES
% add_fringes,inputs,outputs,phys_mat
[inputs,phys_mat] = add_fringes(inputs,outputs,phys_mat);
% 
% ; add the Bphi backoffs
% add_backoffs,inputs,outputs,phys_mat
[inputs,phys_mat] = add_backoffs(inputs,outputs,phys_mat);
% 
% ; add the offsets
% add_offsets,inputs,outputs,phys_mat
add_offsets(inputs,outputs,phys_mat);
% 
% ; create the A-Matrix output list
% outlist = 'CP'+iii(indgen(24)+1)
outlist = strcat('CP',iii(1:24));
% 
% ; compare the first 5 characters of the outputs, allowing use of the rest
% outputs = strmid(outputs,0,5)
outputs = char(outputs); outputs = outputs(:,1:5);
% 
% inlist = strupcase([mds$value('\hybrid::mat_a1:cabling'), $
% 		replicate('dummy for size',8)])
inlist = {upper(mdsdata('\HYBRID::MAT_A1:CABLING')) ...
		repmat('dummy for size',1,8)};
% 
% ; calculate the inscale parameters
% inscale = pcs_invgains(inputs)
inscale = pcs_invgains(inputs);
% 
% ; Store the A-Matrix input scales (YM - 1.2.2000)
% mds$put,'\hybrid::mat_a_in_scale','$',inscale
mdsput('\hybrid::mat_a_in_scale',mdscvt(inscale,'f'))
% 
% mat_arrange,inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,mat,'A',outs,in_indexa,out_indexa
[mat,outs,~,out_indexa] = mat_arrange(inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,'A');
% 
% ; Store the A-Matrix output scales
% mds$put,'\pcs::mat_a_out_scales','$',outs
mdsput('\PCS::MAT_A_OUT_SCALES',mdscvt(outs,'f'));
% 
% ; Here we can store the actual physical M-matrix used for the shot
% mds$put,'\pcs::phys_mat_a','$',phys_mat
mdsput('\PCS::PHYS_MAT_A',mdscvt(phys_mat,'f'))
% mds$put,'\pcs::phys_mat_a_inputs','$',inputs
mdsput('\PCS::PHYS_MAT_A_INPUTS',mdscvt(inputs,'f'))
% 
% ; Now store the A-matrix in its loadable form
% matsize=size(mat)
matsize = ndims(mat);
% if (matsize(0) eq 3) then begin
if matsize == 3
%   nmat = matsize(3)
 nmat = matsize(3);
%   mds$put,'\pcs::load_mat_a1','$',mat(*,0:47,*)
 mdsput('\PCS::LOAD_MAT_A1',mdscvt(mat(:,1:48,:),'f'))
%   mds$put,'\pcs::load_mat_a2','$',mat(*,48:95,*)
 mdsput('\PCS::LOAD_MAT_A2',mdscvt(mat(:,49:96,:),'f'))
%   mds$put,'\pcs::load_mat_a3','$',mat(*,96:127,*)
 mdsput('\PCS::LOAD_MAT_A3',mdscvt(mat(:,97:128,:),'f'))
% endif else begin
else
%   nmat=1
 nmat = 1; 
%   mds$put,'\pcs::load_mat_a1','$',mat(*,0:47)
 mdsput('\PCS::LOAD_MAT_A1',mdscvt(mat(:,1:48),'f'))
%   mds$put,'\pcs::load_mat_a2','$',mat(*,48:95)
 mdsput('\PCS::LOAD_MAT_A2',mdscvt(mat(:,49:96),'f'))
%   mds$put,'\pcs::load_mat_a3','$',mat(*,96:127)
 mdsput('\PCS::LOAD_MAT_A3',mdscvt(mat(:,97:128),'f'))
% endelse
end
% 
% mat_indices=indgen(nmat)+index
mat_indices = (0:nmat-1) + index;
% 
% mds$put,'\pcs::load_mat_a1_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_A1_ADDRESS',mdscvt(mat_indices,'l'))
% mds$put,'\pcs::load_mat_a2_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_A2_ADDRESS',mdscvt(mat_indices,'l'))
% mds$put,'\pcs::load_mat_a3_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_A3_ADDRESS',mdscvt(mat_indices,'l'))
% 
% ; #################################################  GAINS
% out_gain = mds$value('\pcs::feed_gains')
out_gain = mdsdata('\PCS::FEED_GAINS');
% 
% ; modify the A-matrix output scales for the gains
% outscalea = outscale/out_gain
outscalea = outscale ./ out_gain;
% 
% ; ################################################### G1..G3 Matrices
% inputs = 	outputs
inputs = 	outputs;
% inlist =  	[outlist,replicate('dummy for size',8)]
inlist =  	{outlist repmat('dummy for size',1,8)};
% 
% outlist = 'GO'+iii(indgen(24)+1)
outlist = strcat('GO',iii(1:24));
% 
% ; #### G1 
% 
% pid_gain = mds$value('\hybrid::pid_i')
pid_gain = mdsdata('\HYBRID::PID_I');
% ;print,out_indexa
% ;print,pid_gain
% pid_gain=pid_gain(out_indexa)
pid_gain = pid_gain(out_indexa);
% ;print,pid_gain
% 
% inscale=replicate(0.0,n_elements(outscalea))
inscale = zeros(n_elements(outscalea),1);
% validgain=where(pid_gain ne 0.0)
validgain = find(pid_gain ~= 0);
% if validgain(0) ne -1 then begin
if ~isempty(validgain)
%   inscale(validgain) = outscalea(validgain) / pid_gain(validgain)
 inscale(validgain) = outscalea(validgain) ./ pid_gain(validgain);
% endif
end
% 
% outputs = 	strupcase(mds$value('\pcs::phys_mat_g1_outputs'))
outputs = 	upper(mdsdata('\PCS::PHYS_MAT_G1_OUTPUTS'));
% outscale = 	mds$value('\pcs::phys_mat_g1_out_scales')
outscale = 	mdsdata('\PCS::PHYS_MAT_G1_OUT_SCALES');
% phys_mat = 	mds$value('\pcs::phys_mat_g1')
phys_mat = 	mdsdata('\PCS::PHYS_MAT_G1');
% 
% ; compare the first 5 characters of the outputs, allowing use of the rest
% outputs = strmid(outputs,0,5)
outputs = char(outputs); outputs = outputs(:,1:5);
% 
% mat_arrange,inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,mat,'G1',outs,in_indexg,out_indexg
mat = mat_arrange(inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,'G1');
% 
% matsize=size(mat)
matsize = ndims(mat);
% if (matsize(0) eq 3) then nmat = matsize(3) else nmat=1
if matsize == 3, nmat = matsize; else nmat = 1; end
% mat_indices=indgen(nmat)+index
mat_indices = (0:nmat-1) + index;
% 
% mds$put,'\pcs::load_mat_g1','$',-mat
mdsput('\PCS::LOAD_MAT_G1',mdscvt(-mat,'f'));
% mds$put,'\pcs::load_mat_g1_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_G1_ADDRESS',mdscvt(mat_indices,'l'));
% 
% ; #### G2
% pid_gain = mds$value('\hybrid::pid_p')
pid_gain = mdsdata('\HYBRID::PID_P');
% pid_gain=pid_gain(out_indexa)
pid_gain = pid_gain(out_indexa);
% inscale=replicate(0.0,n_elements(outscalea))
inscale = zeros(n_elements(outscalea),1);
% validgain=where(pid_gain ne 0.0)
validgain  = find(pid_gain ~= 0);
% if validgain(0) ne -1 then begin
if ~isempty(validgain)
%   inscale(validgain) = outscalea(validgain) / pid_gain(validgain)
  inscale(validgain) = outscalea(validgain) ./ pid_gain(validgain);
% endif
end
% ;inscale = 	outscalea  / mds$value('\hybrid::pid_p')
% outputs = 	strupcase(mds$value('\pcs::phys_mat_g2_outputs'))
outputs = 	upper(mdsdata('\PCS::PHYS_MAT_G2_OUTPUTS'));
% outscale = 	mds$value('\pcs::phys_mat_g2_out_scales')
outscale = 	mdsdata('\PCS::PHYS_MAT_G2_OUT_SCALES');
% phys_mat = 	mds$value('\pcs::phys_mat_g2')
phys_mat = 	mdsdata('\PCS::PHYS_MAT_G2');
% 
% ; compare the first 5 characters of the outputs, allowing use of the rest
% outputs = strmid(outputs,0,5)
outputs = char(outputs); outputs = outputs(:,1:5);
% 
% mat_arrange,inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,mat,'G2',outs,in_indexg,out_indexg
mat = mat_arrange(inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,'G2');
% 
% matsize=size(mat)
matsize = ndims(mat);
% if (matsize(0) eq 3) then nmat = matsize(3) else nmat=1
if matsize == 3, nmat = matsize; else nmat=1; end
% mat_indices=indgen(nmat)+index
mat_indices = (0:nmat-1)+index;
% 
% mds$put,'\pcs::load_mat_g2','$',-mat
mdsput('\PCS::LOAD_MAT_G2',mdscvt(-mat,'f'))
% mds$put,'\pcs::load_mat_g2_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_G2_ADDRESS',mdscvt(mat_indices,'l'))
% 
% ; #### G3
% pid_gain = mds$value('\hybrid::pid_d')
pid_gain = mdsdata('\HYBRID::PID_D');
% pid_gain=pid_gain(out_indexa)
pid_gain=pid_gain(out_indexa);
% inscale=replicate(0.0,n_elements(outscalea))
inscale=zeros(length(outscalea),1);
% validgain=where(pid_gain ne 0.0)
validgain=find(pid_gain ~= 0);
% if validgain(0) ne -1 then begin
if ~isempty(validgain)
%   inscale(validgain) = outscalea(validgain) / pid_gain(validgain)
  inscale(validgain) = outscalea(validgain) ./ pid_gain(validgain);
% endif
end
% ;inscale = 	outscalea  / mds$value('\hybrid::pid_d')
% outputs = 	strupcase(mds$value('\pcs::phys_mat_g3_outputs'))
outputs = 	upper(mdsdata('\PCS::PHYS_MAT_G3_OUTPUTS'));
% outscale = 	mds$value('\pcs::phys_mat_g3_out_scales')
outscale = 	mdsdata('\PCS::PHYS_MAT_G3_OUT_SCALES');
% phys_mat = 	mds$value('\pcs::phys_mat_g3')
phys_mat = 	mdsdata('\PCS::PHYS_MAT_G3');
% 
% ; compare the first 5 characters of the outputs, allowing use of the rest
% outputs = strmid(outputs,0,5)
outputs = char(outputs); outputs = outputs(:,1:5);
% 
% mat_arrange,inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,mat,'G3',outs,in_indexg,out_indexg
mat = mat_arrange(inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,'G3');
% 
% matsize=size(mat)
matsize=ndims(mat);
% if (matsize(0) eq 3) then nmat = matsize(3) else nmat=1
if matsize == 3, nmat = matsize; else nmat=1; end
% mat_indices=indgen(nmat)+index
mat_indices = (0:nmat-1)+index;
% 
% mds$put,'\pcs::load_mat_g3','$',-mat
mdsput('\PCS::LOAD_MAT_G3',mdscvt(-mat,'f'));
% mds$put,'\pcs::load_mat_g3_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_G3_ADDRESS',mdscvt(mat_indices,'l'))
% 
% outscaleg 	= outscale
outscaleg 	= outscale;
% outputsg	= outputs
outputsg	= outputs;
% 
% ; ################################################### M Matrix
% 
% inputs = 	mds$value('\pcs::phys_mat_m_inputs')
inputs = 	mdsdata('\PCS::PHYS_MAT_M_INPUTS');
% outputs = 	mds$value('\pcs::phys_mat_m_outputs')
outputs = 	mdsdata('\PCS::PHYS_MAT_M_OUTPUTS');
% 
% ; inlist et outlist sont tires d'un noeud au lieu d'etre ecrits en dur
% ; YM 1.2.2000
% ;inlist =  	strupcase([outlist(0:15), $			; 1st Input
% ;		 'ctlamp:ipol_e_'+iii(indgen(8)+1), $		; 2nd Input
% ;		 'ctlamp:ipol_f_'+iii(indgen(8)+1), $		
% ;		  outlist(16:19), $				; 3rd Input
% ;		 'ctlamp:ipol_oh_001','ctlamp:ipol_oh_002', $
% ;		  outlist(20:21), $
% ;		replicate('dummy for size',8)])
% ;outlist = 	['E_'+iii(indgen(8)+1),'F_'+iii(indgen(8)+1), $
% ;	  	 'OH_001','OH_002','GAS','FAST']
% inlist  = strupcase([mds$value('\hybrid::mat_m_in_cabling'),$
% 		replicate('dummy for size',8)])
inlist  = upper({mdsdata('\HYBRID::MAT_M_IN_CABLING'), ...
		repmat('DUMMY FOR SIZE',1,8)});
% outlist = mds$value('\hybrid::mat_m_out_cabling')
outlist = mdsdata('\HYBRID::MAT_M_OUT_CABLING');
% 
% if (pcs_path eq 'hybrid' or pcs_path eq 'rtdtacqden') then begin
if strcmp(pcs_path,'hybrid') || strcmp(pcs_path,'rtdtacqden')
% ; include the physical gains for the direct inputs
%   inscale = pcs_invgains(inputs)
  inscale = pcs_invgains(inputs);
% ; add the gains for the inputs already there
%   for i=0,n_elements(outputsg)-1 do begin
  for i = 1,length(outputsg)
%     inscale(where(inputs eq outputsg(i))) = outscaleg(i)
   inscale(inputs == outputsg(i)) = outscaleg(i);
%   endfor
  end
% 
%   if (pcs_path eq 'rtdtacqden') then inscale(20)=1.
  if strcmp(pcs_path,'rtdtacqden'), inscale(21)=1.; end
% 
%   
% 
% ; fix the output scales : volts / volt
%   e_volts   = mds$value('\hybrid::output_scales_e_u')
  e_volts   = mdsdata('\HYBRID::OUTPUT_SCALES_E_U');
%   f_volts   = mds$value('\hybrid::output_scales_f_u')
  f_volts   = mdsdata('\HYBRID::OUTPUT_SCALES_F_U');
%   oh_volts  = mds$value('\hybrid::output_scales_oh_u')
  oh_volts  = mdsdata('\HYBRID::OUTPUT_SCALES_OH_U');
% ; 1 element de outscales provient maintenant d'un noeud (YM - 1.2.2000)
%   outscalfastu=mds$value('\hybrid::output_scales_fast_u')
  outscalfastu=mdsdata('\HYBRID::OUTPUT_SCALES_FAST_U');
% ; RHVPS scales (SC, 05/09/06)
%   rhvps_volts=[mds$value('product(\pcs::rhvps_gain_a[*, "PCS"], 0)'), $
%              mds$value('product(\pcs::rhvps_gain_b[*, "PCS"], 0)'), $
%              mds$value('product(\pcs::rhvps_gain_c[*, "PCS"], 0)')]
  rhvps_volts=[mdsdata('PRODUCT(\PCS::RHVPS_GAIN_A[*, "PCS"], 0)'), ...
             mdsdata('PRODUCT(\PCS::RHVPS_GAIN_B[*, "PCS"], 0)'), ...
             mdsdata('PRODUCT(\PCS::RHVPS_GAIN_C[*, "PCS"], 0)')];
% ; ECRH mirror angle scales (SC, 15/02/07)
%   outscalmirror=[1./mds$value('\pcs::mir_v_slope_01'),$
% 	       1./mds$value('\pcs::mir_v_slope_02'),$
% 	       1./mds$value('\pcs::mir_v_slope_03'),$
% 	       1./mds$value('\pcs::mir_v_slope_04'),$
% 	       1./mds$value('\pcs::mir_v_slope_05'),$
% 	       1./mds$value('\pcs::mir_v_slope_06')]
  outscalmirror=[1./mdsdata('\PCS::MIR_V_SLOPE_01'),...
	       1./mdsdata('\PCS::MIR_V_SLOPE_02'),...
	       1./mdsdata('\PCS::MIR_V_SLOPE_03'),...
	       1./mdsdata('\PCS::MIR_V_SLOPE_04'),...
	       1./mdsdata('\PCS::MIR_V_SLOPE_05'),...
	       1./mdsdata('\PCS::MIR_V_SLOPE_06')];
% 
%   outscales = [replicate(e_volts,8),replicate(f_volts,8),replicate(oh_volts,2),$
% 		1.0, outscalfastu, replicate(1.0,4)]
  outscales = [repmat(e_volts,1,8) repmat(f_volts,1,8) repmat(oh_volts,1,2) ...
		1.0 outscalfastu ones(1,4)];
% ; Set up for RHVPS feedback experiment (SC, 01/11/06)
%   outinda=where(outlist eq 'RHVPSA')
  outinda=find(strcmp('RHVPSA',outlist));
%   outindb=where(outlist eq 'RHVPSB')
  outindb=find(strcmp('RHVPSB',outlist));
%   if outinda(0) ne -1 then begin
  if ~isempty(outinda)
%     outscales(outinda(0))=rhvps_volts(0)
    outscales(outinda)=rhvps_volts(1);
%   endif
  end
%   if outindb(0) ne -1 then begin
  if ~isempty(outindb)
%     outscales(outindb(0))=rhvps_volts(1)
    outscales(outindb)=rhvps_volts(2);
%   endif
  end
% 
% ; Set up for ECRH mirror feedback experiment (SC, 15/02/07)
%   outind1=where(outlist eq 'MIRROR1')
  outind1=find(strcmp(outlist,'MIRROR1'));
%   outind2=where(outlist eq 'MIRROR2')
  outind2=find(strcmp(outlist,'MIRROR2'));
%   outind3=where(outlist eq 'MIRROR3')
  outind3=find(strcmp(outlist,'MIRROR3'));
%   outind4=where(outlist eq 'MIRROR4')
  outind4=find(strcmp(outlist,'MIRROR4'));
%   outind5=where(outlist eq 'MIRROR5')
  outind5=find(strcmp(outlist,'MIRROR5'));
%   outind6=where(outlist eq 'MIRROR6')
  outind6=find(strcmp(outlist,'MIRROR6'));
%   if outind1(0) ne -1 then begin
  if ~isempty(outind1)
%     outscales(outind1(0))=outscalmirror(0)
    outscales(outind1)=outscalmirror(1);
%   endif
  end
%   if outind2(0) ne -1 then begin
  if ~isempty(outind2)
%     outscales(outind2(0))=outscalmirror(1)
    outscales(outind2)=outscalmirror(2);
%   endif
  end
%   if outind3(0) ne -1 then begin
  if ~isempty(outind3)
%     outscales(outind3(0))=outscalmirror(2)
    outscales(outind3)=outscalmirror(3);
%   endif
  end
%   if outind4(0) ne -1 then begin
  if ~isempty(outind4)
%     outscales(outind4(0))=outscalmirror(3)
    outscales(outind4)=outscalmirror(4);
%   endif
  end
%   if outind5(0) ne -1 then begin
  if ~isempty(outind5)
%     outscales(outind5(0))=outscalmirror(4)
    outscales(outind5)=outscalmirror(5);
%   endif
  end
%   if outind6(0) ne -1 then begin
  if ~isempty(outind6)
%     outscales(outind6(0))=outscalmirror(5)
    outscales(outind6)=outscalmirror(6);
%   endif
  end
% 
%   outscale = fltarr(n_elements(outputs))
  outscale = zeros(length(outputs),1);
%   for i=0,n_elements(outputs)-1 do begin
  for i=1:length(outputs)
%     outind=where(outputs(i) eq outlist)
    outind = find(strcmp(outputs(i),outlist));
%     if outind(0) ne -1 then begin
    if ~isempty(outind)
%       outscale(i)=outscales(outind(0))
      outscale(i)  =outscales(outind);
%     endif else begin
    else
%       outscale(i)=1.
      outscale(i)=1.;
%     endelse
    end
%   endfor
  end
%   if (pcs_path eq 'rtdtacqden') then outscale(18)=1.
  if strcmp(pcs_path,'rtdtacqden'), outscale(19)=1.; end
% 
% endif else if (pcs_path eq 'rtdtacq') then begin
elseif strcmp(pcs_path,'rtdtacq')
%   inscale = fltarr(n_elements(inputs))+1.0
  inscale = ones(length(inputs));
% ; FPS scaling remains in hybrid system
%   inscale(where(inputs eq 'GO022')) = outscaleg(where(outputsg eq 'GO022'))
  inscale(strcmp(inputs,'GO022')) = outscaleg(strcmp(outputsg,'GO022'));
%   outscale = fltarr(n_elements(outputs))+1.0
  outscale = ones(length(outputs));
%   outscale(19)=mds$value('\hybrid::output_scales_fast_u')
  outscale(20)=mdsdata('\HYBRID::OUTPUT_SCALES_FAST_U');
% endif
end
% ; 
% ; get the user's physical matrix
% phys_mat = 	mds$value('\pcs::phys_mat_m')
phys_mat = 	mdsdata('\PCS::PHYS_MAT_M');
% if (pcs_path eq 'rtdtacq') then begin
if strcmp(pcs_path,'rtdtacq')
% ; M matrix becomes an effective unit matrix for RT-controlled channels
%  for j=1,21 do begin
 for j=1:21
%   for i=1,19 do begin
  for i=1:19
%    phys_mat(i-1,j-1)=0.
   phys_mat(i,j)=0.;
%   endfor
  end
%  endfor
 end
%  for j=23,40 do begin
 for j=23:40
%   for i=1,19 do begin
  for i=1:19
%    phys_mat(i-1,j-1)=0.
   phys_mat(i,j)=0.;
%   endfor
  end
%  endfor
 end
%  for i=1,18 do begin
 for i=1:18
%   phys_mat(i-1,i-1)=1.
  phys_mat(i,i)=1.;
%  endfor
 end
%  phys_mat(18,20)=1.
 phys_mat(19,21)=1.;
% endif
end
% if (pcs_path eq 'rtdtacqden') then phys_mat(18,20)=1.
if strcmp(pcs_path,'rtdtacqden'), phys_mat(19,21)=1.; end
% 
% mat_arrange,inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,mat,'M',outs,in_indexm,out_indexm
mat = mat_arrange(inputs,outputs,inscale,outscale,inlist,outlist,phys_mat,'M');
% 
% matsize=size(mat)
matsize=ndims(mat);
% if (matsize(0) eq 3) then nmat = matsize(3) else nmat=1
if matsize == 3, nmat = matsize; else nmat=1; end
% mat_indices=indgen(nmat)+index
mat_indices=(0:nmat-1)+index;
% 
% ; now we have the completed M-Matrix
% mds$put,'\pcs::load_mat_m','$',mat
mdsput('\PCS::LOAD_MAT_M',mdscvt(mat,'f'))
% mds$put,'\pcs::load_mat_m_address','$',mat_indices
mdsput('\PCS::LOAD_MAT_M_ADDRESS',mdscvt(mat_indices,'l'));
% 
% print,'MAT_DO ended at ',!stime
% end
end

% pro add_rog,mat_inputs,mat_outputs,mat
function [mat_inputs,mat] = add_rog(mat_inputs,mat_outputs,mat)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ADD_ROG.pro
% 
% ; PURPOSE :
% ; Takes a User-defined A-Matrix, and looks for an output name *IPLA*
% ; If it finds this, it fills the JMM definition of Iplasma
% 
% ; ARGUMENTS :
% ; mat_inputs	Vector of A-Matrix input names
% ; mat_outputs	Vector of A-Matrix output names
% ; mat		A-Matrix
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; 	Jo Lister	May 92	Original
% ; 	Jo Lister	Feb 94	Finalised
% ;	Jo Lister	Mar 94	Revectorised
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% mat_inputs = strupcase(mat_inputs)
mat_inputs = upper(mat_inputs);
% mat_outputs = strupcase(mat_outputs)
mat_outputs = upper(mat_outputs);
% 
% ; check if there are any IPLA outputs to be filled
% count = fix(0)
% ; Changed for compatibility w. FBTE18 (SC, 13/08/09)
% ;out_index = where(strpos(mat_outputs,'IPLA',0) ne -1,count)
% out_index = where(strpos(mat_outputs,'IPA',0) ne -1,count)
out_index = find(~cellfun(@isempty,strfind(mat_outputs,'IPA')));
% if (count eq 0) then return
if isempty(out_index), return, end
% print,'ADD ROG to ',out_index
% 
% ; ##### INCREASE THE DIMENSIONS of MAT if necessary to include more inputs
% prein=n_elements(mat_inputs)
% % prein = length(mat_inputs);
% nmat = n_elements(mat(0,0,*))
nmat = size(mat(1,1,:));
% 
% ; we ned all of the BPOL signals
% integs = 'CTLINT:BPOL_AVG_'+iii(indgen(38)+1)
integs = strcat('CTLINT:BPOL_AVG_',iii(1:38));
% count = fix(0)
% extra = 0
extra = 0;
% for i=1,38 do begin
for i = 1:38
%   integ = integs(i-1)
 integ = integs(i);
%   in_index = where(mat_inputs eq integ , count)
 in_index = find(~cellfun(@isempty,strfind(mat_inputs,integ)), 1);
%   if(count eq 0) then begin
 if isempty(in_index)
%     extra = extra + 1
  extra = extra + 1;
%     mat_inputs = [mat_inputs,integ]
  mat_inputs = {mat_inputs,integ};
%   endif
 end
% endfor
end
% 
% ; get the full backoff coil list E F and OH
% back_list=strupcase(mds$value('\magnetics::ipol:dim'))
back_list = upper(mdsdata('\MAGNETICS::IPOL:DIM'));
% back_list = back_list(0:17)
back_list = back_list(1:18);
% 
% ; check that all of these IPOLs are there
% for i=0,n_elements(back_list)-1 do begin
for i = 1,length(back_list)
%   in_index = where(mat_inputs eq 'CTLAMP:IPOL_'+back_list(i),count)
 in_index = find(~cellfun(@isempty,strfind(mat_inputs,['CTLAMP:IPOL_' back_list(i)])), 1);
%   if(count eq 0) then begin
 if isempty(in_index)
%     extra = extra + 1
  extra = extra + 1;
%     mat_inputs = [mat_inputs,'CTLAMP:IPOL_'+back_list(I)]
  mat_inputs = {mat_inputs,['CTLAMP:IPOL_' back_list(i)]};
%   endif
 end
% endfor
end
% 
% ; pad out the A-MAT if necessary
% if(extra gt 0) then begin mat = [[mat], $
% 	[fltarr(n_elements(mat_outputs),extra,nmat)]] &$
% 	print,' PRE/POST inputs are :',prein,n_elements(mat(0,*,0))&end
if extra > 0
 mat = [mat ...
	 zeros(length(mat_outputs),extra,nmat)];
end
% 
% ; ########## FIRST DO THE BPOL contributions to the IP
% 
% lengths = mds$value('\magnetics::iplasma:trapeze:coeff') / (!pi*4.e-7)
lengths = mdsdata('\MAGNETICS::IPLASMA:TRAPEZE:COEFF') / (pi*4.e-7);
% 
% in_index=intarr(38)
in_index = zeros(38,1);
% for i=0,37 do in_index(i) = where(mat_inputs eq integs(i))
for i = 1:38, in_index(i) = find(strcmp(integs(i),mat_inputs)); end
% for i=0,n_elements(out_index)-1 do  $
for i= 1,length(out_index)
% 	for j=0,nmat-1 do mat(out_index(i),in_index,j) = lengths
	for j = 1:nmat, mat(out_index(i),in_index,j) = lengths; end
end
% ; temporary for snowflakes because they bugger probe #22: uncomment 
% ;	(SC, 21/4/10)
% ;for i=0,n_elements(out_index)-1 do  $
% ;	for j=0,nmat-1 do mat(out_index(i),in_index(21),j) = 0
% 
% 
% ; ##### Now do the IPOL BACKOFF contributions
% 
% back_contrib = mds$value('\magnetics::iplasma:trapeze:crosstalk')
back_contrib = mdsdata('\MAGNETICS::IPLASMA:TRAPEZE:CROSSTALK');
% 
% in_index = intarr(n_elements(back_list))
in_index = zeros(length(back_list));
% for i=0,n_elements(back_list)-1  do in_index(i) =  $
% 	where(mat_inputs eq 'CTLAMP:IPOL_'+back_list(i))
for i = 1,length(back_list), in_index(i) =  ...
	find(strcomp(['CTLAMP:IPOL_' back_list(i)],mat_inputs)); end
% 
% ; we add minus the crosstalk to the current measurement
% for i=0,n_elements(out_index)-1 do  $
for i = 1,length(out_index)
% 	for j=0,nmat-1 do mat(out_index(i),in_index,j) = - back_contrib
	for j = 1:nmat, mat(out_index(i),in_index,j) = - back_contrib; end
end
% 

% end
end

%% ADD_Z
% pro add_z,mat_inputs,mat_outputs,mat
function add_z(~,mat_outputs,~)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ADD_Z.pro
% 
% ; PURPOSE :
% ; Looks for an A-matrix observer called ZIP, and creates it
% 
% ; ARGUMENTS :
% ; mat_inputs	A-Matrix input names
% ; mat_outputs	A-Matrix output names
% ; mat		A_Matrix
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; 	Jo Lister, Dec 1993 	Original
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% 
% mat_inputs = strupcase(mat_inputs)
% % mat_inputs = upper(mat_inputs);
% mat_outputs = strupcase(mat_outputs)
mat_outputs = upper(mat_outputs);
% nmat = n_elements(mat(0,0,*))
% % nmat = size(mat,3);
% 
% ; check if there are any ZIP outputs
% count = fix(0)
% out_index = where(strpos(mat_outputs,'ZIP',0) ne -1,count)
out_index = find(~cellfun(@isempty,findstr(mat_outputs,'ZIP')), 1);
% if (count eq 0) then return
if isempty(out_index), return, end
error('UNTRANSLATED')
% UNTRANSLATED
% print,'ADD ZIP to ',out_index
% 
% ; we use the complete flux loops for the compensation
% loops=[7,8,9,12,13,14,15,25,26,27,28,31,32,33]
% loops='CTLINT:RVLOOP_'+iii(loops)
% coils = 'CTLINT:BPOL_AVG_'+iii(indgen(38)+1)
% 
% ; ##### INCREASE THE DIMENSIONS of MAT if necessary to add some inputs
% prein=n_elements(mat_inputs)
% count = fix(0)
% extra = 0
% for i=0,n_elements(coils)-1 do begin
%   in_index = where(mat_inputs eq coils(i) , count)
%   if(count eq 0) then begin
%     extra = extra + 1
%     mat_inputs = [mat_inputs,coils(i)]
%   endif
% endfor
% 
% for i=0,n_elements(loops)-1 do begin
%   in_index = where(mat_inputs eq loops(i) , count)
%   if(count eq 0) then begin
%     extra = extra + 1
%     mat_inputs = [mat_inputs,loops(i)]
%   endif
% endfor
% 
% if(extra gt 0) then begin mat = [[mat], $
% 	[fltarr(n_elements(mat_outputs),extra,nmat)]] & $
% 	print,'PRE/POST inputs are :',prein,n_elements(mat_inputs)&end
% 
% ; ########## FIRST DO THE BPOL contributions to the ZIP
% 
% lengths = mds$value('\magnetics::iplasma:trapeze:coeff')
% zb = mds$value('static("\\mag_probe:val:z")')
% contrib = lengths * zb / (!pi*4.e-7)
% 
% ; first we zero the outputs, just in case
% mat(out_index,*,*) = 0.0
% ; now we fill the relevant outputs
% in_index = intarr(n_elements(coils))
% for i=0,n_elements(coils)-1 do in_index(i) = where(mat_inputs eq coils(i) )
% for i=0,n_elements(out_index)-1 do  $
% 	for j=0,nmat-1 do mat(out_index(i),in_index,j) = contrib
% 
% ; ##### Now do the LOOPS contributions
% 
% ; the flux loop sensitivity vector is obtained from the procedure Z_CALIB
% ; third version without the partial flux-loops 10,11,29,30
% ;b=[ 1561,       45019,      -38624 ,     110752,      106552   ,   -46160 ,       7695, $
% ;      -12977 ,      73231  ,    -57375 ,    -114451 ,    -110610,       30673,       -2508]
% ; New version, 16-7-98
% b=[      17029  ,    14568   ,   12292   ,      42     ,  9683 ,      9716, $
%         8657    ,   -7884  ,     -8644  ,    -8653   ,     300 ,    -12971, $
%       -15815   ,   -19185 ]
% 
% in_index = intarr(n_elements(loops))
% for i=0,n_elements(loops)-1  do  in_index(i) = where(mat_inputs eq loops(i))
% for i=0,n_elements(out_index)-1 do $
% 	for j=0,nmat-1 do mat(out_index(i),in_index,j) = b
% 
% end
% END UNSTRANSLATED
end

% pro add_fringes,mat_inputs,mat_outputs,mat
function [mat_inputs,mat_outputs,mat] = add_fringes(mat_inputs,mat_outputs,mat)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ADD_FRINGES.pro
% 
% ; PURPOSE :
% ; Looks for A-matrix observers called *FRINGES or *DENSITY, and creates them
% 
% ; ARGUMENTS :
% ; mat_inputs	A-Matrix input names
% ; mat_outputs	A-Matrix output names
% ; mat		A_Matrix
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ; 	Jo Lister, April 1994 	Original
% ;	Jo Lister  June 1994	Add line-density
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% mat_inputs = strupcase(mat_inputs)
mat_inputs = upper(mat_inputs);
% mat_outputs = strupcase(mat_outputs)
mat_outputs = upper(mat_outputs);
% nmat = n_elements(mat(0,0,*))
nmat = size(mat,3);
% 
% ; check if there are any FRINGES or DENSITY outputs
% fcount = fix(0)
% fout_index = where(strpos(mat_outputs,'FRINGES',0) ne -1,fcount)
fout_index = find(~cellfun(@isempty,strfind(mat_outputs,'FRINGES')));
% ; check if there are any DENSITY outputs
% dcount = fix(0)
% dout_index = where(strpos(mat_outputs,'DENSITY',0) ne -1,dcount)
dout_index = find(~cellfun(@isempty,strfind(mat_outputs,'DENSITY')));
% if (fcount+dcount eq 0) then return
if isempty(fout_index) && isempty(dout_index), return, end
% out_index = [fout_index,dout_index]
% out_index=out_index(where(out_index ne -1))
out_index = [fout_index dout_index];
% print,'ADD FRINGES/DENSITY to ',out_index
% 
% ; ##### INCREASE THE DIMENSIONS of MAT if necessary to add some inputs
% prein=n_elements(mat_inputs)
% % prein = lengths(mat_inputs);
% count = fix(0)
% extra = 0
extra = 0;
% in_index = where(mat_inputs eq 'FIR_FRINGE' , count)
in_index = find(strcmp('FIR_FRINGE',mat_inputs), 1);
% if(count eq 0) then begin
if isempty(in_index)
%     extra = extra + 1
 extra = extra + 1;
%     mat_inputs = [mat_inputs,'FIR_FRINGE']
 mat_inputs = {mat_inputs 'FIR_FRINGE'};
% endif
end
% 
% if(extra gt 0) then begin mat = [[mat], $
% 	[fltarr(n_elements(mat_outputs),extra,nmat)]] & $
% 	print,'PRE/POST inputs are :',prein,n_elements(mat_inputs)&end
if extra > 0, mat = [mat, ...
	zeros(length(mat_outputs),extra,nmat)];
end
% 
% in_index =  where(mat_inputs eq 'FIR_FRINGE')
in_index =  find(strcmp('FIR_FRINGE',mat_inputs));
% ; first we zero the line
% mat(out_index,*,*)=0.0
mat(out_index,:,:) = 0;
% 
% ; then we add the observer
% if(fout_index(0) ne -1) then mat(fout_index,in_index(0),*) = 1.0
if ~isempty(fout_index), mat(fout_index,in_index(1),:) = 1; end
% if(dout_index(0) ne -1) then mat(dout_index,in_index(0),*) =  $
% 					mds$value('\diagz::fir:dens_per_fri')
if ~isempty(dout_index), mat(dout_index,in_index(1),:) =  ...
					mdsdata('\diagz::fir:dens_per_fri'); end
% 
% end
end

% pro add_backoffs,mat_inputs,mat_outputs,mat
function [mat_inputs,mat] = add_backoffs(mat_inputs,mat_outputs,mat)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ADD_BACKOFFS.PRO
% 
% ; PURPOSE :
% ; This routine takes an A-Matrix which is in terms of pure B and PSI
% ; It corrects the B and PSI for the Toroidal Field pickup
% 
% ; ARGUMENTS :
% ; mat_inputs	Vector of A-Matrix input names
% ; mat_outputs	Vector of A-Matrix output names
% ; mat		A-Matrix
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASON :
% ; 	Jo Lister 	Aug 93		Original
% ; 	Jo Lister	Feb 94		Finalised
% ;	Jo Lister	Mar 94		Re-vectorised
% ;	Jo Lister	Sept 98		Cancel old and forget the dzdt
% ;	Jo Lister	Nov 98		Delete the extraneous IPHI inputs
% ;-
% ; Controlled by :       Jo
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% print,'ADD BPHI BACKOFFS ',!stime
% 
% mat_inputs 	= strupcase(mat_inputs)+'           '
mat_inputs 	= strcat(upper(mat_inputs),'           ');
% mat_outputs 	= strupcase(mat_outputs)
mat_outputs 	= upper(mat_outputs);
% nmat 	= n_elements(mat(0,0,*))
nmat 	= size(mat,3);
% matout	= mat
matout	= mat;
% 
% ; ##### INCREASE THE DIMENSIONS of MAT_INPUTS if necessary
% bphi_input = 'CTLAMP:IPHI_001'
bphi_input = 'CTLAMP:IPHI_001';
% count 	= fix(0)
% bphi_index = where(strtrim(mat_inputs) eq bphi_input , count)
bphi_index = find(strcmp(bphi_input,mat_inputs));
% if(count eq 0) then begin
if isempty(bphi_index)
%    mat_inputs = [mat_inputs,bphi_input]
 mat_inputs = {mat_inputs bphi_input};
%    print,'PRE/POST inputs are increased for BPHI'
%    matout = [[matout],[fltarr(n_elements(mat_outputs),1)]]  
 matout = [matout zeros(length(mat_outputs),1)];  
% endif else begin
else
%   if(count gt 1) then begin
 if length(bphi_index) > 1
%     in_index = where(strtrim(mat_inputs) ne bphi_input , count)
  in_index = find(~strcmp(bphi_input,mat_inputs));
%     mat_inputs = [mat_inputs(in_index),bphi_input]
  mat_inputs = [mat_inputs(in_index) bphi_input];
%     matout	= mat(*,[in_index,bphi_index(0)],*)
  matout	= mat(:,[in_index bphi_index(1)],:);
%   endif
 end
% endelse
end
% 
% ; locate the position of the BPHI input
% bphi_index = where(strtrim(mat_inputs) eq bphi_input)
bphi_index = strcmp(bphi_input,mat_inputs);
% 
% ; create the correction matrix
% correction 	= fltarr(n_elements(mat_inputs))
correction 	= zeros(length(mat_inputs),1);
% 
% count	= 0
% bpol_index = where (strmid(mat_inputs,0,12) eq 'CTLINT:BPOL_',count)
bpol_index = find(~cellfun(@isempty,strfind(mat_inputs,'CTLINT:BPOL_')));
% if(count gt 0) then begin
if ~isempty(bpol_index)
%   index = strmid(mat_inputs(bpol_index),16,3)
 index = char(mat_inputs(bpol_index)); index = index(:,17:19);
%   search = '['+arr2str(index)+']'
 search = strcat('[',index,']');
%   correction(bpol_index) =  $
% 	(mds$value('\magnetics::bpol_003:crosstalk'+search) + $
% 	 mds$value('\magnetics::bpol_011:crosstalk'+search) )/ 2.0
  correction(bpol_index) = ...
	(mdsdata('\MAGNETICS::BPOL_003:CROSSTALK[$]',search) + ...
	 mdsdata('\MAGNETICS::BPOL_011:CROSSTALK[$]',search) )/ 2;
% endif
end
% 
% rvloop_index = where (strmid(mat_inputs,0,12) eq 'CTLINT:RVLOO',count)
rvloop_index = find(~cellfun(@isempty,strfind(mat_inputs,'CTLINT:RVLOOP_')));
% if(count gt 0) then begin
if ~isempty(rvloop_index)
%   index = strmid(mat_inputs(rvloop_index),14,3)
 index = char(mat_inputs(rvloop_index)); index = index(:,15:17);
%   search = '['+arr2str(index)+']'
 search = strcat('[',index,']');
%   correction(rvloop_index) = mds$value('\magnetics::rflux:crosstalk'+search) 
 correction(rvloop_index) = mdsdata('\MAGNETICS::RFLUX:CROSSTALK[$]',search);
% endif
end
% 
% vloop_index = where (strmid(mat_inputs,0,12) eq 'CTLINT:VLOOP',count)
vloop_index = find(~cellfun(@isempty,strfind(mat_inputs,'CTLINT:VLOOP_')));
% if(count gt 0) then begin
if ~isempty(vloop_index)
%   index = strmid(mat_inputs(vloop_index),13,3)
 index = char(mat_inputs(vloop_index)); index = index(:,14:16);
%   search = '['+arr2str(index)+']'
 search = strcat('[',index,']');
%   correction(vloop_index) = mds$value('\magnetics::flux:crosstalk'+search) 
 correction(vloop_index) = mdsdata('\MAGNETICS::FLUX:CROSSTALK[$]',search);
% endif
end
% 
% ; Make the correction matrix 
% corrector = fltarr(n_elements(matout(0,*)),n_elements(mat_inputs))
corrector = zeros(size(matout,2),length(mat_inputs));
% for i=0,n_elements(matout(0,*,0))-1 do corrector(i,i)=1.0
for i = 1,size(matout,2), corrector(i,i) = 1.0; end
% 
% ; we add minus the correction vector 
% print,size(correction)
% print,size(corrector(*,bphi_index))
% corrector(*,bphi_index) = - correction
corrector(:,bphi_index) = - correction;
% 
% ; apply the correction
% mat2 	= [[[matout(*,*,0) # corrector]]]
mat2 	= matout(:,:,1) * corrector;
% if(nmat gt 1) then for j=1,nmat-1 do mat2 = [[[mat2]],[[matout(*,*,j) # corrector]]]
if nmat > 1, for j = 2:nmat, mat2(:,:,j) = matout(:,:,j) * corrector; end, end
% 
% ; which is the FH dz/dt output in the final matrix?
% count	= 0
% forget	= where(strpos(mat_outputs, 'DZDT') ne -1,count)
forget	= find(~cellfun(@isempty,strfind(mat_outputs,'DZDT')), 1);
% if(count gt 0) then begin
if ~isempty(forget)
%   print,'FH Cancel the row ',forget+1
%   matout(forget(0),bphi_index(0),*) = 0.
% % matout(forget(1),bphi_index(1),:) = 0;
% endif
end
% 
% ; replace with the new version
% mat 	= mat2
mat 	= mat2;
% 
% end
end

% pro add_offsets,mat_inputs,mat_outputs,mat
function add_offsets(~,mat_outputs,~)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ADD_OFFSETS.PRO
% 
% ; PURPOSE :
% ; This routine takes an A-Matrix which is in terms of pure B and PSI
% ; It corrects A for offsets in the outputs, using the IPHI input
% 
% ; ARGUMENTS :
% ; mat_inputs	Vector of A-Matrix input names
% ; mat_outputs	Vector of A-Matrix output names
% ; mat		A-Matrix
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASON :
% ; 	Jo Lister 	Nov 98		Original
% ;-
% ; Controlled by :       Jo
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% print,'ADD OFFSETS ',!stime
% 
% mat_inputs 	= strupcase(mat_inputs)+'           '
% % mat_inputs 	= strcat(upper(mat_inputs),'           ');
% mat_outputs 	= strupcase(mat_outputs)
% % mat_outputs 	= mat_outputs;
% nmat 	= n_elements(mat(0,0,*))
% % nmat 	= size(mat,3);
% 
% ; locate the position of the IPHI input
% iphi_input = 'CTLAMP:IPHI_001'
% % iphi_input = 'CTLAMP:IPHI_001';
% iphi_index = where(strtrim(mat_inputs) eq iphi_input)
% % iphi_index = find(strcmp(iphi_input,mat_inputs));
% 
% ; zip_offset
% zip_input = 'CP012_ZIP'
zip_input = 'CP012_ZIP';
% zip_index = where(strtrim(mat_outputs) eq zip_input)
zip_index = find(strcmpi(zip_input,mat_outputs), 1);
% 
% if(zip_index(0) eq -1) then begin
if isempty(zip_index)
%   print,'ZIP not found'
%   return
 return
% endif
end
% UNTRANSLATED
error('UNTRANSLATED')
% 
% z_offset	= 2800.0
% iphi		= 64000.0
% 
% print,'PRE  ',mat(zip_index,iphi_index),'  OFFSET: ',z_offset
% mat(zip_index,iphi_index)	= mat(zip_index,iphi_index) - z_offset/iphi
% print,'POST ',mat(zip_index,iphi_index)
% 
% end
% END UNTRANSLATED
end

%% PCS_INVGAINS
% ; modifs:  MJD 09/7/96  Add the Fast Coil Current (IPOL_G)
% ;          MJD 25/2/97  Add the Fast Coil Voltage (UDC, UPOL)
% 
% ; these functions are rather clumsy, but they avoid TDI time-wasting
% 
% function amp_gain,name,magvalues,magnames,labels,dim_labels
function gain = amp_gain(name,magvalues,magnames,labels,dim_labels)
% 
% label 	= labels(where(name eq dim_labels))
label 	= labels(strcmp(name,dim_labels));
% 
% index	= where(magnames eq name)
index	= find(strcmp(name,magnames));
% if(index(0) gt -1) then begin
if ~isempty(index)
%   setting = magvalues(index(0))
 setting = magvalues(index(1));
% endif else begin
else
%   !tcvcs_error = ' ERROR !!!! Was not found in magnames'
%   print,name,!tcvcs_error
%   return,-1e30
 error('Was not found in magnames')
% endelse
end
% 
% old_nnn	= mds$value('_amp_nnn')
old_nnn	= mdsdata('_AMP_NNN');
% nnn	= mds$value('_amp_nnn=iii(element(3,"/","'+label(0)+'"))')
nnn	= mdsdata(['_AMP_NNN=III(ELEMENT(3,"/","' label(1) '"))']);
% 
% if(old_nnn ne nnn) then $
if old_nnn ~= nnn
%   dum = mds$value('_amp_gainmat=execute("\\magnetics::amp:cd_"//_amp_nnn)')
 mdsdata('_AMP_GAINMAT=EXECUTE("\\MAGNETICS::AMP:CD_"//_AMP_NNN)');
end
% 
% dum	= mds$value('_n=execute(element(2,"/","'+label(0)+'"))')
mdsdata(['_N=EXECUTE(ELEMENT(2,"/","' label(0) '"))']);
% gain 	= mds$value('_amp_gainmat[_n-1,'+string(setting)+']')
gain 	= mdsdata(['_AMP_GAINMAT[_n-1,' string(setting) ']']);
% 
% return, -0.9969*gain
gain = -0.9969*gain;
% 
% end
end
% 
% function pre_gain,name,magvalues,magnames,labels,dim_labels
function gain = pre_gain(name,magvalues,magnames,labels,dim_labels)
% 
% label = labels(where(name eq dim_labels))
label 	= labels(strcmp(name,dim_labels));
% 
% index=where(magnames eq name)
index	= find(strcmp(name,magnames));
% if(index(0) gt -1) then begin
if ~isempty(index)
%   setting = magvalues(index(0))
 setting = magvalues(index(1));
% endif else begin
else
%   !tcvcs_error=' ERROR !!!! Was not found in magnames'
%   print,name,!tcvcs_error
%   return,1e30
 error('Was not found in magnames')
% endelse
end
% 
% old_nnn	= mds$value('_pre_nnn')
old_nnn	= mdsdata('_PRE_NNN');
% nnn	= mds$value('_pre_nnn=iii(element(3,"/","'+label(0)+'"))')
nnn	= mdsdata(['_PRE_NNN=III(ELEMENT(3,"/","' label(1) '"))']);
% 
% if(old_nnn ne nnn) then $
%   dum	= mds$value('_pre_gainmat=execute("\\magnetics::pre:cd_"//_pre_nnn)')
if old_nnn ~= nnn,
mdsdata('_PRE_GAINMAT=EXECUTE("\\MAGNETICS::PRE:CD_"//_PRE_NNN)'); end
% 
% dum	= mds$value('_n=execute(element(2,"/","'+label(0)+'"))')
mdsdata(['_N=EXECUTE(ELEMENT(2,"/","' label(0) '"))']);
% gain 	= mds$value('_pre_gainmat[_n-1,'+string(setting)+']')
gain 	= mdsdata(['_PRE_GAINMAT[_n-1,' string(setting) ']']);
% 
% return, gain
% 
% end
end
% 
% function int_gain,name,magvalues,magnames,labels,dim_labels
function gain = int_gain(name,magvalues,magnames,labels,dim_labels)
% 
% inds = where(name eq dim_labels)
inds	= find(strcmp(name,dim_labels));
% if inds(0) eq -1 then begin
if isempty(inds)
%   !tcvcs_error="ERROR in INT_GAIN: name <"+name+"> not in array dim_labels:"
%   print,!tcvcs_error
%   print,dim_labels
%   return,1e30
 error(['ERROR in INT_GAIN: name <' name '> not in array dim_labels'])
% endif
end
% 
% label = labels(inds(0))
label = labels(inds(1));
% 
% index=where(magnames eq name)
index	= find(strcmp(name,magnames));
% if(index(0) gt -1) then begin
if ~isempty(index)
%   setting = ((11-magvalues(index(0))) mod 8)
 setting = rem(11-magvalues(index(1)),8);
% endif else begin
else
%   !tcvcs_error=' ERROR !!!! Was not found in magnames'
%   print,name,!tcvcs_error
%   return,1e30
 error(' ERROR !!!! Was not found in magnames')
% endelse
end
% 
% old_nnn	= mds$value('_int_nnn')
old_nnn	= mdsdata('_INT_NNN');
% nnn	= mds$value('_int_nnn=iii(element(3,"/","'+label(0)+'"))')
nnn	= mdsdata(['_INT_NNN=III(ELEMENT(3,"/","' label(1) '"))']);
% 
% if(old_nnn ne nnn) then begin
if old_nnn ~= nnn
%  gainmat = mds$value('_int_gainmat=execute("\\magnetics::int:cd_"//_int_nnn)')
 mdsdata('_INT_GAINMAT=EXECUTE("\\MAGNETICS::INT:CD_"//_INT_NNN)');
% endif
end
% 
% n	= mds$value('_n=execute(element(2,"/","'+label(0)+'"))')
% % n	= mdsdata(['_N=EXECUTE(ELEMENT(2,"/","' label(0) '"))']);
% gain 	= mds$value('_int_gainmat[_n-1,'+string(setting)+']')
gain 	= mdsdata(['_INT_GAINMAT[_n-1,' string(setting) ']']);
% 
% return, -0.9969*gain
gain = -0.9969*gain;
% 
% end
end
% 

% function pcs_invgains,channels
function invgains = pcs_invgains(channels)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : PCS_INVGAINS.pro
% 
% ; PURPOSE :
% ; gets the physical calibration of magnetics channels
% 
% ; ARGUMENTS :
% ; channels		names of the channels needed
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ;	Jo Lister	July 1993	Original
% ;	MJ Dutch	Mar  1995	Bphi inverted, use calibs magnetics.
% ;	Jo Lister	Jan 1998	Set up for variable polarity - cleanup
% ;-
% ; Controlled by :       Jo
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% print,'PCS_INVGAINS  '+!stime+' ',n_elements(channels)
% 
% ; initialise the gainmat calls to -1
% x=mds$value('_amp_nnn=-1;_pre_nnn=-1;_int_nnn=-1')
mdsdata('_amp_nnn=-1;_pre_nnn=-1;_int_nnn=-1');
% 
% ; go and get the real-time settings of the magnetics
% magdb_iget,magvalues,magnames
[magvalues,magnames] = magdb_iget;
% print,'MAGDB_IGET    '+!stime+' ',n_elements(magvalues)
% 
% ; get the different vsystem labels
% labels = mds$value("_labels=\vsystem::magdb_l")
labels = mdsdata('_LABELS=\VSYSTEM::MAGDB_L');
% dim_labels = dim_of('_labels')
dim_labels = mdsdata('DIM_OF(_LABELS)');
% 
% channels = strtrim(strupcase(channels),2)
channels = deblank(upper(channels));
% names=strtrim(strmid(channels,3,50),2)
names = char(channels); names = names(:,4:end);
% types = strmid(names,0,8)
types = names(:,1:8);
% 
% ; Here we gamble on there being many channels and we do some work once
% 
% ; area and polarity of the BPOL coils - not gain-dependent
% bpol_003	= '\magnetics::bpol_003:area'+ $
% 		 '*\magnetics::pol_prob_char:polarity["003",*]'
bpol_003	= ['\magnetics::bpol_003:area' ...
		 '*\magnetics::pol_prob_char:polarity["003",*]'];
% bpol_011	= '\magnetics::bpol_011:area'+ $
% 		 '*\magnetics::pol_prob_char:polarity["011",*]'
bpol_011	= ['\magnetics::bpol_011:area' ...
		 '*\magnetics::pol_prob_char:polarity["011",*]'];
% sens_bpol_003 = mds$value(bpol_003)
sens_bpol_003 = mdsdata(bpol_003);
% sens_bpol_011 = mds$value(bpol_011)
sens_bpol_011 = mdsdata(bpol_011);
% 
% ; the current conversion values
% escale  = mds$value('\magnetics::ipol:calibration["E_001"]')
escale  = mdsdata('\magnetics::ipol:calibration["E_001"]');
% fscale  = mds$value('\magnetics::ipol:calibration["F_001"]')
fscale  = mdsdata('\magnetics::ipol:calibration["F_001"]');
% gscale  = mds$value('\magnetics::ipol:calibration["G_001"]')
gscale  = mdsdata('\magnetics::ipol:calibration["G_001"]');
% gUscale = mds$value('\magnetics::upol:calibration["G_001"]')
% % mdsdata('\magnetics::upol:calibration["G_001"]');
% ohscale = mds$value('\magnetics::ipol:calibration["OH_001"]')
ohscale = mdsdata('\magnetics::ipol:calibration["OH_001"]');
% torscale= mds$value('\magnetics::iphi:calibration')           ;amp/volt
torscale= mdsdata('\magnetics::iphi:calibration'); % amp/volt
% 
% ; initialise the results
% invgains = fltarr(n_elements(names))
invgains = zeros(length(names),1);
% 
% print,'PCS_INVGAINS begin loop '+!stime
% for i=0,n_elements(names)-1 do begin
for i = 1,length(names)
% 
%   invgain = 1.0
 invgain = 1;
%   type = types(i)
 type = types(i,:);
%   name = names(i)
 name = names(i,:);
% 
% ; $$$$$$$$$$$$$$$  GET THE PREAMP AND THE AMPLI/INTEG
% ; $$$$$$$$$$$$$$$  DO THE CONVERSION OF THE SONDES TO PHYSICAL
% 
%  case 1 of
 switch type
%   (type eq 'AMP:IPOL') : begin
  case 'AMP:IPOL'
%     invgain = 1./amp_gain(name+'_AMPGAIN',magvalues,magnames,labels,dim_labels)
   invgain = 1./amp_gain([name '_AMPGAIN'],magvalues,magnames,labels,dim_labels);
%     case strmid(name,0,11) of
   switch name(1:12)
%       'AMP:IPOL_E_': invgain = invgain * escale ; amp/volt
    case 'AMP:IPOL_E_', invgain = invgain * escale; % amp/volt
%       'AMP:IPOL_F_': invgain = invgain * fscale ;amp/volt
    case 'AMP:IPOL_F_', invgain = invgain * fscale; % amp/volt
%       'AMP:IPOL_G_': invgain = invgain * gscale ;amp/volt
    case 'AMP:IPOL_G_', invgain = invgain * gscale; % amp/volt
%       'AMP:UPOL_G_': invgain = invgain * gUscale ;volt/volt
    case 'AMP:UPOL_G_', invgain = invgain * gVscale; % volt/volt
%       'AMP:IPOL_OH': invgain = invgain * ohscale ;amp/volt
    case 'AMP:IPOL_OH', invgain = invgain * ohscale; % amp/volt
%       'AMP:IPOL_DO': invgain = invgain * ohscale ;amp/volt
    case 'AMP:IPOL_DO', invgain = invgain * ohscale; % amp/volt
%       else: begin
    otherwise
%         help,name
%         !tcvcs_error='Invalid IPOL inside PCS_INVGAINS'
     error('Invalid IPOL inside PCS_INVGAINS')
%         print,!tcvcs_error 
% 	return,'ERROR'
%       end
%     endcase
   end
%   end
% 
%   (type eq 'AMP:RVLO' or type eq 'AMP:VLOO') : $
  case { 'AMP:RVLO' 'AMP:VLOO'}
%     invgain = 1./amp_gain(name+'_AMPGAIN',magvalues,magnames,labels,dim_labels)
   invgain = 1./amp_gain([name '_AMPGAIN'],magvalues,magnames,labels,dim_labels);
% 
%   (type eq 'INT:VLOO' or type eq 'INT:RVLO') : $
  case { 'INT:RVLO' 'INT:VLOO'}
%     invgain = int_gain(name+'_INTGAIN',magvalues,magnames,labels,dim_labels)
   invgain = int_gain([name '_INTGAIN'],magvalues,magnames,labels,dim_labels);
%  
%   (type eq 'INT:ROG_') : $
  case { 'INT:ROG_'}
   error('UNTRANSLATED')
% UNTRANSLATED
%     invgain = 1./ $
%         pre_gain('PRE:'+strmid(name,4,50)+'_PREGAIN', $
% 		magvalues,magnames,labels,dim_labels) * $
%     	int_gain(name+'_INTGAIN',magvalues,magnames,labels,dim_labels)
% 
% END UNTRANSLATED
%   (type eq 'INT:BPOL') : begin
  case 'INT:BPOL'
%     short_name=strmid(name,12,42)
   short_name = name(13:55);
%     invgain_003 = 1./ $
% 	pre_gain('PRE:BPOL_003'+short_name+'_PREGAIN', 	$
% 		magvalues,magnames,labels,dim_labels) * $
%     	int_gain('INT:BPOL_003'+short_name+'_INTGAIN', 	$
% 		magvalues,magnames,labels,dim_labels)
   invgain_003 = 1./ ...
    pre_gain(['PRE:BPOL_003' short_name '_PREGAIN'], ...
     magvalues,magnames,labels,dim_labels) * ...
    int_gain(['INT:BPOL_003' short_name '_INTGAIN'], ...
     magvalues,magnames,labels,dim_labels);
%     invgain_011 = 1./ $
% 	pre_gain('PRE:BPOL_011'+short_name+'_PREGAIN', 	$
% 		magvalues,magnames,labels,dim_labels) * $
%     	int_gain('INT:BPOL_011'+short_name+'_INTGAIN', 	$
% 		magvalues,magnames,labels,dim_labels)
   invgain_011 = 1./ ...
    pre_gain(['PRE:BPOL_011' short_name '_PREGAIN'], ...
     magvalues,magnames,labels,dim_labels) * ...
    int_gain(['INT:BPOL_011' short_name '_INTGAIN'], ...
     magvalues,magnames,labels,dim_labels);
%     strindex = strmid(name,13,3)
   strindex = name(14:16);
%     index = fix(strindex)-1
   index = str2num(strindex);
%     weight = (sens_bpol_003(index)/invgain_003 + $
% 		sens_bpol_011(index)/invgain_011)/2.
   weight = (sens_bpol_003(index)/invgain_003 + ...
             sens_bpol_011(index)/invgain_011)/2;
%     invgain = invgain / weight
   invgain = invgain / weight;
%   end
% 
%   (type eq 'AMP:BPOL') : begin
  case 'AMP:BPOL'
%     short_name=strmid(name,12,42)
   short_name = name(13:55);
%     invgain_003 = 1./ $
% 	pre_gain('PRE:BPOL_003'+short_name+'_PREGAIN', 	$
% 		magvalues,magnames,labels,dim_labels) / $
%     	amp_gain('AMP:BPOL_003'+short_name+'_AMPGAIN', 	$
% 		magvalues,magnames,labels,dim_labels)
   invgain_003 = 1./ ...
    pre_gain(['PRE:BPOL_003' short_name '_PREGAIN'], ...
     magvalues,magnames,labels,dim_labels) / ...
    int_gain(['AMP:BPOL_003' short_name '_AMPGAIN'], ...
     magvalues,magnames,labels,dim_labels);
%     invgain_011 = 1./ $
% 	pre_gain('PRE:BPOL_011'+short_name+'_PREGAIN', 	$
% 		magvalues,magnames,labels,dim_labels) / $
%     	amp_gain('AMP:BPOL_011'+short_name+'_AMPGAIN', 	$
% 		magvalues,magnames,labels,dim_labels)
   invgain_011 = 1./ ...
    pre_gain(['PRE:BPOL_011' short_name '_PREGAIN'], ...
     magvalues,magnames,labels,dim_labels) / ...
    int_gain(['AMP:BPOL_011' short_name '_AMPGAIN'], ...
     magvalues,magnames,labels,dim_labels);
%     strindex = strmid(name,13,3)
   strindex = name(14:16);
%     index = fix(strindex)-1
   index = str2num(strindex);
%     weight = (sens_bpol_003(index)/invgain_003 + $
% 		sens_bpol_011(index)/invgain_011)/2.
   weight = (sens_bpol_003(index)/invgain_003 + ...
             sens_bpol_011(index)/invgain_011)/2;
%     invgain = invgain / weight
   invgain = invgain / weight;
%   end
% 
%   (type eq 'AMP:IPHI'):	invgain = invgain * torscale ;amp/volt
  case 'AMP:IPHI', invgain = invgain * torscale; % amp/volt
% 
 end
 switch channels(i)
%   (channels(i) eq 'FIR_FRINGE') : begin 
  case 'FIR_FRINGE'
% 	invgain = invgain  	$
% 		  * 1.075 	$	; Correct for the A-matrix filter (JBL)	
% 		  * 0.1 	$       ; Conversion factor from FIR (CN)
% 		  * 2.^( 8 - vcs_iget('diag2db::fir:fringe_gain') )
  invgain = invgain ...
     * 1.075 	... % Correct for the A-matrix filter (JBL)	
     * 0.1 	  ... % Conversion factor from FIR (CN)
     * 2.^( 8 - mdsdata('VDBGET("DIAG2DB::FIR:FRINGE_GAIN")') );
%         print,'FIR_INVGAIN ',invgain
%   end
% 
%   (channels(i) eq '1MM_FRINGE') : begin
  case '1MM_FRINGE'
% 	invgain = invgain  	$ ;Include 1MM in list of inputs (SC, 27/02/11)
% 		  * (-0.1) 	$ ;Conversion factor (is also in
% 				  ;\base::onemm:fringe_count:conversion)
% 		  * 2.^( 8 - vcs_iget('diag2db::twomm:fringe_gain') )
  invgain = invgain ... % Include 1MM in list of inputs (SC, 27/02/11)
     * (-0.1) ... %Conversion factor (is also in \base::onemm:fringe_count:conversion)
     * 2.^( 8 - mdsdata('VDBGET("DIAG2DB::TWOMM:FRINGE_GAIN")'));
%         print,'1MM_INVGAIN ',invgain
%   end
% 
%   (channels(i) eq '2MM_FRINGE') : $ 
  case '2MM_FRINGE'
% UNTRANSLATED
   error('UNTRANSLATED')
% 	invgain = 1.0	; Include 2MM in list of recognized inputs (MJD 3/95)
% END UNTRANSLATED
% 
%   else: if(strmid(channels(i),0,2) ne 'GO') then $
  otherwise
   tmp = channels(i);
   if ~strcmp(tmp(1:2),'GO')
% 		print,'A-Input not found : ',channels(i),' ',name,' ',type
    error(['A-Input not found : ' channels(i)])
   end
%   endcase 
  end
% 
%   invgains(i) = invgain
  invgains(i) = invgain;
% 
% endfor
end
% 
% print,'PCS_INVGAINS DONE  '+!stime
% 
% return,invgains
% 
% end
end

% pro magdb_iget,values,names
function [values,names] = magdb_iget
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : MAGDB_IGET.pro
% 
% ; PURPOSE :
% ; returns a list of integer channels out of magdb
% 
% ; ARGUMENTS :
% ; values	values found
% ; names		names found
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ;	Jo Lister	July 92	Original
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; get the offset into the magdb database
% chix1 = vcs_chix('magdb::aaardvaaark')-1
mdsopen('DAVE::');
chix1 = mdsdata('VDBCHIX("MAGDB::AAARDVAAARK")')-1;
% 
% ; get the names and chixes out of the tree
% mds$open,'tcv_shot',-1
mdsopen('tcv_shot',-1)
% names = mds$value('\vsystem::magdb_i:names')
names = mdsdata('\VSYSTEM::MAGDB_I:NAMES');
% chixes = mds$value('\vsystem::magdb_i:chixes')+chix1
chixes = mdsdata('\VSYSTEM::MAGDB_I:CHIXES')+chix1;
% 
% ; prepare for list call
% val_array_desc=lonarr(2)
% chix_array_desc = lonarr(2)
% 
% ; go and fetch the gain codes as a list call
% size = long(n_elements(chixes))*4
% values = -chixes
% 
% if( not call_vms('vdb_accshr','vdb_pckdesc',val_array_desc,size,0,0,values))$
%         then print,'Magdb failed pckdesc'
% if( not call_vms('vdb_accshr','vdb_pckdesc',chix_array_desc,size,0,0,chixes))$
%         then print,'Magdb failed chixes'
% if( not call_vms('vdb_accshr','vdb_iget_list',chix_array_desc,val_array_desc))$
%         then  begin
%    if(n_elements(where(values+chixes eq 0)) gt 11) then begin
%      print,'FATAL : MAGDB FAILS (probably arrays) = ', $
% 		n_elements(where(chixes+values eq 0))
%      !tcvcs_error='Magdb failed list_iget'
%      print,!tcvcs_error
%      return
%    endif
% endif
values = mdsdata('VDBGET($)',chixes);
% 
% names=strupcase(names)
names = upper(names);
% 
% end
end

% pro mat_arrange,in,out,inscale,outscale,inlist,outlist,phys_mat,mat,mat_id,outs,in_index,out_index
function [mat,outs,in_index,out_index] = mat_arrange(in,out,inscale,outscale,inlist,outlist,phys_mat,~)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : MAT_ARRANGE.pro
% 
% ; PURPOSE :
% ; converts a physical matrix (physmat) with scales to a gain matrix (mat)
% 
% ; ARGUMENTS :
% ; in		physmat inputs
% ; out		physmat ouputs
% ; inscale	input scales
% ; outscale	output scales
% ; inlist	list of matrix inputs (mat)
% ; outlist	list of matrix outputs (mat)
% ; phys_mat	physmat
% ; mat		mat
% ; outs		ordered list of outscales
% ; in_index	index of inputs for mapping between physical and real world
% ; out_index	index of outputs for mapping between physical and real world
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ;	Jo Lister July 1992	Original
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
%  
% pwint,'MAT_ARRANGE '+mat_id+' '+!stime
% 
% ; check what has been asked
% x = size(phys_mat)
x = ndims(phys_mat);
% ins = [n_elements(in),n_elements(inscale),x(2)]
ins = [length(in),length(inscale),x(3)];
% outs = [n_elements(out),n_elements(outscale),x(1)]
outs = [length(out),length(outscale),x(2)];
% 
% if(stdev(ins) gt 1e-4) or (stdev(outs) gt 1.e-4) then begin
if any(ins ~= ins(1)) || any(outs ~= outs(1))
%   pwint,'MAT ARRANGE - Bad Input data dimensions'
%   help,in,out,inscale,outscale,inlist,outlist,phys_mat
%   !tcvcs_error = 'Mat_arrange Bad Input data dimensions'
%   return
 error('MAT ARRANGE - Bad Input data dimensions')
% endif
end
% 
% ; render case-insensitive
% in      = strtrim(strupcase(in),2)
in      = deblank(upper(in));
% out     = strtrim(strupcase(out),2)
out     = deblank(upper(out));
% inlist  = strtrim(strupcase(inlist),2)
inlist  = deblank(upper(inlist));
% outlist = strtrim(strupcase(outlist),2)
outlist = deblank(upper(outlist));
% nin     = n_elements(in)
nin     = length(in);
% nout    = n_elements(out)
nout    = length(out);
% 
% ; get indicies and check consistency
% in_index  = intarr(nin)
in_index  = zeros(nin,1);
% out_index = intarr(nout)
out_index = zeros(nout,1);
% 
% ; find the indices
% for i=0,nin-1 do begin
for i = 1:nin
%   in_index(i)=where(in(i) eq inlist)
 tmp = find(in(i) == inlist);
%   if(in_index(i) eq -1) then begin
 if isempty(tmp)
%     pwint,'MAT_ARRANGE FAILED at least for INPUT ',i,in(i)
%     pwint,inlist
%     !tcvcs_error='MAT_ARRANGE FAILED at least for INPUT '+iii(i)+' '+in(i)
%     return
  error(['MAT_ARRANGE FAILED at least for INPUT ' int2str(i) in(i)])
%   endif
 end
 in_index(i) = tmp(1);
% endfor
end
% 
% for i=0,nout-1 do begin
for i = 1:nout
%   out_index(i)=where(out(i) eq outlist)
 tmp = find(out(i) == outlist, 1);
%   if(out_index(i) eq -1) then begin
 if isempty(tmp)
%     pwint,'MAT_ARRANGE FAILED OUTPUT ',i,out(i)
%     pwint,outlist
%     !tcvcs_error='MAT_ARRANGE FAILED OUTPUT '+iii(i)+' '+out(i)
%     return
  error(['MAT_ARRANGE FAILED OUTPUT ' int2string(i) out(i)])
%   endif
 end
% endfor
end
% 
% ; create the output scales for this matrix
% outs = fltarr(n_elements(outlist))+1.e8
outs = NaN(length(outlist),1);
% outs(out_index) = outscale
outs(out_index) = outscale;
% 
% ; make the produced matrix
% 
% nmat = 1
nmat = 1;
% if(x(0) eq 3) then nmat = x(3)
if x(1) == 3, nmat = x(2); end
% mat = fltarr(n_elements(outlist),n_elements(inlist),nmat)
mat = zeros(length(outlist),length(inlist),nmat);
% 
% calibrate = (1./outscale)#inscale
calibrate = (1./outscale)*inscale;
% 
% if (nmat gt 0) then begin 
if nmat > 0
%   for i=0,nmat-1 do begin
 for i = 1:nmat
%     mat(out_index,in_index,i) = phys_mat(*,*,i)*calibrate
  mat(out_index,in_index,i) = phys_mat(:,:,i)*calibrate;
%   endfor
 end
% endif else begin 
else
%     mat(out_index,in_index) = phys_mat(*,*)*calibrate
 mat(out_index,in_index) = phys_mat(:,:)*calibrate;
% endelse
end
% 
% end
end

% pro mat_overflow,shot,matrices
function mat_overflow(shot,matrices)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : 
% 
% ; PURPOSE :
% ; Takes the physics matrices, and looks at their statistics
% ; DYNAMIC RANGE and OVERFLOW CHECK
% 
% ; ARGUMENTS :
% ; shot		shot for checking
% ; matrices	Matrices to be checked (default all)
% 
% ; RESTRICTIONS :
% 
% ; UPDATED/REASONS :
% ;	 Jo Lister October 1992
% ;	 M.J.Dutch   April 1995  Properly handle 3-D matrices (e.g. for matrix switching)
% ;-
% ; Controlled by :       Jo
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% pwint,'MAT_OVERFLOW   '+!stime
% mds$open,'tcv_shot',shot
mdsopen('tcv_shot',shot)
% 
% if(n_params() eq 1) then matrices = ['A1','A2','A3','G1','G2','G3','M']
if nargin == 1, matrices = {'A1','A2','A3','G1','G2','G3','M'}; end
% matrices=[strupcase(matrices)]
matrices=upper(matrices);
% 
% for i=0,n_elements(matrices)-1 do begin
for i = 1,length(matrices)
% 
%   counts = mds$value('\hybrid::mat_'+matrices(i)+':counts')
  counts = mdsdata(['\HYBRID::MAT_' matrices(i) ':COUNTS']);
%   count=0
%   x =where(counts ge 4095 or counts le 0 , count)
  x =find(counts >= 4095 | counts <= 0, 1);
% 
%   if(count ne 0) then begin
 if ~isempty(x)
%     !tcvcs_error='******** MAT_OVERFLOW Overflow indices '+matrices(i)
  error(['******** MAT_OVERFLOW Overflow indices ' matrices(i) '\nUNTRANSLATED'])
% UNTRANSLATED 
%     pwint,!tcvcs_error
%     xx = size(COUNTS)
%     x = x(where(x ne -1))
%     for j=0,n_elements(x)-1 do begin
%       if (xx(0) eq 3) then i_mat = fix(x(j)/(xx(1)*xx(2))) else i_mat=0
%       i_in = fix((x(j)-i_mat*xx(1)*xx(2))/xx(1))
%       i_out = x(j)-i_in*xx(1)-i_mat*xx(1)*xx(2)
%       out_name=' '
%       in_name=' '
%       a_cabling = mds$value('\hybrid::mat_a1_cabling')
%       case matrices(i) of 
% 	'A1': in_name = ' '+a_cabling(i_in)
% 	'A2': in_name = ' '+a_cabling(i_in+48)
% 	'A3': in_name = ' '+a_cabling(i_in+96)
%         else:
%       endcase
%       case matrices(i) of 
% 	'A1': out_name = ' '+mds$value('tcv_cp_name('+string(i_out+1)+')')
% 	'A2': out_name = ' '+mds$value('tcv_cp_name('+string(i_out+1)+')')
% 	'A3': out_name = ' '+mds$value('tcv_cp_name('+string(i_out+1)+')')
%         else:
%       endcase
%       
%       pwint,'Element ',fix(x(j)),' Value : ',fix(counts(x(j)))
%       if (xx(0) eq 3) then pwint,' matrix(1:)',byte(i_mat+1),in_name
%       pwint,'  input(1:)',byte(i_in+1),in_name
%       pwint,' output(1:)',byte(i_out+1),out_name
%     endfor
% 
% END UNTRANSLATED 
%   endif
 end
% 
% UNTRANSLATED 
%   number=0
%   nvalid =  where((abs(counts-2048) gt 0.5),number)
%   sigma = 0. & avg = 0.
%   if(number gt 1) then sigma = stdev(counts(nvalid),avg)
%   pwint,matrices(i),' Min/Max,Mean and s.d. ',min(counts),max(counts),avg,sigma
% END UNTRANSLATED 
% 
% endfor
end
% 
% end
end

% pro fbte1,tin,vin,tout,vout
 function [tout,vout] = fbte1(tin,vin)
% 
% ;    This routine defines the bit_set vectors
% 
% ;    F.H.  Jan 1994 
% 
% delta=0.004
delta=0.004;
% delta2=0.009
delta2=0.009;
% ; SC, 31/03/05
% ; removed 05/09/05 (new coil switching mode available)
% ;delta3=0.5
% ;delta4=0.2
% ;tmin=0.3
% ;
% 
% ; SC, 20/08/08: find sign of first nonzero value
% firstsign=1
firstsign=1;
% indv=where(vin ne 0.)
indv=find(vin ~= 0.);
% if indv(0) ne -1 then if vin(min(indv)) lt 0. then firstsign=-1
if ~isempty(indv), if vin(indv(1)) < 0., firstsign=-1; end, end
% 
% vin(0)=0.
% vin(1)=0.
% vin(2)=0.
vin(1:3) = 0;
% 
% f5=vin
f5=vin;
% f5min=min(f5)
f5min=min(f5);
% f5max=max(f5)
f5max=max(f5);
% ; SC, 20/08/08: avoid unnecessary double bit at the beginning when first
% ;   nonzero point is negative
% if firstsign eq 1 then begin
if firstsign == 1
%   if f5min lt 0. then f5(where(f5 lt 0.))=-1
  if f5min < 0., f5(f5 < 0.)=-1; end
%   if f5max ge 0. then f5(where(f5 ge 0.))=1
  if f5max >= 0., f5(f5 >= 0.)=1; end
% endif else begin
else
%   if f5min le 0. then f5(where(f5 le 0.))=-1
  if f5min <= 0., f5(f5 <= 0.)=-1; end
%   if f5max gt 0. then f5(where(f5 gt 0.))=1
  if f5max > 0., f5(f5 > 0.)=1; end
% endelse
end
% nf5=n_elements(f5)
nf5=length(f5);
% f5t=[f5,-f5(nf5-1)]
f5t=[f5,-f5(nf5)];
% f5s=[-f5(0),f5]
f5s=[-f5(1),f5];
% f5=f5t-f5s
f5=f5t-f5s;
% tok=tin(where(f5 ne 0.))
tok=tin(f5 ~= 0.);
% vok=f5(where(f5 ne 0.))
vok=f5(f5 ~= 0.);
% dimm=n_elements(tok)
dimm=length(tok);
% 
% ;for i=2,dimm do begin
% ; dtok=tok(i-1)-tok(i-2)
% ; if (dtok lt delta) then begin
% ;  vok(i-1)=0.
% ;  vok(i-2)=0.
% ;  endif
% ; endfor
% 
% if(dimm gt 2) then begin
if dimm > 2
% differ=tok(1:dimm-1)-tok(0:dimm-2)
differ=tok(2:dimm)-tok(1:dimm-1);
% diff1=differ(0:dimm-3)
diff1=differ(1:dimm-2);
% diff2=differ(1:dimm-2)
diff2=differ(2:dimm-1);
% ind1=where((diff1 gt delta2) and (diff2 gt delta2))
ind1=find(diff1 > delta2 && diff2 > delta2);
% ind2=where((diff1 le delta2) and (diff2 le delta2))
ind2=find(diff1 <= delta2 && diff2 <= delta2);
% ind=ind1
ind=ind1;
% if ind2(0) ne -1 then begin
if ~isempty(ind2)
%    ind3=ind2-1
   ind3=ind2;
%    ind4=[ind1,ind3]
   ind4=[ind1,ind3];
%    ind5=sort(ind4)
   ind5=sort(ind4);
%    ind=ind4(ind5)
   ind=ind4(ind5);
% endif
end
% tok=[tok(0),tok(ind+1)]
tok=[tok(1),tok(ind+2)];
% vok=[vok(0),vok(ind+1)]
vok=[vok(1),vok(ind+2)];
% endif
end
% dimm=n_elements(tok)
dimm=length(tok);
% 
% ; Advance sign bits whenever possible (SC, 31/03/05)
% ; removed 05/09/05 (new coil switching mode available)
% ;advance_index=0
% ;advancebits:
% ;if dimm gt 2 then begin
% ; differ=tok(2:dimm-1)-tok(1:dimm-2)
% ; ind1=where(differ gt delta3)
% ; if ind1(0) ne -1 then tok(ind1+2)=(tok(ind1+1)+delta4>tmin)
% ;endif
% ;advance_index=advance_index+1
% ;delta3=delta3*1.7;
% ;delta4=delta4*1.7;
% ; *don't* make a second pass! (SC, 07/06/05)
% ;if advance_index lt 2 then goto,advancebits
% ;
% 
% toi=tok
toi=tok;
% toi(0)=tok(0)-0.030
toi(1)=tok(1)-0.030;
% 
% 
% for i=1,dimm-1 do toi(i)=tok(i)-delta2
for i= 2:dimm, toi(i)=tok(i)-delta2; end
% 
% 
% toip=toi+delta
toip=toi+delta;
% toim=toi-delta
toim=toi-delta;
% toi3=[toi,toip,toim]
toi3=[toi,toip,toim];
% toi3=toi3(sort(toi3))
toi3=toi3(sort(toi3));
% c=fltarr(3*dimm)
c=zeros(3*dimm,1);
% 
% for i=1,dimm do begin
for i = 2:dimm+1
%  c((3*i)-3)=0.
%  c((3*i)-2)=vok(i-1)
%  c((3*i)-1)=0.
 c(3*i-[2 1 0]) = [0 vok(i) 0];
%  endfor
end
% 
% tout=[toi3,tin(n_elements(tin)-1)]
tout=[toi3,tin(end)];
% vout=[c*500.,0.0]
vout=[c*500.,0.0];
% return
% end
% 
 end

% pro alim_mode, modes, levels, selects, signbit
function alim_mode(modes,levels,selects,signbit)
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; AS such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ;+ TCVCS FILE : ALIM_MODE.pro
% 
% ; PURPOSE :
% ; Sets up the JSI Mode, level and selection in the PCS tree
% ; Ditto for the FPS
% 
% ; ARGUMENTS :
% ; modes		'A','B' or 'C'
% ; levels	'20','50','80','100'    (FPS level anywhere from '0' to '100')
% ; selects	'OFF' or 'ON'
% 
% ; RESTRICTIONS :
% ; either one or 20 of each argument
% ; if one, then copied *20
% ; Alims are ORDERED, --> E1-8,F1-8,OH1-2,TOR,FPS
% 
% ; UPDATED/REASONS :
% ;	 Jo Lister, Dec 1993 NEW
% ;	 M. Dutch,  Jan 1995 Add 20th element for FPS (Alim Rapide)
% ;	 SC, 26/09/05: added sign bit argument
% ;-
% ; Controlled by :       Jo
% ;                       Michael
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% print,'_-_- '+stime()+' ALIM_MODE: starting'
% 
% if (n_params() lt 3 or n_params() gt 4) then begin
if nargin < 3 || nargin > 4
%   !tcvcs_error = 'ALIM_MODE bad args.'
%   print,!tcvcs_error
%   help
%   print,'_-_- '+stime()+' ALIM_MODE: aborted with bad number of arguments'
%   return
 error('ALIM_MODE bad args.')
end
% endif
% 
% n = n_elements(levels)*n_elements(modes)*n_elements(selects)
n = legnth(levels) * length(modes) * length(selects);
% if(n ne 1 and n ne 20 and n ne 20*20 and n ne 20*20*20) then begin
if n ~= 1 && n ~= 20 && n ~= 20*20 && n ~= 20*20*20
%   !tcvcs_error = 'ALIM_MODE bad args.'
%   print,!tcvcs_error
%   help
%   print,'_-_- '+stime()+' ALIM_MODE: aborted with bad dimensions of arguments'
%   return
 error('ALIM_MODE bad args.')
% endif
end
% 
% if(n_elements(levels)  eq 1) 	then  levels	= replicate(levels, 20)
if length(levels) == 1, levels	= repmat(levels,1,20); end
% if(n_elements(modes)   eq 1) 	then  modes	= replicate(modes,  20)
if length(modes) == 1, modes	= repmat(modes,1,20); end
% if(n_elements(selects) eq 1) 	then  selects	= replicate(selects,20)
if length(selects) == 1, selects	= repmat(selects,1,20); end
% 
% ; force the toroidal choice,independently of the user choice
% levels(18) = '100'
levels(19) = '100';
%  modes(18) = 'A'
modes(19) = 'A';
% 
% ; check the 3 alim requests for acceptability
% bad_levels=where((levels(0:18) ne '20') and (levels(0:18) ne  '50') and $
% 	         (levels(0:18) ne '80') and (levels(0:18) ne '100'))
bad_levels = find(~strcmp(levels(1:19),'20') & ~strcmp(levels(1:19),'50') & ...
	         ~strcmp(levels(1:19),'80') & ~strcmp(levels(1:19),'100'), 1);
% not_xfps = 1-execute('fpslevel='+levels(19))
fpslevel = eval(levels(20),'101');
% 
% bad_fps_level = (fpslevel lt 0) or (fpslevel gt 100) or not_xfps
bad_fps_level = fpslevel < 0 || fpslevel > 100;
% 
% if ((bad_levels(0) ne -1) or (bad_fps_level eq 1)) then begin
if ~isempty(bad_levels) || bad_fps_level == 1
%    print,'Invalid levels ',levels
%    !tcvcs_error = 'ALIM modes : ERROR ON levels'
%    print,'_-_- '+stime()+' ALIM_MODE: aborted'
%    return
 error('Invalid levels')
% endif
end
% 
% modes = strupcase(modes)
modes = upper(modes);
% bad_modes=where((modes ne 'A') and (modes ne 'B') and (modes ne 'C'))
bad_modes = find((~strcmp(modes,'A') && ~strcmp(modes,'B') && ~strcmp(modes,'C')), 1);
% if (bad_modes(0) ne -1) then begin
if ~isempty(bad_modes)
%    print,'Invalid modes ',modes
%    !tcvcs_error = 'ALIM modes : ERROR ON modes'
%    print,'_-_- '+stime()+' ALIM_MODE: aborted'
%    return
 error('Invalid modes ')
% endif
end
% 
% bad_selects=where((selects ne 'ON') and (selects ne 'OFF'))
bad_selects = find(~strcmp(selects,'ON') && ~strcmp(selects,'OFF'), 1);
% if (bad_selects(0) ne -1) then begin
if ~isempty(bad_selects)
%    print,'Invalid selects ',selects
%    !tcvcs_error = 'ALIM_MODE : ERROR ON selects'
%    print,'_-_- '+stime()+' ALIM_MODE: aborted'
%    return
 error('Invalid selects ')
% endif
end
% 
% if (strtrim(!tcvcs_error) ne '') then return
% 
% print,'_-_- '+stime()+' ALIM_MODE: opening TCV_SHOT model'
% ; write out to the PCS tree and print action
% mds$open,'tcv_shot',-1
mdsopen('TCV_SHOT',-1)
% 
% print,'_-_- '+stime()+' ALIM_MODE: writing modes'
% mds$put,'\PCS::ALIM_MODES',  '$',modes
mdsput('\PCS::ALIM_MODES',modes)
% print,'_-_- '+stime()+' ALIM_MODE: writing levels'
% mds$put,'\PCS::ALIM_LEVELS', '$',levels
mdsput('\PCS::ALIM_LEVELS',levels)
% print,'_-_- '+stime()+' ALIM_MODE: writing selects'
% mds$put,'\PCS::ALIM_SELECTS','$',selects
mdsput('\PCS::ALIM_SELECTS',selects)
% 
% format='(20a4)'
% print,'Modes / Levels / Selects = '
% print,modes,  format=format
% print,levels, format=format
% print,selects,format=format
% 
% if (n_params() eq 4) then begin
if nargin == 4
%   mds$put,'\PCS::LOAD_SIGN_BITS','$',signbit
 mdsput('\PCS::LOAD_SIGN_BITS',signbit)
%   print,'Initial signs for currents are: '
%   print,signbit(0:7)
%   print,signbit(8:15)
%   print,signbit(16:17)
% endif
end
% 
% print,'_-_- '+stime()+' ALIM_MODE: finished'
% 
% end
end

% pro liuqe_params
 function liuqe_params
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; TCVCS RECIPE ROUTINE
% 
% ; This routine is part of the TCVCS Recipe concept.
% ; As such, it must be guaranteed to have been tested.
% ; ALL modifications to this routine must be checked off
% ; on a new listing of the module.
% 
% ; Updated/Reason:
% 
% ; Controlled by :       SC
% 
% ; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
% 
% ; *****************************************************
% 
% ; Stefano Coda May 2000
% ;	Last modified 29/08/01
% 
% ;	Sets up Liuqe parameters based on programmed (MGAMS) plasma shape
% ;
% 
% on_error,2
% 
% ; make sure model is still open
% mds$open,'tcv_shot',-1
mdsopen('TCV_SHOT',-1)
% 
% print,'Setting Liuqe parameters'
% nequil=mds$value('\pcs::mgams.data:numeq')
nequil=mdsdata('\PCS::MGAMS.DATA:NUMEQ');
% if nequil lt 1 then begin
if nequil < 1
%   message, 'numeq < 1!'
%   goto, def_params
 liuqe_def_params
 return
% endif
end
% iansha=mds$value('\pcs::mgams.data:iansha')
iansha=mdsvalue('\PCS::MGAMS.DATA:IANSHA');
% rlia1=mds$value('\pcs::mgams.data:rlia1')
rlia1=mdsdata('\PCS::MGAMS.DATA:RLIA1');
% zlia1=mds$value('\pcs::mgams.data:zlia1')
zlia1=mdsdata('\PCS::MGAMS.DATA:ZLIA1');
% ilia=mds$value('\pcs::mgams.data:ilia')
ilia=mdsdata('\PCS::MGAMS.DATA:ILIA');
% rlim1=mds$value('\pcs::mgams.data:rlim1')
rlim1=mdsdata('\PCS::MGAMS.DATA:RLIM1');
% zlim1=mds$value('\pcs::mgams.data:zlim1')
zlim1=mdsdata('\PCS::MGAMS.DATA:ZLIM1');
% ilie=mds$value('\pcs::mgams.data:ilie')
ilie=mdsdata('\PCS::MGAMS.DATA:ILIE');
% rmajo1=mds$value('\pcs::mgams.data:rmajo1')
rmajo1=mdsdata('\PCS::MGAMS.DATA:RMAJO1');
% rmino1=mds$value('\pcs::mgams.data:rmino1')
rmino1=mdsdata('\PCS::MGAMS.DATA:RMINO1');
% zmajo1=mds$value('\pcs::mgams.data:zmajo1')
zmajo1=mdsdata('\PCS::MGAMS.DATA:ZMAJO1');
% cappa1=mds$value('\pcs::mgams.data:cappa1')
cappa1=mdsdata('\PCS::MGAMS.DATA:CAPPA1');
% rout=fltarr(nequil)
% rin=fltarr(nequil)
% zhigh=fltarr(nequil)
% zlow=fltarr(nequil)
% kappa=fltarr(nequil)
[rout,rin,zhigh,zlow,kappa] = deal(zeros(nequil,1));
% for i=0,nequil-1 do begin
for i = 1:nequil
%     if iansha(i) eq 0 then begin
    if iansha(i) == 0
% ; drawn boundary
%       if ilia(i) ne 0 then begin
      if ilia(i) ~= 0
%         rbou=rlia1(0:ilia(i)-1,i)
        rbou=rlia1(1:ilia(i),i);
%         zbou=zlia1(0:ilia(i)-1,i)
        zbou=zlia1(1:ilia(i),i);
%         if ilie(i) ne 0 then begin
        if ilie(i) ~= 0
%           rbou=[rbou,rlim1(0:ilie(i)-1,i)]
          rbou=[rbou,rlim1(1:ilie(i),i)];
%           zbou=[zbou,zlim1(0:ilie(i)-1,i)]
          zbou=[zbou,zlim1(1:ilie(i),i)];
%         endif
        end
%       endif else begin
      else
% 	if ilie(i) eq 0 then begin
	       if ilie(i) == 0
% 	  message, 'Equilibrium # '+arr2str(i+1)+': iansha=0, ilia=0, ilie=0!'
% 	  goto, def_params
	         liuqe_def_params
          return
% 	endif
        end
%         rbou=rlim1(0:ilie(i)-1,i)
        rbou=rlim1(1:ilie(i),i);
%         zbou=zlim1(0:ilie(i)-1,i)
        zbou=zlim1(1:ilie(i),i);
%       endelse
      end
% ; attempt to eliminate points lying beyond X-points for diverted plasmas
%       rbou=rbou(sort(zbou))
%       zbou=zbou(sort(zbou))
     [~,k] = sort(zbou);
     rbou = rbou(k);
     zbou = zbou(k);
% slim_it:
    while 1
%       zave=total(zbou)/n_elements(zbou)
      zave=mean(zbou);
%       rave=total(rbou)/n_elements(rbou)
      rave=mean(rbou);
%       sqrad=(zbou-zave)^2+(rbou-rave)^2
      sqrad=(zbou-zave).^2+(rbou-rave).^2;
%       if total(sqrad)/n_elements(sqrad) gt 1.15*median(sqrad) then begin
      if mean(sqrad) > 1.15*median(sqrad)
%         if abs(zbou(0)-zave) gt abs(zbou(n_elements(zbou)-1)-zave) then begin
        if abs(zbou(1)-zave) > abs(zbou(end)-zave)
%           rbou=rbou(1:n_elements(rbou)-1)
          rbou=rbou(2:end);
%           zbou=zbou(1:n_elements(zbou)-1)
          zbou=zbou(2:end);
%         endif else begin
        else
%           rbou=rbou(0:n_elements(rbou)-2)
          rbou=rbou(1:end-1);
%           zbou=zbou(0:n_elements(zbou)-2)
          zbou=zbou(1:end-1);
%         endelse
        end
%         goto,slim_it
%       endif
      else
       break
      end
    end
%       rout(i)=max(rbou)
      rout(i)=max(rbou);
%       rin(i)=min(rbou)
      rin(i)=min(rbou);
%       zhigh(i)=max(zbou)
      zhigh(i)=max(zbou);
%       zlow(i)=min(zbou)
      zlow(i)=min(zbou);
%       kappa(i)=(zhigh(i)-zlow(i))/(rout(i)-rin(i))
      kappa(i)=(zhigh(i)-zlow(i))/(rout(i)-rin(i));
%       meanrad=sqrt(total(sqrad)/n_elements(sqrad))
      meanrad=sqrt(mean(sqrad));
%       rout(i)=rout(i)+0.02*sqrt(meanrad/kappa(i))
      rout(i)=rout(i)+0.02*sqrt(meanrad/kappa(i));
%       rin(i)=rin(i)-0.02*sqrt(meanrad/kappa(i))
      rin(i)=rin(i)-0.02*sqrt(meanrad/kappa(i));
%       zhigh(i)=zhigh(i)+0.02*sqrt(meanrad*kappa(i))
      zhigh(i)=zhigh(i)+0.02*sqrt(meanrad*kappa(i));
%       zlow(i)=zlow(i)-0.02*sqrt(meanrad*kappa(i))
      zlow(i)=zlow(i)-0.02*sqrt(meanrad*kappa(i));
%     endif else begin
else
% ; analytic boundary
%       rout(i)=rmajo1(i)+rmino1(i)*1.02
      rout(i)=rmajo1(i)+rmino1(i)*1.02;
%       rin(i)=rmajo1(i)-rmino1(i)*1.02
%       zhigh(i)=zmajo1(i)+rmino1(i)*cappa1(i)*1.02
      zhigh(i)=zmajo1(i)+rmino1(i)*cappa1(i)*1.02;
%       zlow(i)=zmajo1(i)-rmino1(i)*cappa1(i)*1.02
      zlow(i)=zmajo1(i)-rmino1(i)*cappa1(i)*1.02;
%       kappa(i)=cappa1(i)
      kappa(i)=cappa1(i);
%     endelse
    end
% endfor
end
% 
% nelem=max([3,min([12,2*round(2*max(kappa))]),3])
nelem=max([3,min([12,2*round(2*max(kappa))]),3]);
% rop=max(rout)
rop=max(rout);
% rip=min(rin)
rip=min(rin);
% zup=max(zhigh)
zup=max(zhigh);
% zlp=min(zlow)
zlp=min(zlow);
% 
% ; Liuqe 1
% mds$put,'\results::parameters:nelem',arr2str(nelem)
% mds$put,'\results::parameters:rop',arr2str(rop)
% mds$put,'\results::parameters:rip',arr2str(rip)
% mds$put,'\results::parameters:zup',arr2str(zup)
% mds$put,'\results::parameters:zlp',arr2str(zlp)
% ; Liuqe 2
% mds$put,'\results::parameters_2:nelem',arr2str(nelem)
% mds$put,'\results::parameters_2:rop',arr2str(rop)
% mds$put,'\results::parameters_2:rip',arr2str(rip)
% mds$put,'\results::parameters_2:zup',arr2str(zup)
% mds$put,'\results::parameters_2:zlp',arr2str(zlp)
% ; Liuqe 3
% mds$put,'\results::parameters_3:nelem',arr2str(nelem)
% mds$put,'\results::parameters_3:rop',arr2str(rop)
% mds$put,'\results::parameters_3:rip',arr2str(rip)
% mds$put,'\results::parameters_3:zup',arr2str(zup)
% mds$put,'\results::parameters_3:zlp',arr2str(zlp)
for i = 1:3
 if i == 1, tmp = '';
 else       tmp = ['_' int2str(i)]; end
mdsput(['\RESULTS::PARAMETERS:NELEM' tmp],arr2str(nelem))
mdsput(['\RESULTS::PARAMETERS:ROP' tmp],arr2str(rop))
mdsput(['\RESULTS::PARAMETERS:RIP' tmp],arr2str(rip))
mdsput(['\RESULTS::PARAMETERS:ZUP' tmp],arr2str(zup))
mdsput(['\RESULTS::PARAMETERS:ZLP' tmp],arr2str(zlp))
end
% 
% goto,done
% 
% def_params:
function liuqe_def_params
% ; on error, set standard Liuqe parameters
% 
% message, 'Parameter optimization has failed: setting standard Liuqe parameters'
% 
% mds$put,'\results::parameters:nelem','12'
% mds$put,'\results::parameters:rop','1.12'
% mds$put,'\results::parameters:rip','0.63'
% mds$put,'\results::parameters:zup','0.73'
% mds$put,'\results::parameters:zlp','-0.73'
% 
% mds$put,'\results::parameters_2:nelem','12'
% mds$put,'\results::parameters_2:rop','1.12'
% mds$put,'\results::parameters_2:rip','0.63'
% mds$put,'\results::parameters_2:zup','0.73'
% mds$put,'\results::parameters_2:zlp','-0.73'
% 
% mds$put,'\results::parameters_3:nelem','12'
% mds$put,'\results::parameters_3:rop','1.12'
% mds$put,'\results::parameters_3:rip','0.63'
% mds$put,'\results::parameters_3:zup','0.73'
% mds$put,'\results::parameters_3:zlp','-0.73'
for l = 1:3
 if l == 1, tmp = '';
 else       tmp = ['_' int2strl(l)]; end
mdsput(['\RESULTS::PARAMETERS:NELEM' tmp],12)
mdsput(['\RESULTS::PARAMETERS:ROP' tmp],1.12)
mdsput(['\RESULTS::PARAMETERS:RIP' tmp],0.63)
mdsput(['\RESULTS::PARAMETERS:ZUP' tmp],0.73)
mdsput(['\RESULTS::PARAMETERS:ZLP' tmp],-0.73)
end
end
%
% done:
% 
% print,'nelem = ',nelem
% print,'rop = ',rop
% print,'rip = ',rip
% print,'zup = ',zup
% print,'zlp = ',zlp
% 
% print,'liuqe_params completed'
% end
end



