function []=test_qucsconv()
%
%convert CSV to QucsStudio data
%

old_dir=pwd;

Rnum=6;
csvfile_name=['R',int2str(Rnum),'.csv'];
read_dir='D:\hicumL2\CSV_data';
dataf=fullfile(read_dir,csvfile_name);
sep=' ';

qsfun='C:\Programme\QucsStudio_332\QucsStudio\bin\qucsconv.exe';
full_prj='C:\Documents and Settings\zhu\qucs3\DC_prj';
outfile_name=['full_R',int2str(Rnum),'.dat'];
targetfile=fullfile(full_prj,outfile_name);

[header_line,data]=csvreadh(dataf,sep); %header_line is cell array, data is matrix
outfile=fullfile(full_prj,outfile_name);
cd(read_dir);
infil=[' -i ',csvfile_name];

%============ run_inXP=1; works, run_inXP=0; does not work in WIN XP ============
run_inXP=1;
if run_inXP
  outfil=[' -o ',outfile_name];
  dostxt=[qsfun,infil,' -if csv -of qucsdata ',outfil],
  dos(dostxt);
  %relocate *.dat file to full_prj (qucsconv does not accept spaces in path)
  dostxt=['copy ',outfile_name,' ',['"',targetfile,'"']];
  dos(dostxt);
  dostxt=['del /q ',outfile_name];
  dos(dostxt)
else
  dostxt=[qsfun,infil,' -if csv -of qucsdata ',targetfile],
  %dostxt=[qsfun,infil,' -if csv -of qucsdata ',['"',targetfile,'"']],  %neither works
  dos(dostxt);
end
%============ run_inXP=1; works, run_inXP=0; does not work in WIN XP ============

cd(old_dir);

return
%========================= subfunctions ============================
function [varnames,data]=csvreadh(cfile,sep);
%
%read csv file with header
%
%cfile:     filename with full path
%varnames:  cell array of variable names
%data:      data matrix of columns in sequence of the variables
%sep:       separation character in header
%
%csv structure:
%area	4xtr	7xtr	Gobert_Ib	Gobert_Ic
%0.262	38.27	36.78	35.69	28.52
%0.442	23.53	22.08	21.67	17.34
%
%Example: [varnames,data]=csvreadh('D:\Archives\Eigene_dat\Doc\Didier\QucsStudio_optim\Reports\rcx_xtr.csv')
%
% @(#) csvreadh.m  1.0 (C) Z. Huszka 11-Jan-2020
%

fid=fopen(cfile,'r');
head=fgetl(fid);
head=strrep(head,'"','');
sor1=fgetl(fid);
fclose(fid);
if nargin==1
  sep=' ';
end
varnames=strsplit(head,sep);
numvar=length(varnames);
B=textread(cfile,'%f','headerlines',1,'delimiter',sep);
data=reshape(B,numvar,[])';

return
%========================= subfunctions ============================  
function scell=strsplit(str,sep)
%
%split str using separator sep into a cell array of strings
%
%simplified form of OCTAVE function under the same name
%
%Example:
%         scel=strsplit('Vbe,Vcb,gm');
%         scell='Vbe'    'Vcb'    'gm'
%
% @(#) strsplit.m  1.0 (C) Z. Huszka 24-Nov-2019
%

idx = find(str == sep);
strlens = [idx(1)-1, diff(idx)-1, numel(str)-idx(end)];
%omit sep repetitions
strlens = strlens(strlens ~= 0);
%remove separators
str(idx) = [];
scell = mat2cell(str, 1, strlens);

return
%========================= subfunctions ============================
