/*
   PEPA input routine, 11th July 1995.

   The input formats are two files, pepa.dia and pepa.off,
   for diagonal and off-diagonal elements, respectively.
   The files contain exactly three numbers per line, two
   integers and a real.  There is a leading whitespace character
   before the first integer but after that there are no surplus
   spaces except as the separators between numbers.
*/

#include <stdio.h>
#include "nr.h"
#include "nrutil.h"

void pwbin(int n, unsigned long nmax, double sa[], unsigned long ija[])
{
   int prev_i, i, j;
   unsigned long k;
   double x;
   char eoln;
   FILE *diag;
   FILE *offdiag;

   /* Initialise to zero for any missing diagonal entries */
   for (j=1;j<=n;j++) 
        sa[j]=0;

   /* Now read the diagonal entries */
   diag = fopen ("pwbsolve.dia", "r");
   if (diag == NULL) {
      fprintf(stderr, "Could not open pwbsolve.dia\n");
      exit(1);
   }
   else
      printf("# Found pwbsolve.dia OK\n");
   while (getc(diag) != EOF) {
       fscanf (diag, "%i%i%lf%c", &i, &j, &x, &eoln);
/*        printf("setting index %d to %f\n", j, x); */
       sa[j]=x;
   };
   fclose (diag);

   k=n+1;
 
   prev_i = 1;

   /* Now read the off-diagonal entries */
   offdiag = fopen ("pwbsolve.off", "r");
   if (offdiag == NULL) {
      fprintf(stderr, "Could not open pwbsolve.off\n");
      exit(1);
   }
   else
      printf("# Found pwbsolve.off OK\n");
   while (getc(offdiag) != EOF) {
     fscanf (offdiag, "%i%i%lf%c", &i, &j, &x, &eoln);
     /* gcla - successful part of if statement */
/*      if (i == j) { */
/* 	 sa[j] += x; */
/* 	 printf("adding %f to index %d - now set to %f\n", x, j, sa[j]); */
/*      } else { */
	 while (prev_i != i) ija[++prev_i]=k+1;
	 if (++k > nmax) nrerror ("pwbin: nmax too small");
	 sa[k]=x;
	 ija[k]=j;
/*      } */
   };
   fclose (offdiag);

   /* Now we need to set the start and end points of the array   */
   /* Location 1 of ija is always equal to N+2.  (It can be read */
   /* to determine N.)                                           */
   ija[1]=n+2;
   /* Location N+1 of ija is one greater than the index in sa of */
   /* the last off-diagonal element of the last row.  (It can be */
   /* read to determine the number of nonzero elements in the    */
   /* matrix, or the number of elements in sa and ija.         ) */
   ija[n+1]=k+1;
   /* Location N+1 of sa is not used and can be set arbitrarily. */
   sa[n+1]=0;

}
