/**************************************************************

   S_INTGRD.C

   This function INTGRIDs an array with or without gaps,
   leaving BADFLOAT in the gaps.  It also checks to see
   that the new grid increases with index.  If not,
   then the two grids are negated before and after
   regridding, for no net change.  There is still no
   checking for monotonicity of either grid, or for
   the same sense of change in both.

   The function returns the number of good points in the new array.

   The function of changing decreasing into increasing
   grids could be done in a modified version of regrid()
   itself.

*/
#include "common.h"
#include "vector.h"

/* Note: in the variables, a second character of 'o' means
   "old", and 'n' means "new", that is, the regridded version.
*/

#if PROTOTYPE_ALLOWED
int s_intgrid(float *zo, float *fo, float *zn, float *fn, int no, int nn)
#else
int s_intgrid(zo, fo, zn, fn, no, nn)
float *zo, *fo, *zn, *fn;
int no, nn;
#endif
{
   int i;
   int in0 = 0, inm;
   int io0, io1;
   int n0, nout;
   int negate = 0;
   int ngood = 0;

/* Find the valid range of zn.  It is the first range with no gaps. */

   while ((in0 < nn) && !good_float(zn[in0]))   in0++;
   inm = in0;
   while ((inm < nn) && good_float(zn[inm]))   inm++;

/* Check for increasing zn; otherwise negate zn and zo. */

   if (zn[in0] > zn[inm-1])   negate = 1;

   if (negate)
      for (i=in0; i<inm; i++)
         zn[i] = -zn[i];

/* Initialize fn as bad everywhere. */

   for (i=0; i<nn; i++)  fn[i] = BADFLOAT;

/* Find each good range in fo, and regrid it.*/

   io0 = 0;
   while (io0 < no)
   {
      while ((io0 < no) && (!good_float(fo[io0]))) io0++;
      /* Now io0 is no or the beginning of a good section. */

      io1 = io0;
      while ((io1 < no) && (good_float(fo[io1]))) io1++;
      /* Now io1 is no or the beginning of a bad section. */
      /* If either is n, both should be n */

      if (negate)
         for (i=io0; i<io1; i++)
            zo[i] = -zo[i];

      if (io1-io0 > 1)
      {
         intgrid(zo+io0, fo+io0, zn+in0, fn+in0, io1-io0, inm-in0, &n0, &nout);
         ngood += nout;
      }

      if (negate)
         for (i=io0; i<io1; i++)
            zo[i] = -zo[i];

      io0 = io1;
   }
   if (negate)
      for (i=in0; i<inm; i++)
         zn[i] = -zn[i];

   return (ngood);
}

