/* wp2m.c
*
*  ==> means stuff to do
*
*  If the waypoint file wasn't specified on the command line
*    Prompt the user for name of waypoint file
*      ( which currently must be in decimal degrees, North positive, West negative )
*  ==> accept any format, convert to decimal degrees
*    Mission speed
*    depthEnvelope settings
*      Present default settings, ask if any changes
*        If yes, get user input
*    Gulper mission yes or no
*    YoYo yes or no
*      Present default settings, ask if any changes
*      If yes, get user input
*    control output of waypoint behaviors based on int yoyoMission
*
*    Use a doubly linked list to handle case where distance between 2 waypoints
*        is greater than 3600 meters
*
*    Construct waypoint 0 500 meters from first waypoint at reciprocal heading
*         for AUV launch
*    Document waypoint 0 in the comments at the head of the Mission File
*        Calculate time between waypoints based on MISSION_SPEED * cos of dive angle in meters/sec
*    Set INITIAL_HEADING at start of mission ( heading to waypoint 1 )
*    Set missionTimer to 120% longer than the expected run in seconds
*    Ascend in spiral if heading change or end of mission
*    Construct and write out a Mission File
*        Output filename: "current_date".cfg
*        Mission File globals placed at head of file
*        Default to arming gulpers at mission start
*        Execution is from bottom of file
*         ( initial waypoint at bottom, final destination at top )
*    Write out a Winfrog waypoints file
*    Write out a Winfrog survey line file
*    Write out a waypoints, headings, distance and time .csv file for Excel import
*  ==> free memory
*  ==> Separate out the file operations to a file fileOps.c
*  ==> Get rid of unnecessary global vars
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <conio.h>
#include "wp2m_user_if.h"
#include "calcs.h"
#include "wptList.h"
#include "writeMission.h"


//  GLOBAL DECLARATIONS
//

char* file_name;  // set to mission output filename in fileName() in file calcs.c

int choice = 0; // user inputs
char reply = '0';

int abortOnTimeout = 1; // 1 if abortOnTimeout == True
int gulperMission = 1;  // 1 if Gulper mission
int yoyoMission = 1;    // 1 if Yoyo mission

// Mission Parameter Default Settings
//
double maxLegMeters = 3600.00;    // meters between AUV surfacings
double missionSpeed = 1.50;       // meters per second
double missionSpeedSlow = 1.25;
int gpsHits = 30;
double spd = 1.50;
double wayPointDepth = 50.0;
double minDepth = 10.0;
double maxDepth = 100.0;
double abortDepth = 115.0;
double abortAltitude = 2.5;
double abortLockoutDepth = 8.0;

// YoYo Mission Parameter Default Settings:
int yoyoMinAltitude = 15;  // meters
int missionYoyoMinDepth = 10;
int missionYoyoMaxDepth = 100;
int missionYoyoMaxDepthShallow = 20;
double diveAngle = 30.0;  // added 2 Aug 14

double surveyLineMeters = 0.0; // added 28 Sept 14


FILE *waypointFilePtr;  // pointer to waypoints file which will be read in

int LAUNCH_OFFSET = 500;  // meters from launch waypoint to first mission waypoint

double missionTime = 0;  // mission timer gets set in wptList.c


int main (int argc, char *argv[])
{
  int i;                            // iterator
  char userInput[101];              // input string from user
  char line[50]= {'\0'};            // line read in from waypoint file
  double latIn = 0.0;               // vars read in from waypoint file
  double lonIn = 0.0;

  // if argc == 1, then prompt user for waypoint filename
  //   else user provided filename, try to open it for reading
  if ( argc == 1 )
  {
    printf("\n\nWelcome to Waypoints to CTD_AUV mission utility.\n");
    printf("Waypoint lat/lon's must be in decimal degree format.\n");
    printf("eg: 36.8167 -121.8170\n");
    printf("What's the name of the waypoint file ? \n");
    printf(" > ");
    fgets(userInput, 100, stdin);
    for ( i = 0; i < 100; i++ )  // strip the newline character
    {
      if(userInput[i]== '\n')
      userInput[i] = '\0';
    }
    if((waypointFilePtr=fopen(userInput, "r"))==NULL)
    {
      printf("cannot open file %s ", userInput);
      exit(1);
    }
  }
  else
  {
    // Open the waypoints file
    if((waypointFilePtr=fopen(argv[1], "r"))==NULL)
    {
      printf("cannot open file %s ", argv[1]);
      exit(1);
    }
  }

  //********************************************
  // Interactive section of code begins
  //

  // present default mission parameters, ask if change
  //
  queryMissionParameters();

  // inquire if this is a YOYO mission
  //
  yoyoMission = queryYoyo();

  // If yoyoMission ==1, present yoyo parameters, ask if change
  // if this is not a YOYO mission, present default waypoint behavior depth, ask if change
  //
  if ( yoyoMission ==1 )
  {
    queryYoYoParameters();
  }
  else
  {
    wayPointDepth = get_wayPointDepth();

    //printf("\n\n wayPointDepth returned = %.1f\n\n", wayPointDepth);
    //getch();

  }

  // inquire if this is a Gulper mission, int gulperMission set to 1 if true
  //
  gulperMission = queryGulper();

  
  //*************************************
  // Interactive section of code ends
  //

  // read in the "waypoints" file, assign each lat/lon to a DLL node
  //
  while ( fgets(line, sizeof(line), waypointFilePtr) != NULL)
  {
    //printf(" line: %s ", line);
    sscanf ( line, "%lf %lf", &latIn, &lonIn);
    //printf ( "line input: %s\n", line );
    //printf(" latIn %lf, lonIn %lf\n", latIn, lonIn);
    insertLatLonEnd(latIn, lonIn);
  }

  // uncomment to display the list:
  //displayFwd();

  struct node *currNodePtr;
  if(headNodePtr==NULL)
  {
    printf("list is empty\n");
    exit(1);
  }
  currNodePtr=headNodePtr;
  while(currNodePtr->nextPtr!=NULL)  // traverse list
  {
    currNodePtr->legMeters = dist(currNodePtr->Lat, currNodePtr->Lon, currNodePtr->nextPtr->Lat, currNodePtr->nextPtr->Lon);
    currNodePtr->heading = heading(currNodePtr->Lat, currNodePtr->Lon, currNodePtr->nextPtr->Lat, currNodePtr->nextPtr->Lon);
    currNodePtr=currNodePtr->nextPtr;
  }

  // add nodes if leg distances > maxLegMeters
  //
  insertIfBig_legMeters();

  // fill in blank waypoint locations
  //
  fillBlankLatLons();

  // fill in member wptNumber
  //
  itemizeList();

  // fill in member legSecs
  //
  calcWaypointTimes();

  // create launch waypoint 500 meters from start of line recip course
  //
  launch_waypoint();  // create launch waypoint 500 meters from start of line recip course

  //  *****  UNCOMMENT TO DISPLAY LINKED LIST  ***********
  //  displayFwd();
  //  displayRev();
  //  printf("\n\n<cr> to continue ");
  //  getch();

  // calculate expected mission time
  //
  missionTime = calcMissionTime();
  //  printf("\n\n missionTime = %g \n\n", missionTime);


  //  write out the mission script
  //
  writeMission();

  //  write out Winfrog waypoints list
  //
  writeWaypoints();

  //  writeout Winfrog survey line
  //
  writeSurLine();

  //  write csv file for Excel import
  //
  write_csvFwd();




  // clean up
  //
  fclose(waypointFilePtr);

  // free memory

  //printf( "\n\n************ Program ends ************ ");

  return 0;
}


