% CSVEXPORT Exports the data of an object to a csv file.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    csvexport
%
% DESCRIPTION: Exports the data of an object to a csv file.
%
% CALL:        csvexport(in-objects)
%
% INPUTS:      in-objects: Input objects which data should be stored to
%                          disc.
%
% OUTPUTS:     success:    If storing of the data was successful
%
% <a href="matlab:utils.helper.displayMethodInfo('ltpda_uoh', 'csvexport')">Parameters Description</a>
%
% VERSION:     $Id: csvexport.m,v 1.7 2011/04/08 08:56:30 hewitson Exp $
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = csvexport(varargin)

  %%% Check if this is a call for parameters
  if utils.helper.isinfocall(varargin{:})
    varargout{1} = getInfo(varargin{3});
    return
  end

  [objs, obj_invars, rest] = utils.helper.collect_objects(varargin(:), '');
  pli = utils.helper.collect_objects(rest(:), 'plist');

  [data, plData] = csvGenerateData(objs);
  
  pl = combine(pli, getDefaultPlist);
  
  filename = pl.find('filename');
  commentChar = pl.find('commentChar');
  description = pl.find('description');
  
  % Some plausibility checks
  if isempty(filename)
    if ~isempty(rest) && ischar(rest{1})
      filename = rest{1};
      pl.pset('filename', filename);
    else
      error('### No filename is specified');
    end
  end
  if isempty(description)
    description = plData.find('DESCRIPTION');
  end
  columns  = plData.find('COLUMNS');
  nrows    = plData.find('NROWS');
  ncols    = plData.find('NCOLS');
  objIDs   = plData.find('OBJECT IDS');
  objNames = plData.find('OBJECT NAMES');
  creator  = plData.find('CREATOR');
  created  = format(time(), 'yyyy-mm-dd HH:MM');
  
  fid = fopen(filename, 'w');
  
  % Check fid
  if fid == -1
    error('### Can not open the file: %s', filename);
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%                              write header                             %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s  DESCRIPTION: %s\n', commentChar, description);
  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s  COLUMNS:     %s\n', commentChar, columns);
  
  columnNames = strtrim(regexp(columns, ',', 'split'));
  maxColNames = max(cellfun(@length, columnNames));
  
  for ii = 1:numel(columnNames)
    columnDesc = plData.find(columnNames{ii});
    if ~isempty(columnDesc)
      off = '';
      off(1:maxColNames-length(columnNames{ii})) = ' ';
      fprintf(fid, '%s    %s%s: %s\n', commentChar, columnNames{ii}, off, columnDesc);
    end
  end
  
  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s  NROWS:         %d\n', commentChar, nrows);
  fprintf(fid, '%s  NCOLS:         %d\n', commentChar, ncols);
  fprintf(fid, '%s  OBJECT IDS:    %s\n', commentChar, objIDs);
  fprintf(fid, '%s  OBJECT NEAMES: %s\n', commentChar, objNames);
  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s  CREATION DATE: %s\n', commentChar, created);
  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s  CREATED BY:    %s\n', commentChar, creator);
  fprintf(fid, '%s\n', commentChar);
  fprintf(fid, '%s\n', commentChar);
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%%                              write data                               %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  for nn=1:nrows
    for dd = 1:ncols
      if numel(data{dd}) >= nn
        fprintf(fid, '%.17f', data{dd}(nn));
      end
      if dd < numel(data)
        fprintf(fid, ',');
      end
    end
    fprintf(fid, '\n');
  end
  
  fclose(fid);
  
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                               Local Functions                               %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    getInfo
%
% DESCRIPTION: Get Info Object
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function ii = getInfo(varargin)
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pl   = [];
  else
    sets = {'Default'};
    pl   = getDefaultPlist;
  end
  % Build info object
  ii = minfo(mfilename, 'ltpda_uoh', 'ltpda', utils.const.categories.helper, '$Id: csvexport.m,v 1.7 2011/04/08 08:56:30 hewitson Exp $', sets, pl);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION:    getDefaultPlist
%
% DESCRIPTION: Get Default Plist
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function plout = getDefaultPlist()
  persistent pl;  
  if exist('pl', 'var')==0 || isempty(pl)
    pl = buildplist();
  end
  plout = pl;  
end

function plo = buildplist()
  plo = plist();
  p = param({'filename' 'cvs filename.'}, '');
  plo.append(p);
  p = param({'commentChar','The comment character in the file.'}, {1, {'#'}, paramValue.OPTIONAL});
  plo.append(p);
  p = param({'description', 'Description for the file.'}, '');
  plo.append(p);
end



