
#include <common.h>
#include <adcp.h>         /* NAVIGATION_TYPE */
#include "tran_nbp.h"     /* TRANSECT_NAV_TYPE */

/* Note: our navigation structure is not well defined; we put in
   it whatever is stored at data averaging time, which may be position
   at the end of the ensemble (with UH user exit programs), or
   averaged over the ensemble (with NAVSOFT).
*/

#define LLSCALE (1.0 / 3600000)

#if PROTOTYPE_ALLOWED
void fill_nav(NAVIGATION_TYPE *n, NBP_ENSEMBLE_TYPE *ens)
#else
void fill_nav(n, ens)
   NAVIGATION_TYPE *n;
   NBP_ENSEMBLE_TYPE *ens;
#endif
{
   TRANSECT_NAV_TYPE *tn;
   double u, v, rad;

   if (!ens->nav_present)
      n->longitude = n->latitude = n->speed = n->direction = BADFLOAT;
   else
   {
      tn = &(ens->nav);
      if (tn->lat == BADLONG)
      {
         n->latitude  = BADFLOAT;
         n->longitude = BADFLOAT;
      }
      else
      {
         n->latitude  = tn->lat * LLSCALE;
         n->longitude = tn->lon * LLSCALE;
      }
      if (tn->u == BADSHORT)
      {
         n->speed     = BADFLOAT;
         n->direction = BADFLOAT;
      }
      else
      {
         u = tn->u * 0.001;
         v = tn->v * 0.001;
         n->speed = sqrt( u*u + v*v );
         if (fabs(u) < 1e-6)  /* Q&D way to prevent the FP error of u = 0 */
            u = 1e-6;
         rad = atan2(v,u);
         n->direction = 90 - 180 * rad / M_PI;
         /** 1999/07/13 Pierre Jaccard
             According to file loadtnbp.def, speed is in knots. I also had
             some problems with sspeed direction being negative. 
         **/
         n->speed *= 3600.0/1852.0;
         if(n->direction < 0.0)
           n->direction += 360.0;
      }
   }
}
