function out = pulse2sdt(varargin);

%PULSE2SDT interface between SDT and Bruel&Kjaer Pulse software
%
%  Note that you can also use PULSE universal file export capabilities
%  and read the data using UFREAD.
%
%  Accepted commands are 
%
%  pulse2sdt(Group1) : converts datasets read with the BridgeTo Matlab
%       to SDT format. By default the dataset is displayed with iiplot,
%       if you wish something else use an output argument.
%
%  pulse2sdt('read') : lets you select a PulseAscii file and displays the 
%       result using iiplot. This requires the Bridge to Matlab 
%       http://www.bksv.com/bksv/?MIval=bk_view_Document&ID=973
%
%
%  This function is provided free of charge but without any warranty.
%  Please send bug reports to mailto:bug@sdtools.com

%	Etienne Balmes  22/01/02
%       Copyright (c) 20002 by SDTools
%       All Rights Reserved.


CAM=varargin{1}; carg=1; 

if isstr(CAM) [CAM,Cam]=comstr(CAM,1); end



% ----------------------------------------------------------------------
% Convert GetPulseAsciiFile to UFS format
if isstruct(CAM)&isfield(CAM,'Function1') 

st0=fieldnames(CAM);

if nargout==0 iiplot; iigui('XF'); r1=XF(1);
else
  out=sdth('XF');
  r1=struct('w',[],'xf',[],'dof',[],'fun',[],'idopt',[], ...
    'header',[],'x',[],'yn',[],'yd',[],'z',[]);
end


xf=[];
for j1=1:length(st0)
 r2=getfield(CAM,st0{j1});

 % Header information
 st=comstr(r2.Name,1);r1.header(1,1:length(st),j1)=st;
 st=comstr(sprintf('%s %s', ...
      r2.DatasetSection.Date{1},r2.DatasetSection.Time{1}),1);
 r1.header(3,1:length(st),j1)=st;
 st=comstr(r2.Attributes.Title1,1); r1.header(2,1:length(st),j1)=st;

 % Unit labels
 r1.x=struct('type',[0 0 0],'label','','unit',r2.Attributes.X_Axis_unit);
 r1.yn=struct('type',[0 0 0],'label',r2.Attributes.Signal, ...
              'unit',r2.Attributes.SignalUnit);
 if isfield(r2.Attributes,'Ref_Signal')
  r1.yd=struct('type',[0 0 0],'label',r2.Attributes.Ref_Signal, ...
              'unit',r2.Attributes.RefSignalUnit);
 else
  r1.yd=struct('type',[0 0 0],'label','None','unit','');
 end
 r1.z=struct('type',[0 0 0],'label','','unit',r2.Attributes.Z_Axis_unit);

 w=r2.DatasetSection.X_axis(:);
 xf(:,j1)=r2.DatasetSection.Data(:);

end

if nargout==0 
 if isstr(r1.w) eval(sprintf('global %s;%s=w;',r1.w,r1.w));else r1.w=w;end
 if isstr(r1.xf) eval(sprintf('global %s;%s=xf;',r1.xf,r1.xf));
 else r1.xf=xf;end
 XF(1)=r1; iicom('sub');
else r1.w=w; r1.xf=xf; out.vfields{1}=r1; end

% ----------------------------------------------------------------------
% Read a 
elseif comstr(Cam,'read')

 [FileName,FilePathName]=uigetfile('*.txt','Read Pulse Ascii file :');
 [fid,mes] = fopen([FilePathName FileName]);
 eval('r1=GetPulseAsciiFile(fullfile(FilePathName,FileName));', ...
      'disp(lasterr); error(''GetPulseAsciiFile failed'');');
 if nargout==0 pulse2sdt(r1); else out=pulse2sdt(r1);end

% ------------------------------------------------------------------------
else error('Not a supported command'); 
end

