function [torbeam_out_struct, file_out_prefix]=run_torbeam_fullshot(shot,varargin);
%
%     [torbeam_out_struct, file_out_prefix]=run_torbeam_fullshot(shot,varargin);
%
% Run tbdemo, using line command execution of TORBEAM, to run torbeam acroos full shot on reduced time axis
%
% shot: shot number for which to run Torbeam. 
%       If empty or not given, ask for it
%       if negative, assume output file exists, do not re-run TORBEAM and just reads data into structure torbeam_out_struct
%
% varargin given in pairs: 'keyword', value
%    'time',time_array: time points for which to run Torbeam (by default run every 50ms for each ECRH2 gyrotron having power>0)
%    'file_prefix', filename_prefix: results are saved on [filename '_gyroXX.dat'] (default: tbdemo_shot_gyroXX.dat with XX being the gyro nb)
%
% Examples:
%      torbeam_out_struct = run_torbeam_fullshot(shot);   % standard call to run Torbeam
%      torbeam_out_struct = run_torbeam_fullshot(-shot);  % standard call to just read the data from the local file from a previous run
%
%      torbeam_out_struct = run_torbeam_fullshot(shot,'time',linspace(tstart,tend,nbpoints)); % to run on given time array
%      torbeam_out_struct = run_torbeam_fullshot(shot,'time',[t1 t2 t3...],'file_prefix','tbdemo_shot_fewtimes_gyro'); % to run on specific times

torbeam_out_struct = [];

if ~exist('shot')
  shot=input('shot: ');
end

time_array=linspace(0,10,10/0.05);
file_out_prefix = ['tbdemo_' num2str(abs(shot)) '_gyro'];

if nargin>=3 && mod(length(varargin),2)==0
  for i=1:2:length(varargin)-1
    if ~isempty(varargin{i}) && ~isempty(varargin{i+1})
      switch lower(varargin{i})
       case {'time'}
	time_array = varargin{i+1};
       case {'file_prefix'}
	file_out_prefix = varargin{i+1};
       otherwise
	disp(['case ' lower(varargin{i}) ' not yet implemented, ask Olivier.Sauter@epfl.ch'])
	return
      end
    end
  end
end

if shot>0
  pgyro=gdat(shot,'pgyro',1);

  hhDCR = sfread('DCR', shot);
  dousedcr = '';
  if hhDCR.handle~=0;
    dousedcr = '-usedcr';
    disp('can usedcr since DCR shotfile exists');
  else
    disp('do not use dcr since DCR shotfile does not seem to exists')
  end

  run_with_IDA = 0;
  % test if IDA present
  hhIDA = sfread('IDA', shot);
  dousebetapol = '-betapol';
  if hhIDA.handle~=0;
    netest=gdat(shot,'IDA/ne');
    tetest=gdat(shot,'IDA/te');
    if ~isempty(netest.data) && ~isempty(tetest.data)
      run_with_IDA = 1;
      dousebetapol = ''; % can use Te from IDA
      dousedcr = ''; % can use ne from IDA
      disp('use IDA since shotfile exists')
    else
      disp('do not use IDA since shotfile does not seem to exist')
    end
  else
    disp('do not use IDA since shotfile does not seem to exist')
  end
  
  for igyro=1:8
    filename=[file_out_prefix num2str(igyro) '.dat'];
    unix(['rm ' filename ' >& /dev/null']); % since cannot write over an existing file by default
    unix(['rm ' '.' filename ' >& /dev/null']); % since cannot write over an existing file by default
    unix(['touch ' '.' filename]);
    itt=find(pgyro.data(:,igyro)>1e5);
    if ~isempty(itt)
      itt_tok=find(time_array>=pgyro.t(itt(1)) & time_array<=pgyro.t(itt(end)));
      if ~isempty(itt_tok)
	pgyro_tok=interp1(pgyro.data(itt,igyro),time_array(itt_tok));
	disp(['running system ' num2str(igyro) '...']);
	for j=1:length(itt_tok)
	  if pgyro_tok(j)>1e5
	      [a,b]=unix(['~rem/public/tbm_demo/tbmdemo -batch -silent -shot ' num2str(shot) ' -time ' num2str(time_array(itt_tok(j))) ' -system ' num2str(igyro) ' -ntm ' dousedcr ' ' dousebetapol ' -eqdiag EQH  -usemirror -cdrive 1 >> ' ['.' filename]]); % -exp AUGE
	  end
	end
	[a,b]=unix(['egrep -e ''^Shot''' ' .' filename ' > ' filename]);
      end
    end
  end
end

for igyro=1:8
  try
    eval(['[shot_tbnam,tbout{igyro}.shot,time_tbnam,tbout{igyro}.time,gyro_tbnam,tbout{igyro}.gyro,pol_tbnam,tbout{igyro}.pol,tor_tbnam,tbout{igyro}.tor,' ...
	  'pow_tbnam,tbout{igyro}.pow,r_tbnam,tbout{igyro}.r,z_tbnam,tbout{igyro}.z,rho_tbnam,tbout{igyro}.rhopol_dep,pwr_dep_tbnam,tbout{igyro}.rhopol_pwr_dep,rhopol_cd_dep_tbnam,tbout{igyro}.rhopol_cd_dep,pdens_peak_tbnam,' ...
	  'tbout{igyro}.pdens_peak,rhopol_pdens_wid_tbnam,tbout{igyro}.rhopol_pdens_width,jcd_peak_tbnam,tbout{igyro}.jcd_peak,rhopol_c_wid_tbnam,tbout{igyro}.rhopol_jcd_width,pni_tbnam,tbout{igyro}.pni,picr_tbnam,tbout{igyro}.picr,prad_tbnam,tbout{igyro}.prad,' ...
	  'betan_tbnam,tbout{igyro}.betan,ipl_tbnam,tbout{igyro}.ipl,bt_tbnam,tbout{igyro}.bt,a1_tbnam,tbout{igyro}.ampN1,a2_tbnam,tbout{igyro}.ampN2,rhopolntm_tbnam,tbout{igyro}.rhopolntm]=' ...
	  'textread(''' file_out_prefix  num2str(igyro) '.dat'',''%s%d%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f'');']);

    %     eval(['[gyro_tbnam,tbout{igyro}.gyro,shot_tbnam,tbout{igyro}.shot,time_tbnam,tbout{igyro}.time,pol_tbnam,tbout{igyro}.pol,tor_tbnam,tbout{igyro}.tor,' ...
    %     'pow_tbnam,tbout{igyro}.pow,r_tbnam,tbout{igyro}.r,z_tbnam,tbout{igyro}.z,pwr_dep_tbnam,tbout{igyro}.rhopol_pwr_dep,rhopol_cd_dep_tbnam,tbout{igyro}.rhopol_cd_dep,jcd_peak_tbnam,' ...
    %     'tbout{igyro}.jcd_peak,rhopol_c_wid_tbnam,tbout{igyro}.rhopol_c_wid,pni_tbnam,tbout{igyro}.pni,picr_tbnam,tbout{igyro}.picr,prad_tbnam,tbout{igyro}.prad,' ...
    % 	  'betan_tbnam,tbout{igyro}.betan,ipl_tbnam,tbout{igyro}.ipl,bt_tbnam,tbout{igyro}.bt,a1_tbnam,tbout{igyro}.a1,a2_tbnam,tbout{igyro}.a2,rhopolntm_tbnam,tbout{igyro}.rhopolntm]=' ...
    %	  'textread(''' file_out_prefix  num2str(igyro) '.dat'',''%s%d%s%d%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s%f'');']);

  catch
    disp(['problems reading file ' file_out_prefix  num2str(igyro) '.dat: may be some errors with tbdemo, check file, skipped'])
  end
end

if exist('tbout');
  torbeam_out_struct = tbout;
end

fig_handles=plot_torbeam(torbeam_out_struct);


% comments for hiytory backup:
% 	    [a,b]=unix(['ssh sxaug21.aug.ipp.mpg.de ~rem/public/tbm_demo/tbmdemo -batch -silent -shot ' num2str(shot) ' -time ' num2str(time_array(itt_tok(j))) ' -system ' num2str(igyro) ' -usedcr -eqdiag EQI -betapol -usemirror -cdrive 1 >> ' ['.' filename]]);

%	      [a,b]=unix(['ssh sxaug21.aug.ipp.mpg.de ~rem/public/tbm_demo/tbmdemo -batch -silent -shot ' num2str(shot) ' -time ' num2str(time_array(itt_tok(j))) ' -system ' num2str(igyro) ' -ntm -usedcr -eqdiag EQI -betapol -usemirror -cdrive 1 >> ' ['.' filename]]);

% -shot 29672 -time 3.0 -system 5 -batch -ntm -silent -usemirror -cdrive 1
%	      [a,b]=unix(['ssh sxaug21.aug.ipp.mpg.de ~rem/public/tbm_demo/tbmdemo -batch -silent -shot ' num2str(shot) ' -time ' num2str(time_array(itt_tok(j))) ' -system ' num2str(igyro) ' -ntm -usemirror -cdrive 1 >> ' ['.' filename]]);

% [a,b]=unix(['grep -v ''could not''' ' .' filename '| grep -v ''invalid'' | grep -v ''Error'' | egrep -e ''^$'' -v > ' filename]);
