#!/usr/bin/perl
#
# Name:         $OPTHOME/optbin/download-2
# Purpose:      part of JGOFS data download package
#		can we find the requested data object and
#		how should dataset be split into multiple small files
#		select listm options
#
# Modification history:
# Dec 98.clc. under development.
# 981017.clc. trap error (&x) returned from listvar.
# 981018.clc. add build-download-env.plx
# 981223.clc. work on bulk=onebig sub one_proc, maxlev=0
# 981230.clc. use fullobject name; change object passed back for retry
# 990210.clc. pass along compress variable
# 990224.clc. remove debug footer.
# 990305.clc. change defn of listvar; allow user to select listm options
# 990311.clc. make separtor char options radio buttons.
# 990312.clc. allow listm options selection for one-big file too;
#		fix radio button bug; appearance mods.
# 990313.clc. change formatting options appearance.
# 990322.clc. add subselection capability for one big file pkg type.
# 990325.clc. listvar error msgs begin with "&x "
# 990526.clc. add help button.
# 990614.clc. remove DBG lines.
# 990616.clc. pass subselctions to download-problem; minor details.
# ###### download version 1.0
# 990621. clc. port to OO server for installation/testing.
# 990715. clc. direcpage changes; optsmenu.
# 990720/991025. rcg/clc. send listvar output to STDERR
# 991122-24.clc. mods for merge with rest of oopt software; 
#		dobject; subsdisp; dtempdir
# 991201.clc. merge/debug with ooptserver on synthesis; dispobj; fmt header
# 991203.clc. goto jg/dir if no object
# 991206.clc. use OBJEXT to fix remote object bug
# 991209.clc. allow object with subsels to be pkgd into multiple files
# ###### download version 1.1  (991209)
#
# =====================================================================

require "cgi-lib.pl";

MAIN:
{

  print STDERR " DWNLD: using script: $0 \n";

  # color palette
  $credhi = "indianred";
  $chdrbar1 = "skyblue";
  $cgobar = "mediumaquamarine";
  
  $previous_page = $ENV{'HTTP_REFERER'};	# page we just came from
#
# These variables set by makefile from ENVars at install time
#
  $jgtopdir  = "/home/data1/www/optserver";		# top of JGOFS tree
  $jgbindir  = "$jgtopdir"."/bin";		# JGOFS binary execs
  $jgscdir   = "/jg";		# where are CGI scripts?
  $webimages = "http://optserv2.whoi.edu:80/images";   	# where are web images?
  $helpaddr  = "http://optserv2.whoi.edu:80";		# URL for web help docs
  $jgdatadir = "http://mvcodata.whoi.edu/jg/dir";		# JGOFS data directory server
  $optsmenu  = "http://optserv2.whoi.edu:80/jg/otheropt";		# JGOFS other options menu
#  
# Read in all the variables set by the form
#
  &ReadParse(*input);
 
  $listvar="$jgbindir"."/listvar -l";
  $dobject = "$input{'dobject'}";
  $dobjext = "$input{'dobjext'}";	# jgofs object string with extension
  $dispobj = "$input{'dispobj'}";	# jgofs object+(QS) for display
  $objnameonly = substr($dobject,rindex($dobject,"/")+1);
  $subsels = "$input{'subsels'}";
  $subsdisp = "$input{'subsdisp'}";

  # Print the header
  print &PrintHeader;    
  print <<ENDOFTEXT; 
   <BODY BGCOLOR="#FBFBFF">
   <h1>Data download continuing ...</h1>
   <b>Current object is:  $dispobj</b></br>
   <hr noshade><p>
ENDOFTEXT
#
# Access data object 
# entire list of variable names goes into array, 
#        each preceded by and separated from its level by a comma
#        and each on a separate line.
#
  print STDERR (" DWNLD: $listvar $dobject \n");
  @level_varlist = `$listvar "$dobject"`;
  $varinfo = $level_varlist[0];
#
#Test for errors returned from listvar
# ie. &x Error - not found: Cannot be found in dictionary: 'dobject'
# if $varinfo begins with "&x " then tell user and bail
#
  if ( $varinfo =~ /^&x / ) {
    &we_have_a_problem($varinfo);

  } else {
#
# ... no errors, we have a valid data object
#
   print <<ENDOFTEXT; 
   <form method="post" action="$jgscdir/download-3">
ENDOFTEXT
   print "<H3>Data will be packaged into \n"; 
    
   if ($input{'bulk'} eq "onebig") {
     print "one file.</H3></B></FONT> \n";
     &one_proc;
   } else {
     print "multiple smaller files.</H3></B></FONT> \n";
     &many_proc;
   }
  }

#
# Close the document cleanly
#
  print &HtmlBot;
}


sub one_proc {

 $maxlev=0;
 
 &select_listm_options;
 
 print <<ENDOFTEXT; 
 <input type="hidden" name="dobject" value="$input{'dobject'}">
 <input type="hidden" name="dobjext" value="$input{'dobjext'}">
 <input type="hidden" name="dispobj" value="$dispobj">
 <input type="hidden" name="bulk" value="$input{'bulk'}">
 <input type="hidden" name="maxlev" value="$maxlev">
 <input type="hidden" name="compress" value="$input{'compress'}">
 <input type="hidden" name="subsels" value="$input{'subsels'}">
 <input type="hidden" name="subsdisp" value="$input{'subsdisp'}">
 <input type="hidden" name="dtempdir" value="$input{'dtempdir'}">
 <TABLE BORDER=0 WiDTH=100% CELLSPACING=0 CELLPADDING=5>
  <TR><TD BGCOLOR="$cgobar">
   <H3><font color=black><input width="80" type="submit" value="Go"></font>
  </TR></TABLE></H3></form>
ENDOFTEXT

}


sub many_proc {

  print <<ENDOFTEXT; 
  <TABLE WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING=6>
  <TR><TD COLSPAN=3 BGCOLOR="$chdrbar1">
    <H3>How would you like to divide up your data?</TD>
    <TD BGCOLOR="$chdrbar1">
      <A HREF="$helpaddr/download-help.html#params"><img alt="[HELP]" 
      align=absmiddle border=0 src="$webimages/helpbutton.gif"></A></TD>
  </TR></H3></TABLE>
ENDOFTEXT

  foreach $var (@level_varlist) {
    ($level,$varname) = split /, /,$var; 
    $whichlevel[$level].=$varname;
  }
  
  $maxlev = $level;

  if ($maxlev > 0) {
   # Good, we have at least 1 level to determine multi file output.  
   $button="Go";
   $submit_msg="to continue with the next form.";

   print <<ENDOFTEXT;
   <dl>
   <dt>
    
ENDOFTEXT
   
   foreach $lev (0..$maxlev-1) {
     print "<dd><select name=\"determine$lev\">";
     print "<option selected>Pick one parameter at level $lev\n";
     foreach $item (split /\n/, $whichlevel[$lev]) {
        print "<option>$item";
     }
     print "</select>";
   }
   print "</dl><p>";
   
   &select_listm_options;
     
  } else {
   
   # Need to redirect user if they requested multi file output, 
   # but maxlev=0 (only 1 level, the object name), meaning 
   # the data has not been levelized.  Someday I'll use listvar 
   # on another form to present user with some logical options.
      $submit_msg=" to submit a request for assistance.";
      $button="Help";
      print <<ENDOFSORRY; 
      Sorry, but this data has not yet been levelized.
      In the future we hope to provide for this situation.
      For now, please go <A HREF=\"$previous_page$ENV{'PATH_INFO'}\"><B>back</B></A>, 
      or use your Browser's <B>Back Button</B> 
      and try one big file instead.<p>  
      <form method="post" action="$jgscdir/download-problem">
ENDOFSORRY

   }

#
# pass along rest of user response information
#
print <<ENDOFSUB;
<P>
<input type="hidden" name="dobject" value="$input{'dobject'}">
<input type="hidden" name="dobjext" value="$input{'dobjext'}">
<input type="hidden" name="dispobj" value="$dispobj">
<input type="hidden" name="bulk" value="$input{'bulk'}">
<input type="hidden" name="maxlev" value="$maxlev"> 
<input type="hidden" name="compress" value="$input{'compress'}">
<input type="hidden" name="subsels" value="$input{'subsels'}">
<input type="hidden" name="subsdisp" value="$input{'subsdisp'}">
<input type="hidden" name="dtempdir" value="$input{'dtempdir'}">
<TABLE BORDER=0 WiDTH=100% CELLSPACING=0 CELLPADDING=5>
  <TR><TD BGCOLOR="$cgobar">
   <H3><font color=black><input width="80" type="submit" value="Go"></font>
  </TR></TABLE></H3></form>

ENDOFSUB

}


sub select_listm_options {
# allow user to select which listm options to use
# We force listm output to be nonstop, flat file, no comments (-n -f -c)
# Optional command line listm options: 
#     -s   space-separated
#     -t   tab-separated
#     -b   brief flat file (no header info)
#     -m   missing value converted to -9999.0
#     -z   delete extra spaces

  $option_list = "-n -f -c ";

  print <<END_OF_TEXT;
  <input type="hidden" name="opt_defs" value="$option_list">
  <TABLE WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING=6>
  <TR><TD COLSPAN=3 BGCOLOR="$chdrbar1">
    <H3>Data file formatting options: </TD>
    <TD BGCOLOR="$chdrbar1">
      <A HREF="$helpaddr/download-help.html#format"><img alt="[HELP]" 
      align=absmiddle border=0 src="$webimages/helpbutton.gif"></A></TD>
  </TR></H3></TABLE><BR>
  The default is to generate a space-separated file with column header 
  information, and data visually aligned in columns, suitable for importing 
  into a spreadsheet program. You may override this by selecting options 
  from the list below.
  <P>
  Select the character with which to separate data fields and whether you want 
  your data visually aligned in columns? <BR>
  <SELECT NAME="opt_sep">
  <option value="-s " SELECTED> space-separated, data aligned in columns 
  <option value="-t "> tab-separated, data aligned in columns 
  <option value=" "> comma-separated, data aligned in columns
  <option value="-z "> comma-separated (no columnar alignment)
  </SELECT>
  <P>
  Additional data formatting options: 
   <TABLE BORDER="0" CELLSPACING="10">  
   <TR>
    <TD COLSPAN=3><input type="checkbox" name="opt_brief" value="-b "> brief (no column headers)</TD>
    <TD COLSPAN=3><input type="checkbox" name="opt_msval" value="-m "> convert missing values to -9999.0</TD>
    </TR>   
  </TABLE>
END_OF_TEXT

}


sub we_have_a_problem {
  $errsta = "0";
  @errmsg = @_ ;
  print STDERR " DWNLD: status=$errsta, errormsg= @errmsg \n";

#
# get ready to pass the data object and QUERY_STRING back
#
  $back_to_opts = "$optsmenu"."$dobjext"."?"."$subsels";
print <<ENDOFSUB;
  Sorry, we have encountered a problem processing the $objnameonly data:<BR>
  @errmsg
  
  <BR><PRE><H3>
  Please go <A HREF=\"$previous_page\"><B>back</B></A> and try again, 
  or <A HREF="$back_to_opts">return</A> to the Plotting and Other Options menu,
  or the <A HREF="$jgdatadir">Data Directory</A> menu 
  or try using your browser's 'Go' menu to return and relocate the data object.</H3>
  </PRE>
  
  <form method="post" action="$jgscdir/download-problem">
  <input type="hidden" name="dobject" value="$input{'dobject'}">
  <input type="hidden" name="dobjext" value="$input{'dobjext'}">
  <input type="hidden" name="dispobj" value="$dispobj">
  <input type="hidden" name="subsels" value="$input{'subsels'}">
  <input type="hidden" name="subsdisp" value="$input{'subsdisp'}">
  <input type="hidden" name="dtempdir" value="$input{'dtempdir'}">
  <input type="hidden" name="bulk" value="$input{'bulk'}">
  <input type="hidden" name="maxlev" value="$maxlev">
  <input type="hidden" name="compress" value="$input{'compress'}">
  <input type="hidden" name="errsta" value="$errsta">
  <input type="hidden" name="errmsg" value="@errmsg">
  

  <H3>&nbsp or press <font color="blue"><input width="80" type="submit" value="help"></font> 
        to submit a request for assistance.</H3>
  </form>

  <p><HR SIZE=4 NOSHADE>
    
ENDOFSUB
}
