## Copyright (C) 2016 Pantxo Diribarne
## 
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*- 
## @deftypefn {Function File} {@var{retval} =} inkprint (@var{fmt}, @var{fname})
##
## Print figure to svg and use inkscape to convert it to the desired
## format.
##
## Supported output formats @var{fmt} are -dpdf, -dps, -deps, -dpng, -demf
## @seealso{}
## @end deftypefn

## Author: Pantxo Diribarne <pantxo@gre046552>
## Created: 2016-06-26

function [retval] = inkprint (fmt = "", fname = "")
  if (isempty (fmt))
    print_usage ();
  endif
  
  if (isempty (fname))
    fname = fmt;
    [d, f, ext] = fileparts (fname);
    if (isempty (ext))
      error ("inkprint: could not infer the file format from the extension")
    endif
    fmt = sprintf ("-d%s", ext(2:end));
  endif

  if (any (strcmpi (fmt, {"-dpdf", "-dps", "-deps", "-demf", "-dpng"})))
    opt_export = sprintf ("--export-%s", fmt(3:end));
  else
    error ("inkprint: unhandled file format %s", fmt)
  endif

  tmp = [tempname() ".svg"];
  unwind_protect
    print ("-dsvg", tmp)
    vr = strsplit (version (), ".");
    if (str2num (vr{1}) > 3 && str2num (vr{2}) > 1)
      while (! exist (tmp, "file"))
        pause (.1)
      endwhile
    endif
    ink_bin = ifelse (isunix (), "inkscape", "inkscape.exe");
    redirect = ifelse (isunix (), " > /dev/null", "");
    cmd = sprintf ("%s -z -f=\"%s\" %s %s %s", ink_bin, tmp, ...
                   opt_export, fname, redirect)
    [status, out] =  system (cmd);
    if (status)
      error ("inkprint: %s", out)
    endif
  unwind_protect_cleanup
    delete (tmp)
  end_unwind_protect
endfunction
