/****************************************************************************/
/*  Copyright © 2012-2015 Mehdi Dogguy <mehdi@debian.org>                   */
/*                                                                          */
/*  This file is part of Dochelp.                                           */
/*                                                                          */
/*  Dochelp 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.                                              */
/*                                                                          */
/*  Dochelp 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 Dochelp.  If not, see <http://www.gnu.org/licenses/>.        */
/****************************************************************************/

#include <glob.h>

#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/memory.h>

CAMLprim value ocaml_glob(value pattern){
  value matches;
  CAMLparam2(pattern, matches);
  int i, r;
  glob_t gl;

  r = glob(String_val(pattern), GLOB_BRACE | GLOB_TILDE, NULL, &gl);
  if (r != 0) {
    globfree(&gl);
    CAMLreturn (caml_alloc(0, 0));
  }
  matches = caml_alloc(gl.gl_pathc, 0);
  for (i = 0; i < gl.gl_pathc; i++)
    Store_field(matches, i, caml_copy_string(gl.gl_pathv[i]));
  CAMLreturn (matches);
}
