/* *********************************************************
 * *	                                                   *
 * *                Compute crab angle                     * 
 * *                                                       *
 * *********************************************************
 * File: libs/user/crab.c
 *
 *                      COPYRIGHT (c) 2002  BY
 *          SIGMET INCORPORATED, WESTFORD MASSACHUSETTS, U.S.A.  
 *
 * THIS SOFTWARE IS FURNISHED UNDER A LICENSE AND MAY BE USED AND  COPIED
 * ONLY  IN  ACCORDANCE WITH  THE  TERMS  OF  SUCH  LICENSE  AND WITH THE
 * INCLUSION OF THE ABOVE COPYRIGHT NOTICE.  THIS SOFTWARE  OR  ANY OTHER
 * COPIES  THEREOF MAY NOT BE PROVIDED OR OTHERWISE MADE AVAILABLE TO ANY
 * OTHER PERSON.  NO TITLE TO AND OWNERSHIP OF  THE  SOFTWARE  IS  HEREBY
 * TRANSFERED. 
 */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#include "sigtypes.h"
#include "user_lib.h"

int main(int argc, char *argv[])
{
  FLT8 fGroundBearing, fGroundSpeed, fWindFrom, fWindSpeed, fAirBearing, fAirSpeed;
  FLT8 fX, fY;
  char *sptr;
  if (argc<5)
    {
      printf( "Sorry, not enough args\n" );
      exit(EXIT_FAILURE);
    }

  fGroundSpeed   = strtod(argv[1], &sptr);
  fGroundBearing = strtod(argv[2], &sptr);
  fWindSpeed     = strtod(argv[3], &sptr);
  fWindFrom      = strtod(argv[4], &sptr);
  fX = fGroundSpeed * sin((FPI/180.0)*fGroundBearing);
  fY = fGroundSpeed * cos((FPI/180.0)*fGroundBearing);

  fX += fWindSpeed * sin((FPI/180.0)*fWindFrom);
  fY += fWindSpeed * cos((FPI/180.0)*fWindFrom);

  fAirSpeed = sqrt( fX*fX + fY*fY );
  if ((fX==0.0)&&(fY==0.0))
    {
      fAirBearing = 0.0;
    }
  else
    {
      fAirBearing = atan2( fX, fY );
      fAirBearing *= (180.0/FPI);
      if (fAirBearing < 0.0) fAirBearing += 360.0;
    }

  printf( "Ground speed: %5.2f, heading: %3.0f deg\n", fGroundSpeed, fGroundBearing );
  printf( "  Wind speed: %5.2f,    from: %3.0f deg\n", fWindSpeed,   fWindFrom );
  printf( "   Air speed: %5.2f, heading: %3.0f deg\n", fAirSpeed,    fAirBearing );
  exit(EXIT_SUCCESS);
}
