/* See {salamic_closer.h}. */
/* Last edited on 2015-11-16 01:25:41 by stolfilocal */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

#include <bool.h>
#include <vec.h>
#include <jsfile.h>
#include <affirm.h>

#include <stmesh.h>
#include <stmesh_section.h>
#include <salamic_closer.h>
#include <salamic_closer_trivial.h>
#include <salamic_closer_Stolfi.h>
/* #include <salamic_closer_Minetto.h> */
/* #include <salamic_closer_Bentley.h> */

void salamic_closer_close
  ( stmesh_t mesh,
    int32_t pZ,
    uint32_t mf,
    stmesh_face_t f[], 
    char *closer, 
    char *outPrefix, 
    salamic_stats_t *st
  )
  {
    bool_t debug = FALSE;
    
    if (debug) { fprintf(stderr, "%s:%d: enter mf = %d\n", __FUNCTION__, __LINE__, mf); }
    
    /* Allocate a vector {e} big enough to hold all mesh edges in the cross-section: */
    uint32_t me_max  = 2*mf;  /* Max mesh edges in all paths. */
    stmesh_edge_t *e = notnull(malloc(me_max*sizeof(stmesh_edge_t)), "no mem");
    
    /* Allocate the vector {estart} that tells where each path starts: */
    uint32_t nc_max = mf; /* Max number of paths. */
    uint32_t *estart = notnull(malloc((nc_max+1)*sizeof(stmesh_edge_t)), "no mem");

    uint32_t nc = 0; /* Actual number of paths found. */
    
    if (strcmp(closer, "TRIVIAL") == 0)
      { salamic_closer_trivial_close(mesh, pZ, mf, f, &nc, estart, e, st); }
    else if (strcmp(closer, "STOLFI") == 0)
      { salamic_closer_Stolfi_close(mesh, pZ, mf, f, &nc, estart, e, st); }
    /* 
    else if (strcmp(closer, "MINETTO") == 0)
      { salamic_closer_Minetto_close(mesh, pZ, mf, f, &nc, estart, e, st); }
    else if (strcmp(closer, "BENTLEY") == 0)
      { salamic_closer_Bentley_close(mesh, pZ, mf, f, &nc, estart, e, st); }
    */
    else 
      { demand(FALSE, "unknown or unimplemented loop closing algorithm"); }

    /* Build the cross-section datat structure: */
    if (debug) { fprintf(stderr, "{stmesh_section_make(nc = %d, me = %d)}\n", nc, estart[nc]); }
    stmesh_section_t *sec = stmesh_section_make(mesh, pZ, nc, estart, e);
    free(e);
    free(estart);
      
    /* Write it to disk: */
    char *fileName = NULL;
    asprintf(&fileName, "%s%+011d.txt", outPrefix, pZ);
    FILE *wr = open_write(fileName, TRUE);
    stmesh_section_write(wr, sec);
    fclose(wr);
    stmesh_section_free(sec);
    free(fileName);
    
    if (debug) { fprintf(stderr, "%s:%d: exit\n", __FUNCTION__, __LINE__); }
  }
