function exportsinglefile(h,tsfigure,ts)
% -------------------------------------------------------------------------
%% load default position parameters for all the components
% some of the code in the function is reused by the resize function
% -------------------------------------------------------------------------
import javax.swing.*

% configure filechooser
chooser = com.mathworks.mwswing.MJFileChooser;
% setup file filter to valid export file types
filter=com.mathworks.mwswing.FileExtensionFilter('MAT File', {'mat'}, true);
chooser.setFileFilter(filter);
filter=com.mathworks.mwswing.FileExtensionFilter('Excel Workbook', {'xls'}, true);
chooser.setFileFilter(filter);
awtinvoke(chooser,'setMultiSelectionEnabled',false);
awtinvoke(chooser,'setShowOverwriteDialog',false);
awtinvoke(chooser,'setAcceptAllFileFilterUsed',false);
% show the filechooser
jf=get(tsfigure, 'JavaFrame');
jframe = SwingUtilities.getWindowAncestor(jf.getAxisComponent);
returnVal=chooser.showSaveDialog(jframe);
tmp=get(chooser,'FileFilter');
tmp=cell2mat(get(tmp,'Patterns'));
tmp=tmp(2:end);
if returnVal==com.mathworks.mwswing.MJFileChooser.APPROVE_OPTION
    selectedFile = chooser.getSelectedFile;
    filefullname=(selectedFile.toString.toCharArray)';
    [filePath,fileName,fileExtension,fileVersion] = fileparts(filefullname);
%     if ~isvarname(fileName)
%         errordlg('Invalid file name.','Time Series Tools');
%         return                
%     end        
    if isempty(fileExtension)
        fileExtension=tmp;
    end
    filefullname=fullfile(filePath,[fileName fileExtension]);
    if ~isempty(fileExtension) && strcmpi(fileExtension,'.xls')
        bar=waitbar(10/100,'Exporting Time Series Object(s), Please Wait...','WindowStyle','modal');
        % export to an excel file
        % get information from the desired file
        warning off
        if isempty(dir(filefullname))
            % create a new excel file
            % write general info
            info=localGeneralInfo(ts);
            try
                xlswrite(filefullname,info,ts.name,'A1:B13');            
            catch
                errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                delete(bar);
                warning on
                return                
            end
            waitbar(40/100,bar);
            % write timeseries
            if ts.metadata.Data.GridFirst==1
                try
                    block=[ts.getAbsTime num2cell(ts.data)];
                catch
                    time=localCheckRelativeTime(ts);
                    if iscell(time)
                        block=[time num2cell(ts.data)];
                    else
                        block=[time ts.data];
                    end
                end
                try
                    xlswrite(filefullname,block,ts.name,strcat('A14:',[h.findcolumnletter(size(block,2)) num2str(size(block,1)+13)]));
                catch
                    errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                    delete(bar);
                    warning on
                    return                
                end
            else
                try
                    block=[ts.getAbsTime num2cell(reshape(ts.data,size(ts.data,3),size(ts.data,1)))];
                catch
                    time=localCheckRelativeTime(ts);
                    if iscell(time)
                        block=[time num2cell(reshape(ts.data,size(ts.data,3),size(ts.data,1)))];
                    else
                        block=[time reshape(ts.data,size(ts.data,3),size(ts.data,1))];
                    end
                end
                try
                    xlswrite(filefullname,block,ts.name,strcat('A14:',[h.findcolumnletter(size(block,2)) num2str(size(block,1)+13)]));
                catch
                    errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                    delete(bar);
                    warning on
                    return                
                end
            end
            waitbar(80/100,bar);
            % remove the default sheet
            if ispc 
                try
                    if isempty(h.Handles.Excel)
                        try
                            h.Handles.Excel = actxserver('Excel.Application');
                        catch
                            delete(bar);
                            warning on
                            return
                        end
                        h.Handles.Excel.Visible = 0;
                        h.Handles.oldWorkbooks = h.Handles.Excel.Workbooks;
                    end
                    invoke(h.Handles.oldWorkbooks, 'open', filefullname);
                    h.Handles.Excel.ActiveWorkBook.Sheets.Item(1).Delete;
                    h.Handles.Excel.ActiveWorkBook.Sheets.Item(1).Delete;
                    h.Handles.Excel.ActiveWorkBook.Sheets.Item(1).Delete;
                    h.Handles.Excel.ActiveWorkBook.Save;
                catch
                    ;
                end
                if ~isempty(h.Handles.Excel)
                    invoke(h.Handles.Excel, 'quit'); 
                    invoke(h.Handles.Excel, 'delete'); 
                end
            end
        else
            % excel file exists
            try
                [FileInfo,DES]=xlsfinfo(filefullname);
            catch
                errordlg('This is not a valid excel workbook','Time Series Tools');
                delete(bar);
                warning on
                return
            end
            waitbar(20/100,bar);
            % check if the file is valid
            if isempty(FileInfo)
                errordlg('This is not a valid excel workbook','Time Series Tools');
                delete(bar);
                warning on
                return
            else
                % add into an existing excel file
                if ispc
                    if isempty(h.Handles.Excel)
                        try
                            h.Handles.Excel = actxserver('Excel.Application');
                        catch
                        end
                        if ~isempty(h.Handles.Excel)
                            h.Handles.Excel.Visible = 0;
                            h.Handles.oldWorkbooks = h.Handles.Excel.Workbooks;
                        end
                    end
                    if ~isempty(h.Handles.Excel)
                        invoke(h.Handles.oldWorkbooks, 'open', filefullname);
                        % check export name
                        tsname=ts.name;
                        for i=1:length(DES)
                            if strcmpi(DES{i},ts.name)
                                ButtonName=questdlg('A spreadsheet with the same name as the timeseries object already exists in the excel file.  Do you want to overwrite the existing sheet or create a new sheet?',...
                                    'Duplicated Sheet Detected','Overwrite','Create','Create');
                                switch ButtonName,
                                    case 'Overwrite'
                                        % clear the old sheet
                                        h.Handles.Excel.ActiveWorkBook.Sheets.Item(i).UsedRange.ClearContents
                                        h.Handles.Excel.ActiveWorkBook.Save;
                                    case 'Create'
                                        % create a unique sheet name
                                        j=1;
                                        while 1
                                            j0=j;
                                            tsname=strcat(ts.name,num2str(j));
                                            for k=1:length(DES)
                                                if strcmpi(tsname,DES{k})
                                                    j=j+1;
                                                    break;
                                                end
                                            end
                                            if j==j0
                                                break;
                                            end
                                        end
                                end
                            end
                        end
                        % close activex connection if any
                        invoke(h.Handles.Excel, 'quit'); 
                        invoke(h.Handles.Excel, 'delete'); 
                    end
                end
                % export
                info=localGeneralInfo(ts);
                try
                    xlswrite(filefullname,info,tsname,'A1:B13');            
                catch
                    errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                    delete(bar);
                    warning on
                    return                
                end
                waitbar(40/100,bar);
                if ts.metadata.Data.GridFirst==1
                    try
                        block=[ts.getAbsTime num2cell(ts.data)];
                    catch
                        time=localCheckRelativeTime(ts);
                        if iscell(time)
                            block=[time num2cell(ts.data)];
                        else
                            block=[time ts.data];
                        end
                    end
                    try
                        xlswrite(filefullname,block,tsname,strcat('A14:',[h.findcolumnletter(size(block,2)) num2str(size(block,1)+13)]));
                    catch
                        errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                        delete(bar);
                        warning on
                        return                
                    end
                else
                    try
                        block=[ts.getAbsTime num2cell(reshape(ts.data,size(ts.data,3),size(ts.data,1)))];
                    catch
                        time=localCheckRelativeTime(ts);
                        if iscell(time)
                            block=[time num2cell(reshape(ts.data,size(ts.data,3),size(ts.data,1)))];
                        else
                            block=[time reshape(ts.data,size(ts.data,3),size(ts.data,1))];
                        end
                    end
                    try
                        xlswrite(filefullname,block,tsname,strcat('A14:',[h.findcolumnletter(size(block,2)) num2str(size(block,1)+13)]));
                    catch
                        errordlg(sprintf('%s\n\n%s','Error in writing into the excel workbook :',lasterr),'Time Series Tools');
                        delete(bar);
                        warning on
                        return                
                    end
                end
                waitbar(80/100,bar);
            end
        end
        waitbar(90/100,bar);
        delete(bar);
        warning on
        % show excel file
        if ispc
            try
                eval(['!' filefullname]);
            catch
            end
        end
    elseif ~isempty(fileExtension) && strcmpi(fileExtension,'.txt')
    elseif ~isempty(fileExtension) && strcmpi(fileExtension,'.mat')
        % export to an mat file
        % get information from the desired file
        eval([ts.name '=ts;']);
        if isempty(dir(filefullname))
            % create a new mat file
            eval(['save ' filefullname ' ' ts.name]);
        else
            list=load(filefullname);
            if isfield(list,ts.name) 
                ButtonName=questdlg('A variable with the same name as the timeseries object already exists in the mat file.  Do you want to overwrite the existing variable or abort?',...
                    'Duplicated Sheet Detected','Overwrite','Abort','Overwrite');
                switch ButtonName,
                    case 'Overwrite'
                        eval(['save ' filefullname ' ' ts.name ' -append']);
                    case 'Abort'
                        return
                end
            else
                eval(['save ' filefullname ' ' ts.name ' -append']);
            end
        end
    elseif ~isempty(fileExtension) && strcmpi(fileExtension,'.csv')
    else
    end
end
    
function info=localGeneralInfo(ts)
% write timeseries general info
info=cell(10,2);
info(1,1)={'Time Series Object Name'};
info(1,2)={ts.name};
info(2,1)={''};
info(2,2)={''};
info(3,1)={'Time vector characteristics'};
info(3,2)={''};
info(4,1)={'Length'};
info(4,2)={num2str(length(ts.time))};
% Time vector characteristics
if ~isempty(ts.timeInfo.Startdate)
    if tsIsDateFormat(ts.timeInfo.Format)
        timeasdate = true;
        info(5,1)={'Strat Date'};
        strStartTime=sprintf('%s',datestr(tsunitconv('days',ts.timeInfo.Units)*ts.timeInfo.Start+...
            datenum(ts.timeInfo.Startdate),ts.timeInfo.Format));
        info(5,2)={strStartTime};
        info(6,1)={'End Date'};
        strEndTime=sprintf('%s',datestr(tsunitconv('days',ts.timeInfo.Units)*ts.timeInfo.End+...
            datenum(ts.timeInfo.Startdate),ts.timeInfo.Format));   
        info(6,2)={strEndTime};
        info(7,1)={''};
        info(7,2)={''};
    else
        timeasdate = true;
        info(5,1)={'Strat Date'};
        strStartTime=sprintf('%s',datestr(tsunitconv('days',ts.timeInfo.Units)*ts.timeInfo.Start+...
            datenum(ts.timeInfo.Startdate),'dd-mmm-yyyy HH:MM:SS'));
        info(5,2)={strStartTime};
        info(6,1)={'End Date'};
        strEndTime=sprintf('%s',datestr(tsunitconv('days',ts.timeInfo.Units)*ts.timeInfo.End+...
            datenum(ts.timeInfo.Startdate),'dd-mmm-yyyy HH:MM:SS'));   
        info(6,2)={strEndTime};
        info(7,1)={''};
        info(7,2)={''};
    end
else
    timeasdate = false;
    info(5,1)={'Strat Time'};
    strStartTime=sprintf('%s  %s',num2str(ts.timeInfo.start),ts.timeInfo.units);
    info(5,2)={strStartTime};
    info(6,1)={'End Time'};
    strEndTime=sprintf('%s  %s',num2str(ts.timeInfo.end),ts.timeInfo.units);
    info(6,2)={strEndTime};
    if ~isempty(ts.timeInfo.Startdate)
        info(7,1)={'Reference start date'};
        info(7,2)={ts.timeInfo.Startdate};
    else
        info(7,1)={''};
        info(7,2)={''};
    end
end    
info(8,1)={''};
info(8,2)={''};
info(9,1)={'Ordinate data characteristics'};
info(9,2)={''};
info(10,1)={'Interpolation method'};;
info(10,2)={ts.DataInfo.Interpolation.Name};
info(11,1)={'Size'};
info(11,2)={num2str(size(ts.Data))};
info(12,1)={''};
info(12,2)={''};
info(13,1)={'Time'};
info(13,2)={'Data'};


function timeout=localCheckRelativeTime(ts)
DateVector=datevec(now);
DateVector=repmat(DateVector,length(ts.time),1);
a=floor(ts.time/3600);
DateVector(:,4)=a;
b=floor((ts.time-a*3600)/60);
DateVector(:,5)=b;
c=ts.time-a*3600-b*60;
DateVector(:,6)=c;
if strcmp(ts.timeinfo.format,'HH:MM:SS')
    timeout=mat2cell(datestr(DateVector,13),ones(length(ts.time),1));
elseif strcmp(ts.timeinfo.format,'HH:MM:SS PM')
    timeout=mat2cell(datestr(DateVector,14),ones(length(ts.time),1));
elseif strcmp(ts.timeinfo.format,'HH:MM')
    timeout=mat2cell(datestr(DateVector,15),ones(length(ts.time),1));
elseif strcmp(ts.timeinfo.format,'HH:MM PM')
    timeout=mat2cell(datestr(DateVector,16),ones(length(ts.time),1));
else
    timeout=ts.time;
end
        