/*

Copyright (C) 2016-2019 John W. Eaton

This file 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 file 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 file; see the file COPYING.  If not, see
<https://www.gnu.org/licenses/>.

*/

// The definition of 'make_command_string' was copied from
// liboctave/wrappers/octave-popen2.c of the Octave project.

#include <stdio.h>

#include "parallel-gnutls.h"

char *
make_command_string (const char *cmd, char *const *args)
{
  char *const *argp;
  size_t cmd_len;
  char *command;

  // Count Command length, quotes, and terminating NUL character.
  cmd_len = strlen (cmd) + 3;

  // Count argument length, space, and quotes.
  // Ignore first arg as it is the command.
  argp = args;
  while (*++argp)
    cmd_len += strlen (*argp) + 3;

  command = (char *) gnulib_malloc (cmd_len);

  sprintf (command, "\"%s\"", cmd);

  argp = args;
  while (*++argp)
    sprintf (command, "%s \"%s\"", command, *argp);

  return command;
}
