%
% Assume "out" in workspace and cheasedata files in cheasedata_dir
%
% Recomputes equilibria from plasma boundary in cheasedata.eqdsk and pressure and j.B profiles from RAPTOR
% Recompute for the same times as the input eqdsks
%

if ~exist('out','var') || ~isstruct(out)
  disp('out is not a local variable or a structure. Load it first')
  return
end

cheasedata_dir = '.';
do_rerun_chease = 0;

% get filenames
ls_cheasedata = ls(fullfile(cheasedata_dir,'*_t*cheasedata*.mat'),'-1');
ij_t=findstr(ls_cheasedata,'_t');
ij_cheasedata=findstr(ls_cheasedata,'_cheasedata');
ij_1st_slash = findstr(ls_cheasedata,'/');
if isempty(ij_1st_slash); ij_1st_slash(1) = 0; end
header = ls_cheasedata(ij_1st_slash(1)+1:ij_t(1)-1);
clear cheasedata_names cheasedata_times cheasedatas
for i=1:length(ij_t)
  cheasedata_names{i} = [header ls_cheasedata(ij_t(i):ij_cheasedata(i)+14)];
  cheasedata_times(i) = str2num(ls_cheasedata(ij_t(i)+2:ij_cheasedata(i)-1));
  load(cheasedata_names{i});
  cheasedatas{i} = chease_data;
  eqdsks{i} = chease_data.eqdsk;
end

% shift out.time to match cheasedata time (experimental time)
out2=out;
if ~isempty(model.equi.offset)
out2.time = out.time + model.equi.offset-0.2;
end
for it=1:length(cheasedata_times)
  filename = [header '_t' num2str(cheasedata_times(it),'%.2f') '_profs_from_RAPTOR'];
  [expeq_filename{it},tout(it),normalization_infos{it}]=RAPTORout2CHEASE(out2,cheasedata_times(it),filename,cheasedatas{it});
end

%%
do_rerun_chease = 1;
if do_rerun_chease
  [~,~,namelist_struct] = run_chease(1);
  namelist_struct.ncscal = 4;
  namelist_struct.nfunrho = 1;
  for it=1:length(cheasedata_times)
    expq=read_expeq(expeq_filename{it});
    namelist_struct.nppfun = expq.nppfun;
    % may be a bug in chease or not good guess when changing kappa for r0
    % for chease mesh center
    % namelist_struct.r0 = normalization_infos{it}.r0_mean_r/normalization_infos{it}.r0; % guess rmag is effective r0
    namelist_struct.r0exp = normalization_infos{it}.r0;
    namelist_struct.b0exp = normalization_infos{it}.b0;
    [fname_out{it},globalsvalues{it},namelist_struct_out{it},namelistfile_eff{it}] = run_chease(namelist_struct,expeq_filename{it});
  end
end

%% Generate .mat files
do_mat_file = 0;
if do_mat_file
    for it=1:length(cheasedata_times)
        fno = fname_out{it};
        fname = sprintf('TCV_%d_t%2.2f_equil_RAPTORprof.mat',shot,cheasedata_times(it));
        % give eqdsk out name and o.....cols name to get chease_data
        % find relevant filenames
        for ii=1:length(fno);
          if ~isempty(regexpi(fno{ii},'o.*\.cols','start'))
            fname_ocols = fno{ii};
          end
          if ~isempty(regexpi(fno{ii},'o.*\.RZcols','start'))
            fname_oRZcols = fno{ii};
          end
          if ~isempty(regexpi(fno{ii},'EQDSK_COCOS_02_POS.OUT.*','start'))
            fname_eqdskout = fno{ii};
          end
        end
        [chease_data] = eqdsk_ocols_to_chease_data(fname_eqdskout,fname_ocols,fname); 
    end
end
