function write_tsd(filename,t,dat,name,curvetype)
% Writes a Time Series Data file 
%
% Usage:
%  write_tsd(filename,t,dat,name,curvetype)
%
% written by Alex Sanchez, USACE-CHL
str = datestr(t(1),'mm/dd/yyyy HH:MM:SS');
t = (t(:)-t(1))*3600;
t = rounddec(t,3); %round to avoid precision errors
nrow = length(t);
if nargin<4
     name = 'Sample'; 
end
if nargin<5
    curvetype = 'Unassigned';
end
fid = fopen(filename,'w');
fprintf(fid,'TIME_SERIES\r');
if size(dat,1)~=nrow %Input dataset is transposed
    dat = dat';
end
ncol = size(dat,2)+1;
fprintf(fid,'"%s"      "%s"      %d      %d     "%s"\n',...
    name,curvetype,ncol,nrow,str);
f = ' %16.2f';
for k=1:ncol-1
    f = [f,' %10.3f'];
end
f = [f,'\r'];
fprintf(fid,f,[t,dat]');
fclose(fid);
return