#include <stdlib.h>
#include "stack-c.h"
#include "api_scilab.h"
#include "Scierror.h"
#include "sciprint.h"

#include "Hausdorff.h"
#include "Erreur.h"

/*****************************************************
 * SCILAB function : EuclideanDistanceMap            *
 *****************************************************/
 
int gtw_EuclideanDistanceMap ( char * fname )
{
    int m,n,l;
    int HandleIndic, HandleEDM;
	float thresh_indic ;

    CheckRhs(3,3);
    CheckLhs(0,1);
    
	// Variable HandleIndic
	
    GetRhsVar(1,"i",&m,&n,&l);
    CheckScalar(1,m,n);
    HandleIndic = *istk(l);

	// Variable thresh_indic
	
    GetRhsVar(2,"r",&m,&n,&l);
    CheckScalar(2,m,n);
    thresh_indic = *sstk(l);
	
	// Variable HandleEDM
	
    GetRhsVar(3,"i",&m,&n,&l);
    CheckScalar(3,m,n);
    HandleEDM = *istk(l);

	// Appel à l'API
			
	if ( EuclideanDistanceMap ( HandleIndic , thresh_indic , HandleEDM ) )
		Scierror (999, GetErreur());

	return(0);
}	

/*****************************************************
 * SCILAB function :   sci_BuildPaths                *
 *****************************************************/
 
int gtw_BuildPaths ( char * fname )
{
    int m,n,l,nedges,npaths,nnodes,i;
    int * ID_START , * ID_END ;
	int ** PATH ;
	int * LENGTH , * DEGREE ;
	int one=1;
	int two=2;
	char ** Labels;

    CheckRhs(2,2);
    CheckLhs(2,2);
    
	// Variable ID_START
	
    GetRhsVar(1,"i",&m,&n,&l);
    CheckVector(1,m,n);
	nedges = m*n ;
    ID_START = istk(l) ;

	// Variable ID_END
	
    GetRhsVar(2,"i",&m,&n,&l);
    CheckVector(2,m,n);
	CheckDimProp(1,2,(m*n)!=nedges);
    ID_END = istk(l);
	
	// Appel à l'API
			
	if ( BuildPaths ( ID_START , ID_END , nedges , & PATH , & LENGTH , & npaths , & DEGREE , & nnodes ) )
		Scierror (999, GetErreur());
		
	// Création des labels
		
	m = npaths + 1;
	
	if ( !(Labels = (char **) malloc ( m * sizeof(char *) ) ) )
		Scierror (999, "gtw_BuildPaths : echec de l'allocation des chaines de caracteres\n");
	
	Labels[0] = (char *) malloc ( 4 * sizeof(char) );
	strncpy (Labels[0],"Type",4);
	
	for(i=0;i<npaths;i++)
	{
		Labels[i+1] = (char *) malloc ( 4 * sizeof(char) );
		strncpy (Labels[i+1],"Path",4);
	}
	
	// Création d'un object de type mlist
	
	CreateVar ( Rhs + 1 , "m", & m, & one , & l );	

	// Affectation des labels
	
	CreateListVarFromPtr ( Rhs + 1 ,  1 , "S" , & m , & one , Labels );
	
	// Création des composantes de la liste
	
	for (i=0;i<npaths;i++)
	{
		CreateListVarFromPtr ( Rhs + 1 ,  i + 2 , "i" , & LENGTH[i] , & one , & PATH[i] );
	}
	
	// Création du vecteur des valences
		
	CreateVarFromPtr ( Rhs + 2 , "i", & nnodes , & two , & DEGREE );
		
	/* Affectation des sorties */
	
    LhsVar(1) = Rhs + 1;
    LhsVar(2) = Rhs + 2;
	
	/* Désaffectation des pointeurs */
	
	for (i=0;i<npaths;i++)
	{
			free(PATH[i]);
	}				
	
	free(PATH);
	free(LENGTH);
	free(DEGREE);

	return(0);
}	
