function num = dspace2latex(dspacename,texname)
%------------------------------------------------
%num = dspace2tex(data,xname,downsample,filename)
%Function to export a dSPACE-mat-file to a tex-file for using NumericPlots. 
%dspace2latex is based on the function struct2tex and export2latex.
%------------------------------------------------
%output:
%num        ...number of y-data exported
%input:
%dspacename ...dspace file name (optional, default io)
%texname    ...name of the tex-file (optional, default io)
%
%author: Alexander Michel
% date: 2010/08/09
%
% function struct2latex.m required to convert structs to export2latex format.
% function export2latex.m required to export datavectors to latex.
%

% Copyright 2010 Thomas König, Alexander Michel
%
% This file is part of NumericPlots.
%
% NumericPlots is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% any later version.
% 
% NumericPlots is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with NumericPlots.  If not, see <http://www.gnu.org/licenses/>.



% choose dSpace File
if(nargin<1)
    data = dspace2struct;
else
    data = dspace2struct(dspacename);
end


% define begin, end and downsampling
options.Resize='on';
options.WindowStyle='normal';
options.Interpreter='tex';
prompt={'t0','t1','downsampling'};
title=['define datapoints. sampling time = ' num2str(data.time(2)-data.time(1)) ' s'];
numlines=1;
defaultanswer={num2str(data.time(1)),num2str(data.time(end)),'1'};
 
answer=inputdlg(prompt,title,numlines,defaultanswer,options);
starttime = str2double(answer{1});
endtime = str2double(answer{2});
downsample = str2double(answer{3});

% define downsampling
istart = find(data.time<=starttime);
istart = istart(end);
iend = find(data.time<=endtime);
iend = iend(end);

idx = istart:downsample:iend;

% choose data which should be exportet
fnames = fieldnames(data);
idxtimename = strmatch('time',fnames,'exact');
idxdatanames = setdiff(1:length(fnames),idxtimename);

[iplots,selected] = listdlg('PromptString','choose data for export:','ListString',fnames(idxdatanames));
if (selected==0)
 error('no data chosen');
end

dat.time = data.time;
for ii = iplots
    dat = setfield(dat,fnames{ii},getfield(data,fnames{ii}));
end

% export data
if(nargin<2)
    num = struct2latex(dat,'time',downsample);
else
    num = struct2latex(dat,'time',downsample,texname);
end
    