/* **********************************************************************
 * *	                                                                *
 * *                       Rays Utility Startup                         *
 * *                                                                    *
 * **********************************************************************
 * File: iris/examiners/rays.C
 *
 * COPYRIGHT (c) 1988, 1989, 1991, 1996, 1998, 1999, 2000, 2001, 2001,
 *                             2002, 2005 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 <locale.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sigtypes.h"
#include "dsp.h"
#include "headers.h"
#include "iris_task.h"
#include "ingest.h"

#include "user_lib.h"
#include "misc_lib.h"

#include "examiners.h"
struct rays_command_line
{
  FLT4  fBinStartKm;
  SINT4 iMaxLength;    /* Maximum line length in data listing */
  SINT2 iSweep;
  char  sSummaryFile[FILENAME_SIZE];
  char  sDataType[20];
  UINT1 lInteractive;
  UINT1 lVerbose;
  UINT1 lPerformance;
  UINT1 lNoExit ;
};

static void ProcessCommandLine
(int iArgc_a,
 char *sArgv_a[],
 struct rays_command_line *pCommand_a );

static void usage( void );

static void AskFile
(char sSummaryFile_a[FILENAME_SIZE]);

/* ===========================================================
 * This is the data rays examiner
 */
int main( int iargc_a, char *sargv_a[] )
{
  struct ingest_header IngestHeader;
  MESSAGE istatus;
  const struct ingest_data_file *pIngest;
  SINT4 isize, ichannel, iray;
  const char *sptr;
  char smomentfile[PATHNAME_SIZE] ;
  char singest_env[DIRECTORY_SIZE];
  UINT2 last, lmissing;
  UINT2 iParam;
  struct rays_command_line Command;
  SINT4 iBinStart;
  /* ----------------------------------------------------------------------
   * Inits
   */
  setlocale( LC_ALL, "" ) ;

  /* Translate environment variables
   */
  sptr = getenv( "IRIS_INGEST" );
  if( sptr == 0 )
    {
      sig_signal_va( USER_NO_ENV, 1, "IRIS_INGEST" );
      exit(EXIT_FAILURE);
    }

  ProcessCommandLine( iargc_a, sargv_a, &Command );


  strncpy( singest_env, sptr, DIRECTORY_SIZE-1 );
  singest_env[DIRECTORY_SIZE-1] = 0;

  /* Prompt for the summary file if not given */
  if (0 == Command.sSummaryFile[0])
    {
      AskFile( Command.sSummaryFile );
    }

  /* Read in the summary file. */
  istatus = iread_summary( Command.sSummaryFile, &IngestHeader, &isize );
  if( istatus != SS_NORMAL ) {
    sig_signal( istatus ) ; exit(EXIT_FAILURE) ;
  }

  /* Optionally print summary */
  if (Command.lVerbose)
    {
      printf( "Task Summary for: %s\n", Command.sSummaryFile );
      showsummary( &IngestHeader ) ;
      printf( "\n" ) ;
    }
  /* Process data type from the command line */
  DataTypeFromStr( &iParam, Command.sDataType, 
		   &IngestHeader.tcf.dsp.DataMask, DB_DBT );

  /* Optionally prompt for other info */
  if (Command.lInteractive)
    {
      asksweep  ( IngestHeader.tcf.scan.isweeps, &Command.iSweep, Command.iSweep );
      askmoments( "What parameter do you wish to display? ", 
		  &IngestHeader.tcf.dsp.DataMask, &iParam, iParam );
      Command.lPerformance = lAskRange( &Command.fBinStartKm, iParam ) ;
    }

  /* Open the desired parameter data file
   */
  strcpy( smomentfile, singest_env );
  strcat( smomentfile, Command.sSummaryFile );
  sptr = sIngestEnd( iParam, Command.iSweep );
  strcat( smomentfile, sptr );
  istatus = imapopen( smomentfile, 0, (void **)&pIngest, &isize, &ichannel );
  if( istatus != SS_NORMAL )
    {
      sig_signal( istatus );
      exit(EXIT_FAILURE);
    }

  /* Compute the starting range bin number. */
  printf( "Reading file: %s\n", smomentfile );
  {
    char sTimeBuffer[TIMENAME_SIZE];
    printf( "Sweep Time: %s\n",
	    shhmmssmmm_ddmonyyyy( &pIngest->IDhdr.time, sTimeBuffer ) ) ;
  }
  if (Command.lPerformance)
    iBinStart = 0;
  else
    {
      FLT4 fMaskStart, fMaskStep;
      fMaskStart = ((FLT4)IngestHeader.tcf.rng.ibin_first)/100000.0;
      fMaskStep  = ((FLT4)IngestHeader.tcf.rng.ibin_out_step)/100000.0;
      if (fMaskStep <= 0.0) fMaskStep = 1/100000.0;
      iBinStart = 1+NINT((Command.fBinStartKm - fMaskStart)/fMaskStep);
      if (iBinStart<1) iBinStart = 1;
      if (iBinStart>IngestHeader.tcf.rng.ibin_out_num) 
	iBinStart = IngestHeader.tcf.rng.ibin_out_num;
      Command.fBinStartKm = fMaskStart + fMaskStep*(FLT4)(iBinStart-1);
      printf( "Starting at range %4.2f km (bin %d), bin step: %4.2f km\n", 
	      Command.fBinStartKm, iBinStart, fMaskStep );
    }

  /* Loop through all the rays
   */
  last = FALSE;
  iray = 0;
  ClearRayAverages();
  while (0 == last)
    {
      const struct data_ray *pray;
      pray = GetRayFromFile( iray, pIngest, &last );

      /* Note that ray pointers are origin 1
       */
      lmissing = (pray==NULL);
      raylist( &IngestHeader.tcf, pray, &pIngest->IDhdr, iray, lmissing, iBinStart,
	       &IngestHeader, Command.iMaxLength );
      iray = iray+1;
    }
  ShowRayAverages( pIngest->IDhdr.idata, iBinStart, Command.iMaxLength );

  istatus = imapclose( pIngest, isize, ichannel );

  /* Exit, or just remain waiting here...
   */
  if( Command.lNoExit ) for(;;) sig_microSleep( 250000 ) ;
  else                  exit( EXIT_SUCCESS ) ;
}

/* =======================================================
 * Function to process the command line arguments.
 */
static void ProcessCommandLine
(int iArgc_a,
 char *sArgv_a[],
 struct rays_command_line *pCommand_a )
{
  int iArg, ilength;
  memset( pCommand_a, 0, sizeof(*pCommand_a) );

  pCommand_a->lVerbose = TRUE;
  pCommand_a->iSweep = 1;
  pCommand_a->iMaxLength = 85;

  for( iArg=1 ; iArg<iArgc_a ; iArg++ )
    {
      const char *sArg = sArgv_a[iArg];
      char *sEnd;

      if ( sArg[0] == '-' )
	{
	  if ( 0 == strncasecmp( sArg, "-data:", 6 ))
	    {
	      ilength = sizeof(pCommand_a->sDataType);
	      strncpy( pCommand_a->sDataType, &sArg[6], ilength-1 );
	      pCommand_a->sDataType[ilength-1] = 0;
	    }
	  else if( ( 0 == strncasecmp( sArg, "-h", 2 ) ) ||
		   ( 0 == strncasecmp( sArg, "-?", 2 ) ) )
	    {
	      usage();
	    }
	  else if ( 0 == strncasecmp( sArg, "-if:", 4 ))
	    {
	      ilength = sizeof(pCommand_a->sSummaryFile);
	      strncpy( pCommand_a->sSummaryFile, &sArg[4], ilength-1 );
	      pCommand_a->sSummaryFile[ilength-1] = 0;
	    }
	  else if ( 0 == strncasecmp( sArg, "-in", 3 ))
	    {
	      pCommand_a->lInteractive = TRUE;
	    }
	  else if ( 0 == strncasecmp( sArg, "-p", 2 ))
	    {
	      pCommand_a->lPerformance = TRUE;
	    }
	  else if ( 0 == strncasecmp( sArg, "-range:", 7 ))
	    {
	      pCommand_a->fBinStartKm = strtod( &sArg[7], &sEnd );
	      if (&sArg[7]==sEnd) usage();
	    }
	  else if ( 0 == strncasecmp( sArg, "-sweep:", 7 ))
	    {
	      pCommand_a->iSweep = strtol( &sArg[7], &sEnd, 10 );
	      if (&sArg[7]==sEnd) usage();
	    }
	  else if ( 0 == strncasecmp( sArg, "-t", 2 ))
	    {
	      pCommand_a->lVerbose = FALSE;
	    }
	  else if ( 0 == strncasecmp( sArg, "-noexit", 7 ))
	    {
	      pCommand_a->lNoExit = TRUE ;
	    }
	  else if ( 0 == strncasecmp( sArg, "-width:", 7 ))
	    {
	      pCommand_a->iMaxLength = strtol( &sArg[7], &sEnd, 10 );
	      if (&sArg[7]==sEnd) usage();
	      if (pCommand_a->iMaxLength<10)  pCommand_a->iMaxLength=10;
	      if (pCommand_a->iMaxLength>200) pCommand_a->iMaxLength=200;
	    }
	}
      else
	{
	  /* For backwards compatibility, all unlabeled args are assumed to be
	   * the input filename.
	   */
	  ilength = sizeof(pCommand_a->sSummaryFile);
	  strncpy( pCommand_a->sSummaryFile, sArg, ilength-1 );
	  pCommand_a->sSummaryFile[ilength-1] = 0;
        }
    }
}

static void usage( void )
{
  fprintf( stderr, "rays options:\n");
  fprintf( stderr, "    -help        -- Print this list\n");
  fprintf( stderr, "    -data:<data> -- Specify the data type to display\n");
  fprintf( stderr, "   [-if:]<file>  -- Specify the ingest summary file\n");
  fprintf( stderr, "    -inter       -- Run in interactive mode\n");
  fprintf( stderr, "    -perf        -- Performance only (no data)\n");
  fprintf( stderr, "    -range:#     -- Specify the starting range in km.\n");
  fprintf( stderr, "    -sweep:#     -- Specify the sweep number origin 1\n");
  fprintf( stderr, "    -terse       -- Skip showing ingest header info\n");
  fprintf( stderr, "    -width:#     -- Specify maximum line length\n");
  fprintf( stderr, "    -noExit      -- Do not exit when done\n");
  exit(EXIT_FAILURE) ;
}
/* ====================================================================
 * This subroutine asks the user for a ingest summary file name.
 */
static void AskFile
(char sSummaryFile_a[FILENAME_SIZE])
{
  SINT4 ilength;
  char sline[80], *sResult, *sReply;

 L1000:
  printf( "Please enter the ingest summary file name: " );
  sResult = fgets( sline, 70, stdin );
  if (NULL == sResult)
    ilength = 0;
  else
    ilength = strlen(sline)-1;

  /* Remove the trailing Carriage return
   */
  sline[ilength] = 0;
  sReply = strtok( sline, " \t" );

  if (!sReply)
    {
      printf( "Sorry, file name is required!\n" );
      goto L1000;
    }
  strncpy( sSummaryFile_a, sReply, FILENAME_SIZE-1 );
  sSummaryFile_a[FILENAME_SIZE-1]=0;
         
  return;
} 
