function write(h)

%% Find and open the file
filepath = fullfile(h.Path,h.Filename);
mfilepath = sprintf('%s.m',filepath);
[fid,msg] = fopen(mfilepath,'w');
if ~isempty(msg)
    error('recorder:write:noopen','Cannot open file')
end

%% Write the file header
fprintf(fid,'%s','function ');
if length(h.Tsoutnames)>0
    fprintf(fid,'%s','[');
    for k=1:length(h.Tsoutnames)-1
        fprintf(fid,'%s',sprintf('%s,',h.Tsoutnames{k}));
    end
    fprintf(fid,'%s',sprintf('%s] = ',h.Tsoutnames{end}));
end 
fprintf(fid,'%s',h.Filename);
if length(h.Tsnames)>0
    fprintf(fid,'%s','(');
    for k=1:length(h.Tsnames)-1
        fprintf(fid,'%s,',h.Tsnames{k});
    end
    fprintf(fid,'%s)',h.Tsnames{end});
end
fprintf(fid,'\n\n%s',sprintf('%s Time Series Tool Auto Generated M file: %s\n',...
    '%%',datestr(now)));

%% If a MAT file has been used to store indices then load it
matfilepath = sprintf('%s.mat',filepath);
if exist(matfilepath)==2 && strcmp(h.Saveddata,'on')
    fprintf(fid,'%s',sprintf('load %s;\n',matfilepath));
end

%% Loop through the undo stack and write the contents of each transaction
%% buffer to the logged M file
for k=1:length(h.Undo)
    thistrans = h.Undo(k);
    for j=1:length(thistrans.Buffer)
        fprintf(fid,'%s',sprintf('%s\n',thistrans.Buffer{j}));
    end
    % Clear buffer
    thistrans.Buffer = {};
end

%% Update the macrostack - do nothing if the macro is empty
if length(h.Tsnames)>0
    I = find(strcmp(h.Filename,h.Macrostack(:,1)));
    if ~isempty(I) && length(h.Tsnames)
        h.Macrostack{I(1),2} = sprintf('%d-in by %d-out',...
            length(h.Tsnames),length(h.Tsoutnames));
        awtinvoke(h.Dialog.COMBMfile,'removeAllItems');
        for k=1:size(h.Macrostack,1)
            awtinvoke(h.Dialog.COMBMfile,'addItem(Ljava/lang/Object;)',...
                java.lang.String(h.Macrostack{k,1}));
        end
    else
        h.Macrostack = [h.Macrostack; {h.Filename,sprintf('%d-in by %d-out',...
            length(h.Tsnames),length(h.Tsoutnames))}];
        awtinvoke(h.Dialog.COMBMfile,'addItem(Ljava/lang/Object;)',java.lang.String(h.Filename))
    end
end

%% Clear in/out time series names
h.Tsnames = {};
h.Tsoutnames = {};

%% Close the file and update the path
fclose(fid);
rehash toolboxcache

%% Edit the file
edit(mfilepath);
