#include <stdio.h>
#include <stdlib.h>

void dgetrf_(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
void dgetrs_(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);


void cbem_lap_solv(void)
{

/* ===purpose=== */

/**********************************************************************************************************************************/
/********************************  COLLOCATION BEM for 3D LAPLACE EQUATION: SINGULAR FORMULATION  *********************************/
/***************************************  3-NODED TRIANGULAR ELEMENT: ANALYTIC INTEGRATION  ***************************************/
/***********************************************  PIECEWISE CONSTANT APPROXIMATION  ***********************************************/
/***************************************************  Solve the Discretized BIE  **************************************************/
/**********************************************************************************************************************************/

/* Developer: Sylvain Nintcheu Fata */
/* Version:   V.1.3                 */
/* Released:  Jun 14, 2012          */

 
   extern int nbelt,*eltbc; /* nbelt == Total number of boundary elements */
                            /* eltbc[k] = {0,1} ==> {Dirichlet,Neunamm} boundary condition is prescribed on element k */
   extern double *g,*rhs;   /* g == Discretized BIE matrix or Left-hand side of the BEM equation*/
                            /* rhs == Right-hand side of the Discretized BIE */
   extern double *phi,*flx; /* phi == Vector containing boundary potentials */
                            /* flx == Vector containing boundary fluxes */

   char tr;
   int k,info,nrhs;
   int *ipiv;



    printf("           >>>  LU Decomposition of the BIE matrix <<<\n");
    
    if ( (ipiv = (int *)malloc(nbelt*sizeof(int))) != NULL ) /* If ipiv is successfully allocated */
       dgetrf_(&nbelt,&nbelt,g,&nbelt,ipiv,&info); /* LU Decomposition */
    else
    {printf("cbem_lap_solv: Allocate array \"ipiv\" failed\n"); exit(1);}

    printf("           >>>  Back-substitution  <<<\n");

    tr = 'N'; nrhs = 1;
    dgetrs_(&tr,&nbelt,&nrhs,g,&nbelt,ipiv,rhs,&nbelt,&info); /* Back-substitution */
    free(ipiv); free(g);
    
    printf("err == %d\n",info);

    for (k=0; k<nbelt; k++)
       if ( eltbc[k] == 0 ) /* eltbc[k] = 0 ==> Dirichlet data is prescribed on element k */
          flx[k] = rhs[k];
       else /* eltbc[k] = 1 ==> Neumann data is prescribed on element k */
          phi[k] = rhs[k];  

    free(rhs); free(eltbc);

}
