#!/usr/local/bin/perl -w 

### $Id: afs.pl,v 1.10 2004/09/28 14:00:17 glennh Exp $
### Author: Glenn Hamell 
### NAME: afs.pl 
# This software is Copyright (C) 2005 ACE Science Center,
# California Institute of Technology. The software is provided to you
# without charge, and with no warranty. You may give away copies of
# this software, including sources, provided that this notice is included
# in all the files.
#
###
###
### SYNTAX:  $results = afs.pl [[[parm1] parm2] parm3]... ;
###	Example:
###		perl  afs.pl mag 1hr year day hr Br -s 03 330 -e 03 332
###
###		afs.pl mag [args...] > foo	Output to file
###
###		afs.pl mag [args...] | more	Output to another pgm
###
###
### PURPOSE:	Return tabular ACE data from ASC database.
###	
###
### INPUT:	Command line parmeter string
###		Modified H file          (retrieved from ASC web site)
###		ASC archived Data file   (retrieved from ASC web site)
###	
###	
### OUTPUT:	Requested data appears at the Standard Output (STDOUT).
###		STDERR recvs dbug o/p
###
### RETURN:	
###	
###
### MODIFICATION HISTORY: 
### =====================
### 2005Dec20-GRH-SWICS 1hr works
### 2005Dec19-GRH-SWICS 2hr works -- Starting on SWICS 1hr.
### 2005Dec15-GRH-Restart SWICS mods.
### 2005Dec13-GRH-Finished mods to enable the EPAM instrument.
###	Started mods to enable SWICS instrument.
### 2005Dec08-GRH-Starting mods to enable the EPAM instrument.
### 2004Sep28-GRH-New cmd line terms: stacked, overplot, logarithmic,
###	linear, samerange, multirange, x_day, x_year, x_epoch,
###	x_records, -ytitle, -title, url
### 2004Sep20-GRH-Start merging the "afs_plot.pl" functionality
###	into this program.
### 2004Sep20-GRH-Move the subroutines into a ".pm" module.
###	Added hook for an "error handler". This needs to be developed.  
###	Most mods relate to the passing of arguments by reference.
###	Another area was the transfer of tables of constants from 
###	the program script into a reference file.
###	The idea: the reference file will live at ASC. 
###	As instruments are added, the distributed pgm will not have 
###	to be updated; just add & modify tables in the reference
###	file back at the ASC.
### 2004Sep13-GRH-Dr.D. rpts a bug w/swepam implementation. Fixed it.
### 2004Sep06-GRH-Start mods to add SWEPAM instrument.
### 2004Jun05-GRH-Got it running.
###	Cleaned up code- added more/deleted some comments & dbug stmnts.
### 2004Jun04-GRH-Implemented "$req=POST $ASCurl, [ @parms ] "
### 2004Jun02-GRH-Implement fetching of afs_h_mag.txt from web site.
### 2004Jun01-GRH-Ensure DOY values have no leading zeros.
### 2004Jun01-GRH-Mod code to only expect and hamdle "mag" requests.
### 2004May26-GRH-Changed the "-s" & "-e" date fmt 
###	to -s yyyy ddd & -e yyyy ddd 
### 2004May25-GRH-Changed the (dot)H file 1st column names, those that 
###	are expected on the command line, to conform with the names 
###	displayed to the user in the heading of a responce.
### 2004Apr29-GRH-changed name of H file 
###	to "afs_H_mag.txt"    from "afs_H_mag_1hr.txt".
###	This allows all instument requests to use one file.
### 2004Apr...GRH-On-going refinements to handling of cmdline parameters.
### 2004Apr22-GRH-Removed most debugging comments.
###	Removed write-to-file ($wf) flag .
###	Removed tests based upon $wf & reformed structured indentations. 
### 2004Apr21-GRH-1st functioning version saved in RCS
###	Starting a major mod: 
###		Make the __DATA__ text into a separate file module.
### 2004Apr14 - Glenn Hamell, Created. 
###
###################################################

$dbug = 0;			# Debug stmnts: 1=ON,  0=OFF

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use afs_subs;

sub get_instyp_avgtyp(\@\@\@);
sub set_ASCurl($);
sub is_valid_inst_avg($$\@);


$ua = LWP::UserAgent->new();

@t = ();	# Tags (parameters) list
$msg="";	# Can pass to "Error_Handler"

# Flags: dbug, plotting, url(a valid flag when plotting)
%flags = ( "dbug" => $dbug, 
	   "plot" => 0, 
	   "url"  => 0 );

# Calls to init routines (below) are found in the afs_subs.pm module

# Init values used to build the ref value in ";tag=1962,ref=X,s=0"
@avg_types  =();
@avg_time_rv=();

# This is the first call to any routine in the ".pm" module.
# Inits globals within the ".pm" module.

afs_init_rv( \@avg_types, \@avg_time_rv, \%flags );

printf STDERR "DBUG: \@avg_types=@avg_types \n" if( $dbug );
printf STDERR "DBUG: \@avg_time_rv=@avg_time_rv \n" if(	$dbug );

@known_instruments=();
get_known_instruments( \@known_instruments );

printf STDERR "DBUG: \@known_instruments=@known_instruments \n" if( $dbug );

tr/A-Z/a-z/ for @avg_types  ;   # ensure all lowercase for comparisons
 
@Hpn = ();	# Parameter Names from "H" table(for matching cmdline params)
@Hqn = ();	# Query     Names from "H" table(1st of param pair for "POST")
@Hval= ();	# Values          from "H" table(2nd of param pair for "POST")

#  Load up a set of input parms for debug/testing...
if(( $dbug ) || ( $#ARGV < 0 )) {
#  @ARGV = ( 'mag', '1hr', 'year', 'day', 'hr', 'min', 'sec', 
#            'BR', 'BT', '-s', '2003', '031', '-e', '2003', '032' );
#  @ARGV = ( 'swepam', '1hr', 'year', 'day', 'hr', 'min', 'sec', 
#            'density', '4He_H+', '-s', '2003', '031', '-e', '2003', '032' );
#  @ARGV = ( "epam", "1hr", "year", "day", "hr", "min", "sec", 
#            "P1", "DE1", "E1p", "unc_P1p", "unc_FP7", 
#	    "-s", "2003", "031", "-e", "2003", "032" );
  @ARGV = ( "swics", "1hr", "year", "day", "hr", "min", 
            "nHe2", "vHe2", "vC5", "avqFe_qual", "FetoO", "FetoO_qual",
            "MgtoO_qual", "SitoO", "SitoO_qual", 
	    "-s", "2003", "031", "-e", "2003", "032" );
#  @ARGV = ( 'mag', 
#            '-ytitle', 'I Can Read This?', 'range',
#            '1hr', '-title', "X vs Y", 'linear', 
#            'overplot', 'x_records',
#            '-s', '2003', '031', 
#            '-e', '2003', '033',
#            'BT', 'bgse_z', url );

}

printf STDERR "DBUG: What came in?? args=@ARGV \n" if( $dbug );

# Move cmdline args into local table & set flags
@parms= () ;
get_cmdline_parms( \@parms );

# Pick out the params for defining the data type & avg interval
($instyp, $avgtyp) = get_instyp_avgtyp( @parms, @known_instruments, @avg_types );

if( is_valid_inst_avg( $instyp, $avgtyp, @known_instruments ) ) { # 0=valid
  $msg="BAD instrument name or BAD inst/avg combination.\n";
  $msg=$msg . "    instrument: '" . $instyp . "'";
  $msg=$msg . "    avg: '" . $avgtyp . "'";
  Error_Handler( MSG => $msg );
  exit;
}

printf STDERR "DBUG: instyp= '$instyp'   avgtyp='$avgtyp' \n" if($dbug) ;

$ASCurl = set_ASCurl( $instyp );

printf STDERR "DBUG: \$ASCurl= '$ASCurl' \n" if($dbug) ;

# Init the H tables of strings & their assoc. values
get_afs_h_file( $instyp, \@Hpn, \@Hqn, \@Hval );

# Construct strings for "hidden" values:
#	filename fragment values for:
#		VDATA_NAME, F-name
#	Also setup values for:
#		avg_time, vh_start &/or vh_end values
gen_hidden_value_str( $instyp, $avgtyp, \@parms, \@Hpn, \@Hval, \@avg_types, \@avg_time_rv );

# Need to make something that looks "sort of like" this...

#my $req = POST 'http://www.srl.caltech.edu/cgi-bin/dib/rundibviewmagl2/ACE/ASC/DATA/level2/mag',
#       [   NFIELDS	=> "32"
#	 , avg_time	=> "3"
#	 , VH_YFIELD	=> "0"
#	 , VH_YFIELD	=> "2"
#	 , VH_YFIELD	=> "3"
#	 , VH_YFIELD	=> "10"
#	 , VH_YFIELD	=> "11"
#	 , VH_YFIELD	=> "12"
#	 , VH_YFIELD	=> "13"
#	 , VDATA_NAME	=> "MAG_data_1hr"
#	 , "retrieve type"=> "2"
#	 , hdfref	=> ";tag=1962,ref=3,s=0"
#	 , f_name      	=> "mag_data_1hr.hdf"
#	 , display_mode	=> "3"
#	 , VH_START	=> "03/330"
#	 , VH_END	=> "03/332"
#       ];

# Start building strings like shown above
build_rqst_parms( \@parms,\@Hpn,\@Hqn,\@Hval,\@t );

my $res = "" ;		# prepare a response string variable
if( $dbug) {
  for( my $i=0; $i <= $#t; $i++ ) {
    printf STDERR "'$t[$i]'\n";
  }
  printf STDERR '"'.$ASCurl.', [ @t ]'."\n" ;
  printf STDERR '@t: '."@t \n";
}

my $req = POST $ASCurl, [ @t ] ;

$res = $ua->request($req)->as_string;

if( $flags{plot} ) {	# Plotting??
  if( $flags{url} ) {	# is URL requested? (1=yes)

    @L = split(/img src=/, $res );
    @L = split(/>/, $L[1] );
    $res = $L[0] ;

  } else {
    remove_header( \$res );
  }
}

printf STDOUT $res;	# Show the response
  if( $flags{url} ) {	# is URL requested? (1=yes)
     printf STDOUT "\n";
  }
     
#------------- end main---------------------------------


#========= begin  SUB_NAME  ===========

sub Sub_Name {

  # Description goes here
  $rtn_val = 0;
  return( $rtn_val );
}
#--------  end  Sub_Name ------------
