/* A Bison parser, made by GNU Bison 3.0.2.  */

/* Skeleton implementation for Bison LALR(1) parsers in Java

   Copyright (C) 2007-2013 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* As a special exception, you may create a larger work that contains
   part or all of the Bison parser skeleton and distribute that work
   under terms of your choice, so long as that work isn't itself a
   parser generator using the skeleton or a modified version thereof
   as a parser skeleton.  Alternatively, if you modify or redistribute
   the parser skeleton itself, you may (at your option) remove this
   special exception, which will cause the skeleton and the resulting
   Bison output files to be licensed under the GNU General Public
   License without this special exception.

   This special exception was added by the Free Software Foundation in
   version 2.2 of Bison.  */

package opendap.servers.parsers;
/* First part of user declarations.  */

/* "CeParser.java":37  */ /* lalr1.java:91  */

/* "CeParser.java":39  */ /* lalr1.java:92  */
/* "%code imports" blocks.  */
/* "ce.y":12  */ /* lalr1.java:93  */

import opendap.dap.*;
import opendap.dap.parsers.*;
import opendap.servers.*;
import java.io.*;
import java.util.*;

/* "CeParser.java":49  */ /* lalr1.java:93  */

/**
 * A Bison parser, automatically generated from <tt>ce.y</tt>.
 *
 * @author LALR (1) parser skeleton written by Paolo Bonzini.
 */
public class CeParser extends Ceparse
{
    /** Version number for the Bison executable that generated this parser.  */
  public static final String bisonVersion = "3.0.2";

  /** Name of the skeleton that generated this parser.  */
  public static final String bisonSkeleton = "lalr1.java";

  /**
   * True if verbose error messages are enabled.
   */
  private boolean yyErrorVerbose = true;

  /**
   * Return whether verbose error messages are enabled.
   */
  public final boolean getErrorVerbose() { return yyErrorVerbose; }

  /**
   * Set the verbosity of error messages.
   * @param verbose True to request verbose error messages.
   */
  public final void setErrorVerbose(boolean verbose)
  { yyErrorVerbose = verbose; }

  /**
   * Communication interface between the scanner and the Bison-generated
   * parser <tt>CeParser</tt>.
   */
  public interface Lexer {
    /** Token returned by the scanner to signal the end of its input.  */
    public static final int EOF = 0;

/* Tokens.  */
    /** Token number,to be returned by the scanner.  */
    static final int SCAN_WORD = 258;
    /** Token number,to be returned by the scanner.  */
    static final int SCAN_STRINGCONST = 259;
    /** Token number,to be returned by the scanner.  */
    static final int SCAN_NUMBERCONST = 260;

    /**
     * Method to retrieve the semantic value of the last scanned token.
     * @return the semantic value of the last scanned token.
     */
    Object getLVal ();

    /**
     * Entry point for the scanner.  Returns the token identifier corresponding
     * to the next token and prepares to return the semantic value
     * of the token.
     * @return the token identifier corresponding to the next token.
     */
    int yylex () throws ParseException;

    /**
     * Entry point for error reporting.  Emits an error
     * in a user-defined way.
     *
     *
     * @param msg The string for the error message.
     */
     void yyerror (String msg);
  }

  /**
   * The object doing lexical analysis for us.
   */
  private Lexer yylexer;

  /**
   * Instantiates the Bison-generated parser.
   * @param yylexer The scanner that will supply tokens to the parser.
   */
  public CeParser (Lexer yylexer)
  {

    this.yylexer = yylexer;

  }

  private java.io.PrintStream yyDebugStream = System.err;

  /**
   * Return the <tt>PrintStream</tt> on which the debugging output is
   * printed.
   */
  public final java.io.PrintStream getDebugStream () { return yyDebugStream; }

  /**
   * Set the <tt>PrintStream</tt> on which the debug output is printed.
   * @param s The stream that is used for debugging output.
   */
  public final void setDebugStream(java.io.PrintStream s) { yyDebugStream = s; }

  private int yydebug = 0;

  /**
   * Answer the verbosity of the debugging output; 0 means that all kinds of
   * output from the parser are suppressed.
   */
  public final int getDebugLevel() { return yydebug; }

  /**
   * Set the verbosity of the debugging output; 0 means that all kinds of
   * output from the parser are suppressed.
   * @param level The verbosity level for debugging output.
   */
  public final void setDebugLevel(int level) { yydebug = level; }

  /**
   * Print an error message via the lexer.
   *
   * @param msg The error message.
   */
  public final void yyerror (String msg)
  {
    yylexer.yyerror (msg);
  }

  protected final void yycdebug (String s) {
    if (yydebug > 0)
      yyDebugStream.println (s);
  }

  private final class YYStack {
    private int[] stateStack = new int[16];

    private Object[] valueStack = new Object[16];

    public int size = 16;
    public int height = -1;

    public final void push (int state, Object value                            ) {
      height++;
      if (size == height)
        {
          int[] newStateStack = new int[size * 2];
          System.arraycopy (stateStack, 0, newStateStack, 0, height);
          stateStack = newStateStack;

          Object[] newValueStack = new Object[size * 2];
          System.arraycopy (valueStack, 0, newValueStack, 0, height);
          valueStack = newValueStack;

          size *= 2;
        }

      stateStack[height] = state;

      valueStack[height] = value;
    }

    public final void pop () {
      pop (1);
    }

    public final void pop (int num) {
      // Avoid memory leaks... garbage collection is a white lie!
      if (num > 0) {
        java.util.Arrays.fill (valueStack, height - num + 1, height + 1, null);

      }
      height -= num;
    }

    public final int stateAt (int i) {
      return stateStack[height - i];
    }

    public final Object valueAt (int i) {
      return valueStack[height - i];
    }

    // Print the state stack on the debug stream.
    public void print (java.io.PrintStream out)
    {
      out.print ("Stack now");

      for (int i = 0; i <= height; i++)
        {
          out.print (' ');
          out.print (stateStack[i]);
        }
      out.println ();
    }
  }

  /**
   * Returned by a Bison action in order to stop the parsing process and
   * return success (<tt>true</tt>).
   */
  public static final int YYACCEPT = 0;

  /**
   * Returned by a Bison action in order to stop the parsing process and
   * return failure (<tt>false</tt>).
   */
  public static final int YYABORT = 1;

  /**
   * Returned by a Bison action in order to start error recovery without
   * printing an error message.
   */
  public static final int YYERROR = 2;

  /**
   * Internal return codes that are not supported for user semantic
   * actions.
   */
  private static final int YYERRLAB = 3;
  private static final int YYNEWSTATE = 4;
  private static final int YYDEFAULT = 5;
  private static final int YYREDUCE = 6;
  private static final int YYERRLAB1 = 7;
  private static final int YYRETURN = 8;

  private int yyerrstatus_ = 0;

  /**
   * Return whether error recovery is being done.  In this state, the parser
   * reads token until it reaches a known state, and then restarts normal
   * operation.
   */
  public final boolean recovering ()
  {
    return yyerrstatus_ == 0;
  }

  /** Compute post-reduction state.
   * @param yystate   the current state
   * @param yysym     the nonterminal to push on the stack
   */
  private int yy_lr_goto_state_ (int yystate, int yysym)
  {
    int yyr = yypgoto_[yysym - yyntokens_] + yystate;
    if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate)
      return yytable_[yyr];
    else
      return yydefgoto_[yysym - yyntokens_];
  }

  private int yyaction (int yyn, YYStack yystack, int yylen) throws ParseException
  {
    Object yyval;

    /* If YYLEN is nonzero, implement the default value of the action:
       '$$ = $1'.  Otherwise, use the top of the stack.

       Otherwise, the following line sets YYVAL to garbage.
       This behavior is undocumented and Bison
       users should not rely upon it.  */
    if (yylen > 0)
      yyval = yystack.valueAt (yylen - 1);
    else
      yyval = yystack.valueAt (0);

    yy_reduce_print (yyn, yystack);

    switch (yyn)
      {
          case 8:
  if (yyn == 8)
    /* "ce.y":101  */ /* lalr1.java:489  */
    {projections(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 9:
  if (yyn == 9)
    /* "ce.y":106  */ /* lalr1.java:489  */
    {selections(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 10:
  if (yyn == 10)
    /* "ce.y":112  */ /* lalr1.java:489  */
    {yyval=projectionlist(parsestate,(Object)null,((yystack.valueAt (1-(1)))));};
  break;

  case 11:
  if (yyn == 11)
    /* "ce.y":114  */ /* lalr1.java:489  */
    {yyval=projectionlist(parsestate,((yystack.valueAt (3-(1)))),((yystack.valueAt (3-(3)))));};
  break;

  case 12:
  if (yyn == 12)
    /* "ce.y":120  */ /* lalr1.java:489  */
    {yyval=projection(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 13:
  if (yyn == 13)
    /* "ce.y":122  */ /* lalr1.java:489  */
    {yyval=((yystack.valueAt (1-(1))));};
  break;

  case 14:
  if (yyn == 14)
    /* "ce.y":127  */ /* lalr1.java:489  */
    {yyval=function(parsestate,((yystack.valueAt (3-(1)))),null);};
  break;

  case 15:
  if (yyn == 15)
    /* "ce.y":129  */ /* lalr1.java:489  */
    {yyval=function(parsestate,((yystack.valueAt (4-(1)))),((yystack.valueAt (4-(3)))));};
  break;

  case 16:
  if (yyn == 16)
    /* "ce.y":135  */ /* lalr1.java:489  */
    {yyval=segmentlist(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 17:
  if (yyn == 17)
    /* "ce.y":137  */ /* lalr1.java:489  */
    {yyval=segmentlist(parsestate,((yystack.valueAt (3-(1)))),((yystack.valueAt (3-(3)))));};
  break;

  case 18:
  if (yyn == 18)
    /* "ce.y":143  */ /* lalr1.java:489  */
    {yyval=segment(parsestate,((yystack.valueAt (1-(1)))),null);};
  break;

  case 19:
  if (yyn == 19)
    /* "ce.y":145  */ /* lalr1.java:489  */
    {yyval=segment(parsestate,((yystack.valueAt (2-(1)))),((yystack.valueAt (2-(2)))));};
  break;

  case 20:
  if (yyn == 20)
    /* "ce.y":151  */ /* lalr1.java:489  */
    {yyval=rangelist(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 21:
  if (yyn == 21)
    /* "ce.y":153  */ /* lalr1.java:489  */
    {yyval=rangelist(parsestate,((yystack.valueAt (2-(1)))),((yystack.valueAt (2-(2)))));};
  break;

  case 22:
  if (yyn == 22)
    /* "ce.y":159  */ /* lalr1.java:489  */
    {yyval=range(parsestate,((yystack.valueAt (1-(1)))),null,null);};
  break;

  case 23:
  if (yyn == 23)
    /* "ce.y":161  */ /* lalr1.java:489  */
    {yyval=range(parsestate,((yystack.valueAt (5-(2)))),null,((yystack.valueAt (5-(4)))));};
  break;

  case 24:
  if (yyn == 24)
    /* "ce.y":163  */ /* lalr1.java:489  */
    {yyval=range(parsestate,((yystack.valueAt (7-(2)))),((yystack.valueAt (7-(4)))),((yystack.valueAt (7-(6)))));};
  break;

  case 25:
  if (yyn == 25)
    /* "ce.y":167  */ /* lalr1.java:489  */
    {yyval = range1(parsestate,((yystack.valueAt (3-(2)))));};
  break;

  case 26:
  if (yyn == 26)
    /* "ce.y":174  */ /* lalr1.java:489  */
    {yyval=clauselist(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 27:
  if (yyn == 27)
    /* "ce.y":176  */ /* lalr1.java:489  */
    {yyval=clauselist(parsestate,((yystack.valueAt (2-(1)))),((yystack.valueAt (2-(2)))));};
  break;

  case 28:
  if (yyn == 28)
    /* "ce.y":182  */ /* lalr1.java:489  */
    {yyval=sel_clause(parsestate,1,((yystack.valueAt (6-(2)))),((yystack.valueAt (6-(3)))),((yystack.valueAt (6-(5)))));};
  break;

  case 29:
  if (yyn == 29)
    /* "ce.y":184  */ /* lalr1.java:489  */
    {yyval=sel_clause(parsestate,2,((yystack.valueAt (4-(2)))),((yystack.valueAt (4-(3)))),((yystack.valueAt (4-(4)))));};
  break;

  case 30:
  if (yyn == 30)
    /* "ce.y":186  */ /* lalr1.java:489  */
    {yyval=((yystack.valueAt (2-(1))));};
  break;

  case 31:
  if (yyn == 31)
    /* "ce.y":191  */ /* lalr1.java:489  */
    {yyval=value_list(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 32:
  if (yyn == 32)
    /* "ce.y":193  */ /* lalr1.java:489  */
    {yyval=value_list(parsestate,((yystack.valueAt (3-(1)))),((yystack.valueAt (3-(3)))));};
  break;

  case 33:
  if (yyn == 33)
    /* "ce.y":198  */ /* lalr1.java:489  */
    {yyval=value(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 34:
  if (yyn == 34)
    /* "ce.y":200  */ /* lalr1.java:489  */
    {yyval=value(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 35:
  if (yyn == 35)
    /* "ce.y":202  */ /* lalr1.java:489  */
    {yyval=value(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 36:
  if (yyn == 36)
    /* "ce.y":207  */ /* lalr1.java:489  */
    {yyval=constant(parsestate,((yystack.valueAt (1-(1)))),Lexer.SCAN_NUMBERCONST);};
  break;

  case 37:
  if (yyn == 37)
    /* "ce.y":209  */ /* lalr1.java:489  */
    {yyval=constant(parsestate,((yystack.valueAt (1-(1)))),Lexer.SCAN_STRINGCONST);};
  break;

  case 38:
  if (yyn == 38)
    /* "ce.y":214  */ /* lalr1.java:489  */
    {yyval=var(parsestate,((yystack.valueAt (1-(1)))));};
  break;

  case 39:
  if (yyn == 39)
    /* "ce.y":223  */ /* lalr1.java:489  */
    {yyval=indexpath(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 40:
  if (yyn == 40)
    /* "ce.y":225  */ /* lalr1.java:489  */
    {yyval=indexpath(parsestate,((yystack.valueAt (3-(1)))),((yystack.valueAt (3-(3)))));};
  break;

  case 41:
  if (yyn == 41)
    /* "ce.y":230  */ /* lalr1.java:489  */
    {yyval=index(parsestate,((yystack.valueAt (1-(1)))),null);};
  break;

  case 42:
  if (yyn == 42)
    /* "ce.y":232  */ /* lalr1.java:489  */
    {yyval=index(parsestate,((yystack.valueAt (2-(1)))),((yystack.valueAt (2-(2)))));};
  break;

  case 43:
  if (yyn == 43)
    /* "ce.y":238  */ /* lalr1.java:489  */
    {yyval=array_indices(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 44:
  if (yyn == 44)
    /* "ce.y":240  */ /* lalr1.java:489  */
    {yyval=array_indices(parsestate,((yystack.valueAt (2-(1)))),((yystack.valueAt (2-(2)))));};
  break;

  case 45:
  if (yyn == 45)
    /* "ce.y":245  */ /* lalr1.java:489  */
    {yyval=function(parsestate,((yystack.valueAt (3-(1)))),null);};
  break;

  case 46:
  if (yyn == 46)
    /* "ce.y":247  */ /* lalr1.java:489  */
    {yyval=function(parsestate,((yystack.valueAt (4-(1)))),((yystack.valueAt (4-(3)))));};
  break;

  case 47:
  if (yyn == 47)
    /* "ce.y":252  */ /* lalr1.java:489  */
    {yyval=arg_list(parsestate,null,((yystack.valueAt (1-(1)))));};
  break;

  case 48:
  if (yyn == 48)
    /* "ce.y":254  */ /* lalr1.java:489  */
    {yyval=arg_list(parsestate,((yystack.valueAt (3-(1)))),((yystack.valueAt (3-(3)))));};
  break;

  case 49:
  if (yyn == 49)
    /* "ce.y":259  */ /* lalr1.java:489  */
    {yyval=new Integer(EQUAL);};
  break;

  case 50:
  if (yyn == 50)
    /* "ce.y":260  */ /* lalr1.java:489  */
    {yyval=new Integer(GREATER);};
  break;

  case 51:
  if (yyn == 51)
    /* "ce.y":261  */ /* lalr1.java:489  */
    {yyval=new Integer(LESS);};
  break;

  case 52:
  if (yyn == 52)
    /* "ce.y":262  */ /* lalr1.java:489  */
    {yyval=new Integer(NOT_EQUAL);};
  break;

  case 53:
  if (yyn == 53)
    /* "ce.y":263  */ /* lalr1.java:489  */
    {yyval=new Integer(GREATER_EQL);};
  break;

  case 54:
  if (yyn == 54)
    /* "ce.y":264  */ /* lalr1.java:489  */
    {yyval=new Integer(LESS_EQL);};
  break;

  case 55:
  if (yyn == 55)
    /* "ce.y":265  */ /* lalr1.java:489  */
    {yyval=new Integer(REGEXP);};
  break;

  case 56:
  if (yyn == 56)
    /* "ce.y":269  */ /* lalr1.java:489  */
    {yyval = ((yystack.valueAt (1-(1))));};
  break;

  case 57:
  if (yyn == 57)
    /* "ce.y":273  */ /* lalr1.java:489  */
    {yyval=unescapeDAPName(((yystack.valueAt (1-(1)))));};
  break;

  case 58:
  if (yyn == 58)
    /* "ce.y":277  */ /* lalr1.java:489  */
    {yyval = ((yystack.valueAt (1-(1))));};
  break;

  case 59:
  if (yyn == 59)
    /* "ce.y":281  */ /* lalr1.java:489  */
    {yyval = ((yystack.valueAt (1-(1))));};
  break;

/* "CeParser.java":702  */ /* lalr1.java:489  */
        default: break;
      }

    yy_symbol_print ("-> $$ =", yyr1_[yyn], yyval);

    yystack.pop (yylen);
    yylen = 0;

    /* Shift the result of the reduction.  */
    int yystate = yy_lr_goto_state_ (yystack.stateAt (0), yyr1_[yyn]);
    yystack.push (yystate, yyval);
    return YYNEWSTATE;
  }

  /* Return YYSTR after stripping away unnecessary quotes and
     backslashes, so that it's suitable for yyerror.  The heuristic is
     that double-quoting is unnecessary unless the string contains an
     apostrophe, a comma, or backslash (other than backslash-backslash).
     YYSTR is taken from yytname.  */
  private final String yytnamerr_ (String yystr)
  {
    if (yystr.charAt (0) == '"')
      {
        StringBuffer yyr = new StringBuffer ();
        strip_quotes: for (int i = 1; i < yystr.length (); i++)
          switch (yystr.charAt (i))
            {
            case '\'':
            case ',':
              break strip_quotes;

            case '\\':
              if (yystr.charAt(++i) != '\\')
                break strip_quotes;
              /* Fall through.  */
            default:
              yyr.append (yystr.charAt (i));
              break;

            case '"':
              return yyr.toString ();
            }
      }
    else if (yystr.equals ("$end"))
      return "end of input";

    return yystr;
  }

  /*--------------------------------.
  | Print this symbol on YYOUTPUT.  |
  `--------------------------------*/

  private void yy_symbol_print (String s, int yytype,
                                 Object yyvaluep                                 )
  {
    if (yydebug > 0)
    yycdebug (s + (yytype < yyntokens_ ? " token " : " nterm ")
              + yytname_[yytype] + " ("
              + (yyvaluep == null ? "(null)" : yyvaluep.toString ()) + ")");
  }

  /**
   * Parse input from the scanner that was specified at object construction
   * time.  Return whether the end of the input was reached successfully.
   *
   * @return <tt>true</tt> if the parsing succeeds.  Note that this does not
   *          imply that there were no syntax errors.
   */
   public boolean parse () throws ParseException, ParseException

  {

    /* Lookahead and lookahead in internal form.  */
    int yychar = yyempty_;
    int yytoken = 0;

    /* State.  */
    int yyn = 0;
    int yylen = 0;
    int yystate = 0;
    YYStack yystack = new YYStack ();
    int label = YYNEWSTATE;

    /* Error handling.  */
    int yynerrs_ = 0;

    /* Semantic value of the lookahead.  */
    Object yylval = null;

    yycdebug ("Starting parse\n");
    yyerrstatus_ = 0;

    /* Initialize the stack.  */
    yystack.push (yystate, yylval );

    for (;;)
      switch (label)
      {
        /* New state.  Unlike in the C/C++ skeletons, the state is already
           pushed when we come here.  */
      case YYNEWSTATE:
        yycdebug ("Entering state " + yystate + "\n");
        if (yydebug > 0)
          yystack.print (yyDebugStream);

        /* Accept?  */
        if (yystate == yyfinal_)
          return true;

        /* Take a decision.  First try without lookahead.  */
        yyn = yypact_[yystate];
        if (yy_pact_value_is_default_ (yyn))
          {
            label = YYDEFAULT;
            break;
          }

        /* Read a lookahead token.  */
        if (yychar == yyempty_)
          {

            yycdebug ("Reading a token: ");
            yychar = yylexer.yylex ();
            yylval = yylexer.getLVal ();

          }

        /* Convert token to internal form.  */
        if (yychar <= Lexer.EOF)
          {
            yychar = yytoken = Lexer.EOF;
            yycdebug ("Now at end of input.\n");
          }
        else
          {
            yytoken = yytranslate_ (yychar);
            yy_symbol_print ("Next token is", yytoken,
                             yylval);
          }

        /* If the proper action on seeing token YYTOKEN is to reduce or to
           detect an error, take that action.  */
        yyn += yytoken;
        if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken)
          label = YYDEFAULT;

        /* <= 0 means reduce or error.  */
        else if ((yyn = yytable_[yyn]) <= 0)
          {
            if (yy_table_value_is_error_ (yyn))
              label = YYERRLAB;
            else
              {
                yyn = -yyn;
                label = YYREDUCE;
              }
          }

        else
          {
            /* Shift the lookahead token.  */
            yy_symbol_print ("Shifting", yytoken,
                             yylval);

            /* Discard the token being shifted.  */
            yychar = yyempty_;

            /* Count tokens shifted since error; after three, turn off error
               status.  */
            if (yyerrstatus_ > 0)
              --yyerrstatus_;

            yystate = yyn;
            yystack.push (yystate, yylval);
            label = YYNEWSTATE;
          }
        break;

      /*-----------------------------------------------------------.
      | yydefault -- do the default action for the current state.  |
      `-----------------------------------------------------------*/
      case YYDEFAULT:
        yyn = yydefact_[yystate];
        if (yyn == 0)
          label = YYERRLAB;
        else
          label = YYREDUCE;
        break;

      /*-----------------------------.
      | yyreduce -- Do a reduction.  |
      `-----------------------------*/
      case YYREDUCE:
        yylen = yyr2_[yyn];
        label = yyaction (yyn, yystack, yylen);
        yystate = yystack.stateAt (0);
        break;

      /*------------------------------------.
      | yyerrlab -- here on detecting error |
      `------------------------------------*/
      case YYERRLAB:
        /* If not already recovering from an error, report this error.  */
        if (yyerrstatus_ == 0)
          {
            ++yynerrs_;
            if (yychar == yyempty_)
              yytoken = yyempty_;
            yyerror (yysyntax_error (yystate, yytoken));
          }

        if (yyerrstatus_ == 3)
          {
        /* If just tried and failed to reuse lookahead token after an
         error, discard it.  */

        if (yychar <= Lexer.EOF)
          {
          /* Return failure if at end of input.  */
          if (yychar == Lexer.EOF)
            return false;
          }
        else
            yychar = yyempty_;
          }

        /* Else will try to reuse lookahead token after shifting the error
           token.  */
        label = YYERRLAB1;
        break;

      /*-------------------------------------------------.
      | errorlab -- error raised explicitly by YYERROR.  |
      `-------------------------------------------------*/
      case YYERROR:

        /* Do not reclaim the symbols of the rule which action triggered
           this YYERROR.  */
        yystack.pop (yylen);
        yylen = 0;
        yystate = yystack.stateAt (0);
        label = YYERRLAB1;
        break;

      /*-------------------------------------------------------------.
      | yyerrlab1 -- common code for both syntax error and YYERROR.  |
      `-------------------------------------------------------------*/
      case YYERRLAB1:
        yyerrstatus_ = 3;       /* Each real token shifted decrements this.  */

        for (;;)
          {
            yyn = yypact_[yystate];
            if (!yy_pact_value_is_default_ (yyn))
              {
                yyn += yyterror_;
                if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
                  {
                    yyn = yytable_[yyn];
                    if (0 < yyn)
                      break;
                  }
              }

            /* Pop the current state because it cannot handle the
             * error token.  */
            if (yystack.height == 0)
              return false;

            yystack.pop ();
            yystate = yystack.stateAt (0);
            if (yydebug > 0)
              yystack.print (yyDebugStream);
          }

        if (label == YYABORT)
            /* Leave the switch.  */
            break;

        /* Shift the error token.  */
        yy_symbol_print ("Shifting", yystos_[yyn],
                         yylval);

        yystate = yyn;
        yystack.push (yyn, yylval);
        label = YYNEWSTATE;
        break;

        /* Accept.  */
      case YYACCEPT:
        return true;

        /* Abort.  */
      case YYABORT:
        return false;
      }
}

  // Generate an error message.
  private String yysyntax_error (int yystate, int tok)
  {
    if (yyErrorVerbose)
      {
        /* There are many possibilities here to consider:
           - If this state is a consistent state with a default action,
             then the only way this function was invoked is if the
             default action is an error action.  In that case, don't
             check for expected tokens because there are none.
           - The only way there can be no lookahead present (in tok) is
             if this state is a consistent state with a default action.
             Thus, detecting the absence of a lookahead is sufficient to
             determine that there is no unexpected or expected token to
             report.  In that case, just report a simple "syntax error".
           - Don't assume there isn't a lookahead just because this
             state is a consistent state with a default action.  There
             might have been a previous inconsistent state, consistent
             state with a non-default action, or user semantic action
             that manipulated yychar.  (However, yychar is currently out
             of scope during semantic actions.)
           - Of course, the expected token list depends on states to
             have correct lookahead information, and it depends on the
             parser not to perform extra reductions after fetching a
             lookahead from the scanner and before detecting a syntax
             error.  Thus, state merging (from LALR or IELR) and default
             reductions corrupt the expected token list.  However, the
             list is correct for canonical LR with one exception: it
             will still contain any token that will not be accepted due
             to an error action in a later state.
        */
        if (tok != yyempty_)
          {
            /* FIXME: This method of building the message is not compatible
               with internationalization.  */
            StringBuffer res =
              new StringBuffer ("syntax error, unexpected ");
            res.append (yytnamerr_ (yytname_[tok]));
            int yyn = yypact_[yystate];
            if (!yy_pact_value_is_default_ (yyn))
              {
                /* Start YYX at -YYN if negative to avoid negative
                   indexes in YYCHECK.  In other words, skip the first
                   -YYN actions for this state because they are default
                   actions.  */
                int yyxbegin = yyn < 0 ? -yyn : 0;
                /* Stay within bounds of both yycheck and yytname.  */
                int yychecklim = yylast_ - yyn + 1;
                int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
                int count = 0;
                for (int x = yyxbegin; x < yyxend; ++x)
                  if (yycheck_[x + yyn] == x && x != yyterror_
                      && !yy_table_value_is_error_ (yytable_[x + yyn]))
                    ++count;
                if (count < 5)
                  {
                    count = 0;
                    for (int x = yyxbegin; x < yyxend; ++x)
                      if (yycheck_[x + yyn] == x && x != yyterror_
                          && !yy_table_value_is_error_ (yytable_[x + yyn]))
                        {
                          res.append (count++ == 0 ? ", expecting " : " or ");
                          res.append (yytnamerr_ (yytname_[x]));
                        }
                  }
              }
            return res.toString ();
          }
      }

    return "syntax error";
  }

  /**
   * Whether the given <code>yypact_</code> value indicates a defaulted state.
   * @param yyvalue   the value to check
   */
  private static boolean yy_pact_value_is_default_ (int yyvalue)
  {
    return yyvalue == yypact_ninf_;
  }

  /**
   * Whether the given <code>yytable_</code>
   * value indicates a syntax error.
   * @param yyvalue the value to check
   */
  private static boolean yy_table_value_is_error_ (int yyvalue)
  {
    return yyvalue == yytable_ninf_;
  }

  private static final byte yypact_ninf_ = -35;
  private static final byte yytable_ninf_ = -57;

  /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
   STATE-NUM.  */
  private static final byte yypact_[] = yypact_init();
  private static final byte[] yypact_init()
  {
    return new byte[]
    {
       8,   -35,    15,     4,   -35,   -35,    51,    -5,   -35,    10,
     -35,   -35,    11,   -35,    -5,   -35,    21,    41,   -35,   -35,
     -35,    27,   -35,   -35,    13,   -35,   -35,    29,    42,   -35,
     -35,   -35,    39,    39,   -35,    23,    57,    40,   -35,   -35,
      43,    49,    50,    52,     7,    39,    31,    57,   -35,    59,
     -35,   -35,    40,   -35,    56,    62,    63,    46,   -35,   -35,
     -35,   -35,   -35,    51,   -35,   -35,    59,     5,    64,    55,
     -35,    51,   -35,    57,   -35,     9,   -35,     6,    66,    48,
      51,   -35,    57,   -35,   -35,    65,   -35
    };
  }

/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
   Performed when YYTABLE does not specify something else to do.  Zero
   means the default is an error.  */
  private static final byte yydefact_[] = yydefact_init();
  private static final byte[] yydefact_init()
  {
    return new byte[]
    {
       7,     6,     0,     0,     1,    57,     0,     2,     3,     8,
      10,    13,    12,    16,     9,    26,     0,    18,    59,    58,
      34,     0,    35,    33,    38,    39,    30,     0,    41,    36,
      37,     4,     0,     0,    27,     0,     0,    19,    20,    22,
      49,    50,    51,     0,     0,     0,     0,     0,    43,    42,
      11,    17,    18,    14,     0,    31,     0,     0,    21,    55,
      53,    54,    52,     0,    29,    40,    41,    14,     0,     0,
      44,     0,    15,     0,    25,     0,    31,    15,    32,     0,
       0,    28,     0,    23,    32,     0,    24
    };
  }

/* YYPGOTO[NTERM-NUM].  */
  private static final byte yypgoto_[] = yypgoto_init();
  private static final byte[] yypgoto_init()
  {
    return new byte[]
    {
     -35,   -35,   -35,   -35,    69,   -35,    45,     1,   -35,    47,
     -35,    44,   -25,   -35,    68,    16,    -6,   -35,   -35,   -35,
      38,   -35,   -35,    53,   -35,    78,    -2,   -34,   -35
    };
  }

/* YYDEFGOTO[NTERM-NUM].  */
  private static final byte yydefgoto_[] = yydefgoto_init();
  private static final byte[] yydefgoto_init()
  {
    return new byte[]
    {
      -1,     2,     3,     7,     8,     9,    10,    20,    12,    13,
      37,    38,    39,    14,    15,    54,    55,    22,    23,    24,
      25,    49,    26,    56,    44,    16,    28,    29,    30
    };
  }

/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM.  If
   positive, shift that token.  If negative, reduce the rule whose
   number is the opposite.  If YYTABLE_NINF, syntax error.  */
  private static final byte yytable_[] = yytable_init();
  private static final byte[] yytable_init()
  {
    return new byte[]
    {
      21,    17,    57,    48,    11,   -45,   -46,     5,    -5,     6,
       5,    18,    19,    69,     1,     4,    80,    32,     6,   -45,
     -46,    33,    63,    45,    70,    81,     5,    18,    19,    35,
      17,    52,    53,    11,     5,    18,    19,    46,    64,    79,
      67,    48,     5,    66,    40,    41,    42,    43,    85,   -56,
     -56,    36,    36,    47,     5,    18,    19,    76,    73,    74,
      82,    83,    19,    71,    59,    78,    60,    61,    74,    62,
      47,   -47,    72,    77,    84,   -48,    31,    50,    86,    75,
      51,    58,    34,    65,    27,     0,     0,     0,     0,     0,
       0,     0,     0,     0,     0,     0,     0,     0,     0,    68
    };
  }

private static final byte yycheck_[] = yycheck_init();
  private static final byte[] yycheck_init()
  {
    return new byte[]
    {
       6,     3,    36,    28,     3,     0,     0,     3,     0,    14,
       3,     4,     5,    47,     6,     0,     7,     7,    14,    14,
      14,    10,    15,    10,    49,    16,     3,     4,     5,     8,
      32,    33,     9,    32,     3,     4,     5,     8,    44,    73,
       9,    66,     3,    45,    17,    18,    19,    20,    82,     8,
       8,    11,    11,    11,     3,     4,     5,    63,    12,    13,
      12,    13,     5,     7,    21,    71,    17,    17,    13,    17,
      11,     9,     9,     9,    80,     9,     7,    32,    13,    63,
      33,    37,    14,    45,     6,    -1,    -1,    -1,    -1,    -1,
      -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    -1,    46
    };
  }

/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
   symbol of state STATE-NUM.  */
  private static final byte yystos_[] = yystos_init();
  private static final byte[] yystos_init()
  {
    return new byte[]
    {
       0,     6,    23,    24,     0,     3,    14,    25,    26,    27,
      28,    29,    30,    31,    35,    36,    47,    48,     4,     5,
      29,    38,    39,    40,    41,    42,    44,    47,    48,    49,
      50,    26,     7,    10,    36,     8,    11,    32,    33,    34,
      17,    18,    19,    20,    46,    10,     8,    11,    34,    43,
      28,    31,    48,     9,    37,    38,    45,    49,    33,    21,
      17,    17,    17,    15,    38,    42,    48,     9,    45,    49,
      34,     7,     9,    12,    13,    37,    38,     9,    38,    49,
       7,    16,    12,    13,    38,    49,    13
    };
  }

/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
  private static final byte yyr1_[] = yyr1_init();
  private static final byte[] yyr1_init()
  {
    return new byte[]
    {
       0,    22,    23,    23,    23,    23,    24,    24,    25,    26,
      27,    27,    28,    28,    29,    29,    30,    30,    31,    31,
      32,    32,    33,    33,    33,    34,    35,    35,    36,    36,
      36,    37,    37,    38,    38,    38,    39,    39,    40,    41,
      41,    42,    42,    43,    43,    44,    44,    45,    45,    46,
      46,    46,    46,    46,    46,    46,    47,    48,    49,    50
    };
  }

/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.  */
  private static final byte yyr2_[] = yyr2_init();
  private static final byte[] yyr2_init()
  {
    return new byte[]
    {
       0,     2,     2,     2,     3,     0,     1,     0,     1,     1,
       1,     3,     1,     1,     3,     4,     1,     3,     1,     2,
       1,     2,     1,     5,     7,     3,     1,     2,     6,     4,
       2,     1,     3,     1,     1,     1,     1,     1,     1,     1,
       3,     1,     2,     1,     2,     3,     4,     1,     3,     1,
       1,     1,     2,     2,     2,     2,     1,     1,     1,     1
    };
  }

  /* YYTOKEN_NUMBER[YYLEX-NUM] -- Internal symbol number corresponding
      to YYLEX-NUM.  */
  private static final short yytoken_number_[] = yytoken_number_init();
  private static final short[] yytoken_number_init()
  {
    return new short[]
    {
       0,   256,   257,   258,   259,   260,    63,    44,    40,    41,
      46,    91,    58,    93,    38,   123,   125,    61,    62,    60,
      33,   126
    };
  }

  /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
     First, the terminals, then, starting at \a yyntokens_, nonterminals.  */
  private static final String yytname_[] = yytname_init();
  private static final String[] yytname_init()
  {
    return new String[]
    {
  "$end", "error", "$undefined", "SCAN_WORD", "SCAN_STRINGCONST",
  "SCAN_NUMBERCONST", "'?'", "','", "'('", "')'", "'.'", "'['", "':'",
  "']'", "'&'", "'{'", "'}'", "'='", "'>'", "'<'", "'!'", "'~'", "$accept",
  "constraints", "optquestionmark", "projections", "selections",
  "projectionlist", "projection", "function", "segmentlist", "segment",
  "rangelist", "range", "range1", "clauselist", "sel_clause", "value_list",
  "value", "constant", "var", "indexpath", "index", "array_indices",
  "boolfunction", "arg_list", "rel_op", "ident", "word", "number",
  "string", null
    };
  }

  /* YYRLINE[YYN] -- Source line where rule number YYN was defined.  */
  private static final short yyrline_[] = yyrline_init();
  private static final short[] yyrline_init()
  {
    return new short[]
    {
       0,    91,    91,    92,    93,    94,    97,    97,   101,   106,
     111,   113,   119,   121,   126,   128,   134,   136,   142,   144,
     150,   152,   158,   160,   162,   166,   173,   175,   181,   183,
     185,   190,   192,   197,   199,   201,   206,   208,   213,   222,
     224,   229,   231,   237,   239,   244,   246,   251,   253,   259,
     260,   261,   262,   263,   264,   265,   268,   272,   276,   280
    };
  }

  // Report on the debug stream that the rule yyrule is going to be reduced.
  private void yy_reduce_print (int yyrule, YYStack yystack)
  {
    if (yydebug == 0)
      return;

    int yylno = yyrline_[yyrule];
    int yynrhs = yyr2_[yyrule];
    /* Print the symbols being reduced, and their result.  */
    yycdebug ("Reducing stack by rule " + (yyrule - 1)
              + " (line " + yylno + "), ");

    /* The symbols being reduced.  */
    for (int yyi = 0; yyi < yynrhs; yyi++)
      yy_symbol_print ("   $" + (yyi + 1) + " =",
                       yystos_[yystack.stateAt(yynrhs - (yyi + 1))],
                       ((yystack.valueAt (yynrhs-(yyi + 1)))));
  }

  /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
  private static final byte yytranslate_table_[] = yytranslate_table_init();
  private static final byte[] yytranslate_table_init()
  {
    return new byte[]
    {
       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,    20,     2,     2,     2,     2,    14,     2,
       8,     9,     2,     2,     7,     2,    10,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,    12,     2,
      19,    17,    18,     6,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,    11,     2,    13,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,    15,     2,    16,    21,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
       5
    };
  }

  private static final byte yytranslate_ (int t)
  {
    if (t >= 0 && t <= yyuser_token_number_max_)
      return yytranslate_table_[t];
    else
      return yyundef_token_;
  }

  private static final int yylast_ = 99;
  private static final int yynnts_ = 29;
  private static final int yyempty_ = -2;
  private static final int yyfinal_ = 4;
  private static final int yyterror_ = 1;
  private static final int yyerrcode_ = 256;
  private static final int yyntokens_ = 22;

  private static final int yyuser_token_number_max_ = 260;
  private static final int yyundef_token_ = 2;

/* User implementation code.  */
/* Unqualified %code blocks.  */
/* "ce.y":20  */ /* lalr1.java:1066  */

    static public boolean DEBUG = false;

    /**
     * Instantiates the Bison-generated parser.
     * @param yylexer The scanner that will supply tokens to the parser.
     */

    public CeParser(BaseTypeFactory factory)
    {
	super(factory);
	this.yylexer = new Celex(this);
	super.lexstate = (Celex)this.yylexer;
	this.yyDebugStream = System.out;
	if(DEBUG)
	    setDebugLevel(1);
    }

    /* the parse function allows the specification of a
       new stream in case one is reusing the parser
    */

    boolean parse(String constraint) throws ParseException
    {
	((Celex)yylexer).reset(parsestate,constraint);
	return parse();
    }

    // Static entry point to be called by CEEvaluator
    // This parses, then fills in the evaluator from the AST

    static public boolean constraint_expression(CEEvaluator ceEval,
                                         BaseTypeFactory factory,
					 ClauseFactory clauseFactory,
					 String constraint,
				         String url // for error reporting
					 )
            throws DAP2Exception, ParseException
    {
	CeParser parser = new CeParser(factory);
	parser.setURL(url);
	parser.setConstraint(constraint);
        ServerDDS sdds = ceEval.getDDS();
        if(!parser.parse(constraint)) return false;
        ASTconstraint root = (ASTconstraint)parser.getAST();
	root.init(ceEval,factory,clauseFactory,sdds,parser.getASTnodeset());
	root.walkConstraint();
        return true;
    }

    public  void setURL(String url) {
        lexstate.url = url;
    }
    public String getURL() {return lexstate.url;}

    public void setConstraint(String constraint) {lexstate.constraint = constraint;}
    public String getConstraint() {return lexstate.constraint;}

/* "CeParser.java":1451  */ /* lalr1.java:1066  */

}

/* "ce.y":284  */ /* lalr1.java:1070  */


/*
 * Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
 * See LICENSE for license information.
 */
package ucar.units;

import javax.annotation.concurrent.Immutable;

/**
 * Provides support for prefix symbols.
 *
 * Instances of this class are immutable.
 *
 * @author Steven R. Emmerson
 */
@Immutable
public final class
PrefixSymbol
    extends	Prefix
{
    /**
     * Constructs from a name and a numeric value.
     * @param name		The name for the prefix.
     * @param value		The numeric value for the prefix.
     */
    public
    PrefixSymbol(String name, double value)
    {
	super(name, value);
    }

    /**
     * Compares this prefix against another PrefixSymbol.  The sort keys are
     * decreasing length (major) and increasing lexicality (minor).
     * @param obj		The other PrefixSymbol.
     * @return			A negative value, zero, or a positive value
     *				depending on whether this PrefixSymbol is less
     *				than, equal to, or greater than
     *				obj, respectively.
     */
    public final int
    compareTo(Object obj)
    {
	String	thatID = ((PrefixSymbol)obj).getID();
	int	comp = thatID.length() - getID().length();
	if (comp == 0)
	    comp = getID().compareTo(thatID);
	return comp;
    }

    /**
     * Compares this prefix against a String.  The sort keys are
     * decreasing length (major) and increasing lexicality (minor).
     * @param string		The string.
     * @return			A negative value, zero, or a positive value
     *				depending on whether this PrefixSymbol is less
     *				than, equal to, or greater than
     *				string, respectively.
     */
    public final int
    compareTo(String string)
    {
	int	comp = string.length() - getID().length();
	return comp < 0
		? comp
		: comp == 0
		    ? (getID().compareTo(string) == 0 ? 0 : -1)
		    : (getID().compareTo(string.substring(0, getID().length()))
			== 0
			    ? 0
			    : -1);
    }
}


/* Copyright 2012, UCAR/Unidata.
   See the LICENSE file for more information.
*/

package dap4.dap4lib;

import dap4.core.util.DapException;
import dap4.core.util.DapUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * This class wraps a chunked source of databuffer
 * as an InputStream. It is mostly pass-thru
 * in the sense that reads on this class are
 * turned into a series of reads of the underlying stream.
 */

public class ChunkInputStream extends InputStream
{
    //////////////////////////////////////////////////
    // Constants

    static final int DFALTCHUNKSIZE = 0x00FFFFFF;

    static final byte CR8 = DapUtil.extract(DapUtil.UTF8.encode("\r"))[0];
    static final byte LF8 = DapUtil.extract(DapUtil.UTF8.encode("\n"))[0];

    //////////////////////////////////////////////////
    // Type Decls

    //////////////////////////////////////////////////
    // static variables

    //////////////////////////////////////////////////
    // static methods

    //////////////////////////////////////////////////
    // Type declarations

    enum State
    {
        ERROR,    // after error chunk
        END,     // after last databuffer chunk
        DATA,    // when at start of a databuffer chunk
        INDATA,    // when reading a databuffer chunk
        INITIAL; // before anything is written
    }

    //////////////////////////////////////////////////
    // Instance variable

    protected InputStream input = null;
    protected State state = State.INITIAL;
    protected RequestMode requestmode = null;

    protected ByteOrder localorder = null;
    protected ByteOrder remoteorder = null;
    protected boolean nochecksum = false;

    // State info for current chunk
    protected int flags = 0;
    protected int chunksize = 0;
    protected int avail = 0;

    //////////////////////////////////////////////////
    // Constructor(s)

    public ChunkInputStream(InputStream input, RequestMode requestmode)
    {
        this(input, requestmode, ByteOrder.nativeOrder());
    }

    public ChunkInputStream(InputStream input, RequestMode requestmode, ByteOrder order)
    {
        this.input = input;
        this.requestmode = requestmode;
        this.localorder = order;
    }

    //////////////////////////////////////////////////
    // Accessors

    public ByteOrder getHostByteOrder()
    {
        return this.localorder;
    }

    public ByteOrder getRemoteByteOrder()
    {
        return this.remoteorder;
    }

    public boolean getNoChecksum()
        {
            return this.nochecksum;
        }

    //////////////////////////////////////////////////

    /**
     * Read the DMR, trimmed.
     *
     * @return the DMR as a Java String
     */

    public String
    readDMR()
            throws DapException
    {
        try {
            if(state != State.INITIAL)
                throw new DapException("Attempt to read DMR twice");

            byte[] dmr8 = null;

            if(requestmode == RequestMode.DMR) {
                // The whole buffer is the dmr;
                // but we do not know the length
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int c;
                while((c = input.read()) >= 0) {
                    baos.write(c);
                }
                baos.close();
                dmr8 = baos.toByteArray();
            } else if(requestmode == RequestMode.DAP) {
                // Pull in the DMR chunk header
                if(!readHeader(input))
                    throw new DapException("Malformed chunk count");
                // Read the DMR databuffer
                dmr8 = new byte[this.chunksize];
                int red = read(dmr8, 0, this.chunksize);
                if(red < this.chunksize)
                    throw new DapException("Short chunk");
            } else
                assert false : "Internal error";

            // Convert DMR to a string
            String dmr = new String(dmr8, DapUtil.UTF8);
            // Clean it up
            dmr = dmr.trim();
            // Make sure it has trailing \r\n"
            if(dmr.endsWith("\r\n")) {
                // do nothing
            } else if(dmr.endsWith("\n"))
                dmr = dmr.substring(0,dmr.length()-2) + "\r\n";
            else
                dmr = dmr + "\r\n";

            // Figure out the endian-ness of the response
            this.remoteorder = (flags & DapUtil.CHUNK_LITTLE_ENDIAN) == 0 ? ByteOrder.BIG_ENDIAN
                    : ByteOrder.LITTLE_ENDIAN;
            this.nochecksum = (flags & DapUtil.CHUNK_NOCHECKSUM) != 0;

            // Set the state
            if((flags & DapUtil.CHUNK_ERROR) != 0)
                state = State.ERROR;
            else if((flags & DapUtil.CHUNK_END) != 0)
                state = State.END;
            else
                state = State.DATA;
            return dmr; //return the DMR

        } catch (IOException ioe) {
            throw new DapException(ioe.getMessage());
        }
    }

    /**
     * Convert an error chunk to an exception
     *
     * @param document XML representation of the error
     * @throws DapException containing the contents of the error chunk
     */
    public void
    throwError(String document)
            throws ErrorException
    {
        throw new ErrorException("Error chunk encountered")
                .setDocument(document);
    }

    /**
     * Read an error chunk
     *
     * @return the error document as a string
     */
    public String
    readError()
            throws IOException
    {
        state = State.ERROR;
        // Read the error body databuffer
        byte[] bytes = new byte[this.chunksize];
        try {
            if(read(bytes, 0, this.chunksize) < this.chunksize)
                throw new ErrorException("Short chunk");
        } catch (IOException ioe) {
            throw new ErrorException(ioe);
        }
        String document = new String(bytes, DapUtil.UTF8);
        return document;
    }

    //////////////////////////////////////////////////
    // InputStream abstract methods

    /**
     * Reads the next byte of databuffer from the input stream. The value byte is
     * returned as an int in the range 0 to
     * 255. If no byte is available because the end of the stream
     * has been reached, the value -1 is returned. This method
     * blocks until input databuffer is available, the end of the stream is detected,
     * or an exception is thrown.
     *

     * Operates by loading chunk by chunk. If an error chunk is detected,
     * then return ErrorException (which is a subclass of IOException).
     *
     * @return the next byte of databuffer, or -1 if the end of the
     * stream is reached.
     * @throws IOException if an I/O error occurs.
     */
    public int
    read()
            throws IOException
    {
        if(requestmode == RequestMode.DMR)
            throw new UnsupportedOperationException("Attempt to read databuffer when DMR only"); // Runtime
        if(avail <= 0) {
            if((flags & DapUtil.CHUNK_END) != 0)
                return -1; // Treat as EOF
            if(!readHeader(input))
                return -1; // EOF
            // See if we have an error chunk,
            // and if so, turn it into an exception
            if((flags & DapUtil.CHUNK_ERROR) != 0) {
                String document = readError();
                throwError(document);
            }
        }
        avail--;
        return input.read();
    }

    //////////////////////////////////////////////////
    // InputStream method overrides

    /**
     * Reads up to len databuffer of databuffer from the input stream into an
     * array of databuffer. An attempt is made to read as many as len
     * databuffer, but a smaller number may be read. The number of databuffer
     * actually read is returned as an integer.
     *
     * @param buf the byte array into which databuffer is read
     * @param off the offset in the byte array at which to write
     * @param len the amount to read
     * @return the actual number of databuffer read
     * @throws IOException
     */

    public int
    read(byte[] buf, int off, int len)
            throws IOException
    {
        // Sanity check
        if(off < 0 || len < 0)
            throw new IndexOutOfBoundsException();// Runtime
        if(off >= buf.length || buf.length < (off + len))
            throw new IndexOutOfBoundsException(); //Runtime
        if(requestmode == RequestMode.DMR)
            throw new UnsupportedOperationException("Attempt to read databuffer when DMR only"); // Runtime

        // Attempt to read len bytes out of a sequence of chunks
        int count = len;
        int pos = off;
        while(count > 0) {
            if(avail <= 0) {
                if((flags & DapUtil.CHUNK_END) != 0
                        || !readHeader(input))
                    return (len - count); // return # databuffer read
                // See if we have an error chunk,
                // and if so, turn it into an exception
                if((flags & DapUtil.CHUNK_ERROR) != 0) {
                    String document = readError();
                    throwError(document);
                }
            } else {
                int actual = (this.avail < count ? this.avail : count);
                int red = input.read(buf, pos, actual);
                if(red < 0)
                    throw new IOException("Unexpected EOF");
                pos += red;
                count -= red;
                this.avail -= red;
            }
        }
        return len;
    }

    /**
     * Returns an estimate of the number of databuffer that can be read
     * (or skipped over) from this input stream without
     * blocking by the next invocation of a method for this
     * input stream.
     *

     * Repurposed here to do equivalent of peek().
     *
     * @return 0 if at eof, some number > 0 otherwise.
     */

    public int
    available()
    {
        if(this.avail > 0) return this.avail;
        if((flags & DapUtil.CHUNK_END) != 0)
            return 0;
        return 1; // should be some unknown amount left.
    }

    /**
     * Closes this output stream and releases any system resources
     * associated with this stream. The underlying servlet stream is
     * not closed; that is left to the level above.
     */

    public void close()
            throws IOException
    {
        state = State.END;
    }

    //////////////////////////////////////////////////
    // Utilities

    /**
     * Read the size+flags header from the input stream and use it to
     * initialize the chunk state
     *
     * @param input The input streamfrom which to read
     * @return true if header read false if immediate eof encountered
     */

    boolean
    readHeader(InputStream input)
            throws IOException
    {
        byte[] bytehdr = new byte[4];
        int red = input.read(bytehdr);
        if(red == -1) return false;
        if(red < 4)
            throw new IOException("Short binary chunk count");
        this.flags = ((int) bytehdr[0]) & 0xFF; // Keep unsigned
        bytehdr[0] = 0;
        ByteBuffer buf = ByteBuffer.wrap(bytehdr).order(ByteOrder.BIG_ENDIAN);
        this.chunksize = buf.getInt();
        this.avail = this.chunksize;
        return true;
    }

}


/*
 * Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
 * See LICENSE for license information.
 */
package ucar.nc2.iosp.bufr.tables;

import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.Element;
import ucar.nc2.iosp.bufr.Descriptor;
import ucar.nc2.wmo.CommonCodeTable;
import ucar.unidata.util.StringUtil2;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Read BUFR Code / Flag tables.
 *
 * @author caron
 * @since Jul 12, 2008
 */
public class CodeFlagTables {
  static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CodeFlagTables.class);
  static private final String CodeFlagFilename = "wmo/BUFRCREX_25_0_0_CodeFlag_en.xml";
  static Map<Short, CodeFlagTables> tableMap;

  static public CodeFlagTables getTable(short id) {
    if (tableMap == null) init();

    if (id == 263) return useCC(id, 5); // 0-1-7
    if (id == 526) return useCC(id, 7); // 0-2-14
    if (id == 531) return useCC(id, 8); // 0-2-19
    if (id == 5699) return useCC(id, 3); // 0-22-67
    if (id == 5700) return useCC(id, 4); // 0-22-68

    return tableMap.get(id);
  }

  static private CodeFlagTables useCC(short fxy, int cc) {
    CodeFlagTables cft = tableMap.get(fxy);
    if (cft == null) {
      CommonCodeTable cct =  CommonCodeTable.getTable(cc);
      cft = new CodeFlagTables(fxy, cct.getTableName(),  cct.getMap());
      tableMap.put(fxy, cft);
    }
    return cft;
  }

  static public boolean hasTable(short id) {
    if (tableMap == null) init();
    CodeFlagTables result = tableMap.get(id);
    return result != null;
  }

  static private void init() {
    tableMap = new HashMap<>(300);
    init(tableMap);
  }

  static public Map<Short, CodeFlagTables> getTables() {
    if (tableMap == null) init();
    return tableMap;
  }

  /*
  <Exp_CodeFlagTables_E>
    <No>837</No>
    <FXY>002119</FXY>
    <ElementName_E>Instrument operations</ElementName_E>
    <CodeFigure>0</CodeFigure>
    <EntryName_E>Intermediate frequency calibration mode (IF CAL)</EntryName_E>
    <Status>Operational</Status>
  </Exp_CodeFlagTables_E>

<BUFRCREX_19_1_1_CodeFlag_en>
  <No>2905</No>
  <FXY>020042</FXY>
  <ElementName_en>Airframe icing present</ElementName_en>
  <CodeFigure>2</CodeFigure>
  <EntryName_en>Reserved</EntryName_en>
  <Status>Operational</Status>
</BUFRCREX_19_1_1_CodeFlag_en>

<BUFRCREX_22_0_1_CodeFlag_en>
<No>3183</No>
<FXY>020063</FXY>
<ElementName_en>Special phenomena</ElementName_en>
<CodeFigure>31</CodeFigure>
<EntryName_en>Slight coloration of clouds at sunrise associated with a tropical disturbance</EntryName_en>
<Status>Operational</Status>
</BUFRCREX_22_0_1_CodeFlag_en>

   */
  static private void init(Map<Short, CodeFlagTables> table) {
    String filename = BufrTables.RESOURCE_PATH + CodeFlagFilename;
    try (InputStream is = CodeFlagTables.class.getResourceAsStream(filename)) {
      SAXBuilder builder = new SAXBuilder();
      org.jdom2.Document tdoc = builder.build(is);
      org.jdom2.Element root = tdoc.getRootElement();

      List<Element> elems = root.getChildren();
      for (Element elem : elems) {
        String fxyS = elem.getChildText("FXY");
        String desc = elem.getChildText("ElementName_en");

        short fxy = Descriptor.getFxy2(fxyS);
        CodeFlagTables ct = table.get(fxy);
        if (ct == null) {
          ct = new CodeFlagTables(fxy, desc);
          table.put(fxy, ct);
          // System.out.printf(" added %s == %s %n", ct.id, desc);
        }

        String line = elem.getChildText("No");
        String codeS = elem.getChildText("CodeFigure");
        String value = elem.getChildText("EntryName_en");

        if ((codeS == null) || (value == null)) continue;
        if (value.toLowerCase().startsWith("reserved"))  continue;
        if (value.toLowerCase().startsWith("not used")) continue;

        int code;
        if (codeS.toLowerCase().contains("all")) {
          code = -1;
        } else try {
          code = Integer.parseInt(codeS);
        } catch (NumberFormatException e) {
          log.debug("NumberFormatException on line " + line + " in " + codeS);
          continue;
        }
        ct.addValue((short) code, value);
      }

    } catch (IOException|JDOMException e) {
      log.error("Can't read BUFR code table " + filename, e);
    }
  }

  static private final boolean showReadErrs = false, showNameDiff = false;

  static private void init2(Map<Short, CodeFlagTables> table) {
    String filename = BufrTables.RESOURCE_PATH + "wmo/BC_CodeFlagTable.csv";
    BufferedReader dataIS = null;

    try {
      InputStream is = CodeFlagTables.class.getResourceAsStream(filename);
      dataIS = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF8")));
      int count = 0;
      while (true) {
        String line = dataIS.readLine();
        if (line == null) break;
        if (line.startsWith("#")) continue;
        count++;

        if (count == 1) { // skip first line - its the header
          continue;
        }

        // any commas that are embedded in quotes - replace with blanks for now so split works
        int pos1 = line.indexOf('"');
        if (pos1 >= 0) {
          int pos2 = line.indexOf('"', pos1 + 1);
          StringBuilder sb = new StringBuilder(line);
          for (int i = pos1; i < pos2; i++)
            if (sb.charAt(i) == ',') sb.setCharAt(i, ' ');
          line = sb.toString();
        }

        String[] flds = line.split(",");
        if (flds.length < 4) {
          if (showReadErrs) System.out.printf("%d BAD split == %s%n", count, line);
          continue;
        }

        // SNo,FXY,CodeFigure,enDescription1,enDescription2,enDescription3
        int fldidx = 1; // start at 1 to skip sno
        try {
          int xy = Integer.parseInt(flds[fldidx++].trim());
          int no;
          try {
            no = Integer.parseInt(flds[fldidx++].trim());
          } catch (NumberFormatException e) {
            if (showReadErrs) System.out.printf("%d skip == %s%n", count, line);
            continue;
          }
          String name = StringUtil2.remove(flds[fldidx], '"');
          String nameLow = name.toLowerCase();
          if (nameLow.startsWith("reserved")) continue;
          if (nameLow.startsWith("not used")) continue;

          int x = xy / 1000;
          int y = xy % 1000;
          int fxy = (x << 8) + y;

          CodeFlagTables ct = table.get((short) fxy);
          if (ct == null) {
            ct = new CodeFlagTables((short) fxy, null);
            table.put(ct.fxy, ct);
            //System.out.printf(" added in 2: %s (%d)%n", ct.fxy(), ct.fxy);
          }
          ct.addValue((short) no, name);

        } catch (NumberFormatException e) {
          if (showReadErrs) System.out.printf("%d %d BAD line == %s%n", count, fldidx, line);
        }
      }

    } catch (IOException e) {
      log.error("Can't read BUFR code table " + filename, e);
    } finally {
      if (dataIS != null)
        try {
          dataIS.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
  }

  public static void main(String arg[]) throws IOException {
    HashMap<Short, CodeFlagTables> tableMap1 = new HashMap<>(300);
    init(tableMap1);

    HashMap<Short, CodeFlagTables> tableMap2 = new HashMap<>(300);
    init2(tableMap2);

    System.out.printf("Compare 1 with 2%n");
    for (Map.Entry<Short, CodeFlagTables> ent : tableMap1.entrySet()) {
      CodeFlagTables t = ent.getValue();
      CodeFlagTables t2 = tableMap2.get(ent.getKey());
      if (t2 == null)
        System.out.printf(" NOT FOUND in 2: %s (%d)%n", t.fxy(), t.fxy);
      else {
        for (int no : t.map.keySet()) {
          String name1 = t.map.get(no);
          String name2 = t2.map.get(no);
          if (name2 == null)
            System.out.printf(" %s val %d name '%s' missing in 2%n", t.fxy(), no, name1);
          else if (showNameDiff && !name1.equals(name2))
            System.out.printf(" *** %s names different%n  %s%n  %s%n", t.fxy(), name1, name2);
        }
      }
    }

    System.out.printf("Compare 2 with 1%n");
    for (Map.Entry<Short, CodeFlagTables> ent : tableMap2.entrySet()) {
      CodeFlagTables t = ent.getValue();
      CodeFlagTables t1 = tableMap1.get(ent.getKey());
      if (t1 == null)
        System.out.printf(" NOT FOUND in 1: %s (%d)%n", t.fxy(), t.fxy);
      else {
        for (int no : t.map.keySet()) {
          String name = t.map.get(no);
          String name1 = t1.map.get(no);
          if (name1 == null)
            System.out.printf(" %s val %d name '%s' missing%n", t.fxy(), no, name);
          else if (showNameDiff && !name.equals(name1))
            System.out.printf(" %s names different%n  %s%n  %s%n", t.fxy(), name, name1);
        }
      }
    }

  }

  ////////////////////////////////////////////////
  private short fxy;
  private String name;
  private Map<Integer, String> map;  // needs to be integer for EnumTypedef

  private CodeFlagTables(short fxy, String name) {
    this.fxy = fxy;
    this.name = (name == null) ? fxy() : name; // StringUtil2.replace(name, ' ', "_") + "("+fxy()+")";
    map = new HashMap<>(20);
  }

  private CodeFlagTables(short fxy, String name, Map<Integer, String> map) {
    this.fxy = fxy;
    this.name = (name == null) ? fxy() : name;
    this.map = map;
  }

  public String getName() {
    return name;
  }

  public Map<Integer, String> getMap() {
    return map;
  }

  private void addValue(int value, String text) {
    map.put(value, text);
  }

  public short getId() { return fxy; }

  public String fxy() {
    int f = fxy >> 14;
    int x = (fxy & 0xff00) >> 8;
    int y = (fxy & 0xff);

    return f + "-" + x + "-" + y;
  }

  public String toString() { return name; }

}


/*
 * Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
 * See LICENSE for license information.
 */

package ucar.nc2.time;

import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import ucar.nc2.units.DateFormatter;

import javax.annotation.concurrent.ThreadSafe;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Threadsafe static routines for date formatting.
 * Replacement for ucar.nc2.units.DateFormatter
 *
 * @author John
 * @since 7/9/11
 */
@ThreadSafe
public class CalendarDateFormatter {
  // these are thread-safe (yeah!)
  private static DateTimeFormatter isof = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZoneUTC();
  private static DateTimeFormatter isof_with_millis_of_second = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();
  private static DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss'Z'").withZoneUTC();

  private static DateTimeFormatter dtf_with_millis_of_second = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS'Z'").withZoneUTC();
  private static DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC();
  private static DateTimeFormatter df_units = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS 'UTC'").withZoneUTC(); // udunits

  static public String toDateTimeStringISO(CalendarDate cd) {

	 if(cd.getDateTime().getMillisOfSecond() == 0)
		 return isof.print( cd.getDateTime() );
	 else
		 return isof_with_millis_of_second.print(cd.getDateTime());

  }

  static public String toDateTimeStringISO(Date d) {
	  return toDateTimeStringISO( CalendarDate.of(d) );
  }

  static public String toDateTimeStringISO(long millisecs) {
 	  return toDateTimeStringISO( CalendarDate.of(millisecs) );
   }

   static public String toDateTimeString(CalendarDate cd) {

	  if(cd.getDateTime().getMillisOfSecond()==0)
		  return dtf.print(cd.getDateTime());
	  else
		  return dtf_with_millis_of_second.print(cd.getDateTime());
  }

  static public String toDateTimeString(Date date) {
	    return toDateTimeString(CalendarDate.of(date));
  }

  static public String toDateTimeStringPresent() {
    return dtf.print(new DateTime());
  }

  static public String toDateString(CalendarDate cd) {
    return df.print(cd.getDateTime());
  }

  static public String toDateStringPresent() {
    return df.print(new DateTime());
  }

  /**
   * udunits formatting
   * @param cd  the calendar date
   * @return udunits formated date
   */
  static public String toTimeUnits(CalendarDate cd){
	  return df_units.print(cd.getDateTime());
  }

  static public String toTimeUnits(Date date){
	  return df_units.print(date.getTime());
  }

  static public CalendarDateFormatter factory(CalendarPeriod period) {
    switch (period.getField()) {
      case Year: return new CalendarDateFormatter("yyyy");
      case Month: return new CalendarDateFormatter("yyyy-MM");
      case Day: return new CalendarDateFormatter("yyyy-MM-dd");
      case Hour: return new CalendarDateFormatter("yyyy-MM-ddTHH");
      default: return new CalendarDateFormatter("yyyy-MM-ddTHH:mm:ss");
    }
  }

  /////////////////////////////////////////////////////////////////////////////
  // reading an ISO formatted date

  /**
   * Old version using DateFormatter
   * @param iso ISO 8601 date String
   * @return equivilent Date
   *
   * @deprecated As of 4.3.10 use {@link #isoStringToDate(String)} instead
   *
   */
  @Deprecated
  static public Date parseISODate(String iso) {
    DateFormatter df = new DateFormatter();
    return df.getISODate(iso);
  }

  /**
   * Convert an ISO formatted String to a CalendarDate.
   * @param calt calendar, may be null for default calendar (Calendar.getDefault())
   * @param iso ISO 8601 date String

possible forms for W3C profile of ISO 8601
        Year:
         YYYY (eg 1997)
      Year and month:
         YYYY-MM (eg 1997-07)
      Complete date:
         YYYY-MM-DD (eg 1997-07-16)
      Complete date plus hours and minutes:
         YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
      Complete date plus hours, minutes and seconds:
         YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
      Complete date plus hours, minutes, seconds and a decimal fraction of a second
         YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

   where:
        YYYY = four-digit year
        MM   = two-digit month (01=January, etc.)
        DD   = two-digit day of month (01 through 31)
        hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
        mm   = two digits of minute (00 through 59)
        ss   = two digits of second (00 through 59)
        s    = one or more digits representing a decimal fraction of a second
        TZD  = time zone designator (Z or +hh:mm or -hh:mm)
   except:
       You may use a space instead of the 'T'
       The year may be preceeded by a '+' (ignored) or a '-' (makes the date BCE)
       The date part uses a '-' delimiter instead of a fixed number of digits for each field
       The time part uses a ':' delimiter instead of a fixed number of digits for each field

   * @return CalendarDate using given calendar
   * @throws IllegalArgumentException if the String is not a valid ISO 8601 date
   * @see "http://www.w3.org/TR/NOTE-datetime"
   */
  static public CalendarDate isoStringToCalendarDate(Calendar calt, String iso) throws IllegalArgumentException {
	  DateTime dt = parseIsoTimeString(calt, iso);
    Calendar useCal = Calendar.of(dt.getChronology());
	  return new CalendarDate(useCal, dt);
  }

  /**
   * Does not handle non-standard Calendars
   * @param iso iso formatted string
   * @return Date
   * @throws IllegalArgumentException
   * @deprecated use isoStringToCalendarDate
   */
  static public Date isoStringToDate(String iso) throws IllegalArgumentException {
    CalendarDate dt = isoStringToCalendarDate(null, iso);
	  return dt.toDate();
  }

  //                                                   1                  2            3
  static public final String isodatePatternString = "([\\+\\-?\\d]+)([ t]([\\.\\:?\\d]*)([ \\+\\-]\\S*)?z?)?$"; // public for testing
  // private static final String isodatePatternString = "([\\+\\-\\d]+)[ Tt]([\\.\\:\\d]*)([ \\+\\-]\\S*)?z?)?$";
  private static final Pattern isodatePattern = Pattern.compile(isodatePatternString);

  private static DateTime parseIsoTimeString(Calendar calt, String iso) {
    iso = iso.trim();
    iso = iso.toLowerCase();

    Matcher m = isodatePattern.matcher(iso);
    if (!m.matches()) {
      //System.out.printf("'%s' does not match regexp '%s'%n", dateUnitString, udunitPatternString);
      throw new IllegalArgumentException(iso + " does not match regexp " + isodatePatternString);
    }

    String dateString = m.group(1);
    String timeString = m.group(3);
    String zoneString = m.group(4);

    // Set the defaults for any values that are not specified
    int year = 0;
    int month = 1;
    int day = 1;
    int hour = 0;
    int minute = 0;
    double second = 0.0;

    try {
      boolean isMinus = false;
      if (dateString.startsWith("-")) {
         isMinus = true;
         dateString = dateString.substring(1);
       } else if (dateString.startsWith("+")) {
         dateString = dateString.substring(1);
       }

      if (dateString.contains("-")) {
        StringTokenizer dateTokenizer = new StringTokenizer(dateString, "-");
        if (dateTokenizer.hasMoreTokens()) year = Integer.parseInt(dateTokenizer.nextToken());
        if (dateTokenizer.hasMoreTokens()) month = Integer.parseInt(dateTokenizer.nextToken());
        if (dateTokenizer.hasMoreTokens()) day = Integer.parseInt(dateTokenizer.nextToken());
      } else {
        int dateLength = dateString.length();
        if (dateLength % 2 != 0) {
          throw new IllegalArgumentException(dateString + " is ambiguous. Cannot parse uneven " +
                  "length date strings when no date delimiter is used.");
        } else {
          // dateString length must be even - only four digit year, two digit month, and
          // two digit day values are allowed when there is no date delimiter.
          if (dateLength > 3) year = Integer.parseInt(dateString.substring(0, 4));
          if (dateLength > 5) month = Integer.parseInt(dateString.substring(4, 6));
          if (dateLength > 7) day = Integer.parseInt(dateString.substring(6, 8));
        }
      }

      // Parse the time if present
      if (timeString != null && timeString.length() > 0) {
        if (timeString.contains(":")) {
          StringTokenizer timeTokenizer = new StringTokenizer(timeString, ":");
          if (timeTokenizer.hasMoreTokens()) hour = Integer.parseInt(timeTokenizer.nextToken());
          if (timeTokenizer.hasMoreTokens()) minute = Integer.parseInt(timeTokenizer.nextToken());
          if (timeTokenizer.hasMoreTokens()) second = Double.parseDouble(timeTokenizer.nextToken());
        } else {
          int timeLengthNoSubseconds = timeString.length();
          // possible this contains a seconds value with subseconds (i.e. 25.125 seconds)
          // since the seconds value can be a Double, let's check check the length of the
          // time, without the subseconds (if they exist)
          if (timeString.contains(".")) {
            timeLengthNoSubseconds = timeString.split("\\.")[0].length();
          }
          // Ok, so this is a little tricky.
          // First: A udunit date of 1992-10-8t7 is valid. We want to make sure this still work, so
          // there is a special case of timeString.length() == 1;
          //
          // Second: We have the length of the timeString, without
          // any subseconds. Given that the values for hour, minute, and second must be two
          // digit numbers, the length of the timeString, without subseconds, should be even.
          // However, if someone has encoded time as hhms, there is no way we will be able to tell.
          // So, this is the best we can do to ensure we are parsing the time properly.
          // Known failure here: hhms will be interpreted as hhmm, but hhms is not following iso, and
          // a bad idea to use anyway.
          if (timeLengthNoSubseconds == 1) {
            hour = Integer.parseInt(timeString);
          } else if (timeLengthNoSubseconds % 2 != 0) {
            throw new IllegalArgumentException(timeString + " is ambiguous. Cannot parse uneven " +
                    "length time strings (ignoring subseconds) when no time delimiter is used.");
          } else {
            // dateString length must be even - only four digit year, two digit month, and
            // two digit day values are allowed when there is no date delimiter.
            if (timeString.length() > 1) hour = Integer.parseInt(timeString.substring(0, 2));
            if (timeString.length() > 3) minute = Integer.parseInt(timeString.substring(2, 4));
            if (timeString.length() > 5) second = Double.parseDouble(timeString.substring(4));
          }
        }
      }

      if (isMinus) year = -year;

      // kludge to deal with legacy files using year 0. // 10/10/2013 jcaron
      if ((year == 0) && (calt == Calendar.gregorian)) {
        calt = Calendar.proleptic_gregorian;
      }

      //if (year <  -292275054 || year > 292278993)
      //  throw new IllegalArgumentException(" incorrect date specification = " + iso);

      // Get a DateTime object in this Chronology
      Chronology cron = Calendar.getChronology(calt);
      cron = cron.withUTC(); // default is UTC
      DateTime dt = new DateTime(year, month, day, hour, minute, 0, 0, cron);

      // Add the seconds
      dt = dt.plus((long) (1000 * second));

      // Parse the time zone if present
      if (zoneString != null) {
        zoneString = zoneString.trim();
        if (zoneString.length() > 0 && !zoneString.equalsIgnoreCase("Z") && !zoneString.equalsIgnoreCase("UTC") && !zoneString.equalsIgnoreCase("GMT")) {
          isMinus = false;
          if (zoneString.startsWith("-")) {
             isMinus = true;
             zoneString = zoneString.substring(1);
           } else if (zoneString.startsWith("+")) {
             zoneString = zoneString.substring(1);
           }

          // allow 01:00, 1:00, 01 or 0100
          int hourOffset;
          int minuteOffset = 0;
          int posColon = zoneString.indexOf(':');
          if (posColon > 0) {
            String hourS = zoneString.substring(0,posColon);
            String minS = zoneString.substring(posColon+1);
            hourOffset = Integer.parseInt(hourS);
            minuteOffset = Integer.parseInt(minS);

          } else {   // no colon - assume 2 digit hour, optional minutes
            if (zoneString.length() > 2) {
              String hourS = zoneString.substring(0,2);
              String minS = zoneString.substring(2);
              hourOffset = Integer.parseInt(hourS);
              minuteOffset = Integer.parseInt(minS);
            } else {
              hourOffset = Integer.parseInt(zoneString);
            }
          }
          if (isMinus) {
            // DateTimeZone.forOffsetHoursMinutes: "If constructed with the values (-2, 30), the resulting zone is '-02:30'.
            // so i guess dont make minuteOffset negetive
            hourOffset = -hourOffset;
          }
          DateTimeZone dtz = DateTimeZone.forOffsetHoursMinutes(hourOffset, minuteOffset);

          // Apply the time zone offset, retaining the field values.  This
          // manipulates the millisecond instance.
          dt = dt.withZoneRetainFields(dtz);
          // Now convert to the UTC time zone, retaining the millisecond instant
          dt = dt.withZone(DateTimeZone.UTC);
        } //else {
          //dt = dt.withZone(DateTimeZone.UTC);   // default UTC
        //}

      //} else {
      //  dt = dt.withZone(DateTimeZone.UTC);   // default UTC
      }

      return dt;
    } catch (Throwable e) {  // catch random joda exceptions
      throw new IllegalArgumentException("Illegal base time specification: '" + dateString+"' "+e.getMessage());
    }
  }

  /////////////////////////////////////////////
  private final DateTimeFormatter dflocal;

  /**
   * Date formatter with specified pattern.
   * NOTE: we are using jodatime patterns right now, but may switch to jsr-310 when thats available in java 8.
   *  Not sure whether these patterns will still work then, so use this formatter at the risk of having to
   *  change it eventually. OTOH, its likely that the same functionality will be present in jsr-310.
   *

   * The pattern syntax is mostly compatible with java.text.SimpleDateFormat -
   * time zone names cannot be parsed and a few more symbols are supported.
   * All ASCII letters are reserved as pattern letters, which are defined as follows:
   *

   *

   * Symbol  Meaning                      Presentation  Examples
   * ------  -------                      ------------  -------
   * G       era                          text          AD
   * C       century of era (>=0)         number        20
   * Y       year of era (>=0)            year          1996
   *
   * x       weekyear                     year          1996
   * w       week of weekyear             number        27
   * e       day of week                  number        2
   * E       day of week                  text          Tuesday; Tue
   *
   * y       year                         year          1996
   * D       day of year                  number        189
   * M       month of year                month         July; Jul; 07
   * d       day of month                 number        10
   *
   * a       halfday of day               text          PM
   * K       hour of halfday (0~11)       number        0
   * h       clockhour of halfday (1~12)  number        12
   *
   * H       hour of day (0~23)           number        0
   * k       clockhour of day (1~24)      number        24
   * m       minute of hour               number        30
   * s       second of minute             number        55
   * S       fraction of second           number        978
   *
   * z       time zone                    text          Pacific Standard Time; PST
   * Z       time zone offset/id          zone          -0800; -08:00; America/Los_Angeles
   *
   * '       escape for text              delimiter
   * ''      single quote                 literal       '
   *

   */
  public CalendarDateFormatter(String pattern) {
    dflocal = DateTimeFormat.forPattern(pattern).withZoneUTC();
  }

  public CalendarDateFormatter(String pattern, CalendarTimeZone tz, Calendar cal) {
    Chronology chron = Calendar.getChronology(cal);
    dflocal = DateTimeFormat.forPattern(pattern).withChronology(chron).withZone(tz.getJodaTimeZone());
  }

  public CalendarDateFormatter(String pattern, CalendarTimeZone tz) {
    dflocal = DateTimeFormat.forPattern(pattern).withZone( tz.getJodaTimeZone());
  }

  public String toString(CalendarDate cd) {
    return dflocal.print(cd.getDateTime());
  }

  public CalendarDate parse(String timeString) {
    DateTime dt = dflocal.parseDateTime(timeString);
    Calendar cal = Calendar.get(dt.getChronology().toString());
    return new CalendarDate(cal, dt);
  }

   public static void main(String arg[]) {
     CalendarDate cd = CalendarDate.present();
     /* {"S", "M", "L", "F", "-"}
     System.out.printf("%s%n", DateTimeFormat.forStyle("SS").print(cd.getDateTime()));
     System.out.printf("%s%n", DateTimeFormat.forStyle("MM").print(cd.getDateTime()));
     System.out.printf("%s%n", DateTimeFormat.forStyle("LL").print(cd.getDateTime()));
     System.out.printf("%s%n", DateTimeFormat.forStyle("FF").print(cd.getDateTime())); */

     System.out.printf("%s%n", cd);
     System.out.printf("toDateTimeStringISO=%s%n", toDateTimeStringISO(cd));
     System.out.printf("   toDateTimeString=%s%n", toDateTimeString(cd));
     System.out.printf("       toDateString=%s%n", toDateString(cd));
     System.out.printf("        toTimeUnits=%s%n", toTimeUnits(cd));
     System.out.printf("===============================%n");
     Date d = cd.toDate();
     System.out.printf("cd.toDate()=%s%n", toDateTimeString(d));

     SimpleDateFormat udunitDF = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
     udunitDF.setTimeZone(TimeZone.getTimeZone("UTC"));
     udunitDF.applyPattern("yyyy-MM-dd HH:mm:ss.SSS 'UTC'");
     System.out.printf("           udunitDF=%s%n", udunitDF.format(d));

     System.out.printf("===============================%n");
     DateFormatter df = new DateFormatter();
     System.out.printf("     toTimeUnits(date)=%s%n", toTimeUnits(cd));
     System.out.printf("toDateTimeString(date)=%s%n", df.toDateTimeString(d));
     System.out.printf("toDateOnlyString(date)=%s%n", df.toDateOnlyString(d));

   }

}


package ucar.nc2.ogc.waterml;

import net.opengis.waterml.x20.MeasureTVPType;
import ucar.nc2.VariableSimpleIF;
import ucar.nc2.ft.PointFeature;
import ucar.nc2.ogc.gml.NcTimePositionType;

import java.io.IOException;

/**
 * Created by cwardgar on 2014/03/05.
 */
public abstract class NcMeasureTVPType {
    // wml2:Collection/wml2:observationMember/om:OM_Observation/om:result/wml2:MeasurementTimeseries/wml2:point/
    //         wml2:MeasurementTVP
    public static MeasureTVPType initMeasurementTVP(MeasureTVPType measurementTVP, PointFeature pointFeat,
            VariableSimpleIF dataVar) throws IOException {
        // wml2:time
        NcTimePositionType.initTime(measurementTVP.addNewTime(), pointFeat);

        // wml2:value
        NcMeasureType.initValue(measurementTVP.addNewValue(), pointFeat, dataVar);

        return measurementTVP;
    }

    private NcMeasureTVPType() { }
}


/*
 * Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata
 * See LICENSE for license information.
 */

package ucar.nc2.util;

import ucar.nc2.constants.CDM;
import ucar.unidata.util.StringUtil2;

import java.io.*;
import java.util.*;
import java.net.URL;

/**
 * Utility class to read and parse a fixed length table.
 * Each line of the table becomes a "Record". Each Record has a set of Fields described by the format string.
 *

 *

 * List<TableParser.Record> recs = TableParser.readTable(is, "3,15,46,54,60d,67d,73d", 50000);
 * for (TableParser.Record record : recs) {
 * Station s = new Station();
 * s.id = "K" + record.get(0);
 * s.name = record.get(2) + " " + record.get(3);
 * s.lat = (Double) record.get(4) * .01;
 * s.lon = (Double) record.get(5) * .01;
 * s.elev = (Double) record.get(6);
 *

 * stationTableHash.put(s.id, s);
 * if (showStations) System.out.println(" station= " + s);
 * }
 *

 * Example Table:
 * TLX      000001 OKLAHOMA_CITY/Norman             OK US  3532  -9727   370  0 NWS
 * AMA      000313 AMARILLO/Amarillo                TX US  3523 -10170  1093  0 NWS
 * HGX      000378 HOUSTON/GALVESTON/Dickinson      TX US  2947  -9507     5  0 NWS
 * MLB      000302 MELBOURNE/Melbourne              FL US  2810  -8065    11  0 NWS
 *

 * format:
 * "3,15,54,60d,67d,73d"
 *

 * grammer:
 * format = {field,}
 * field = endPos type
 * endPos = ending pos in the line, 0 based, exclusive, ie [start, end)
 * type = i=integer, d=double, L=long else String
 * field[0] goes from [0, endPos[0])
 * field[i] goes from [endPos[i-1] to endPos[i])
 *

 *

 *
 * @author caron
 */
/*
    ClassLoader cl = Level2VolumeScan.class.getClassLoader();
    InputStream is = cl.getResourceAsStream("resources/nj22/tables/nexrad.tbl");

    List<TableParser.Record> recs = TableParser.readTable(is, "3,15,46, 54,60d,67d,73d", 50000);
    for (TableParser.Record record : recs) {
      Station s = new Station();
      s.id = "K" + record.get(0);
      s.name = record.get(2) + " " + record.get(3);
      s.lat = (Double) record.get(4) * .01;
      s.lon = (Double) record.get(5) * .01;
      s.elev = (Double) record.get(6);

      stationTableHash.put(s.id, s);
      if (showStations) System.out.println(" station= " + s);
    }

          1         2         3         4         5         6         7         8         9         10        11        12
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

 */
public class TableParser {
  static private final boolean debug = false;

  /**
   * Reads a URL or file in as a table.
   *
   * @param urlString starts with http, read URL contenets, else read file.
   * @param format    describe format of each line.
   * @param maxLines  maximum number of lines to parse, set to < 0 to read all
   * @return List of TableParser.Record
   * @throws IOException           on read error
   * @throws NumberFormatException on parse number error
   * @see #readTable(InputStream ios, String format, int maxLines)
   */
  static public List<Record> readTable(String urlString, String format, int maxLines) throws IOException, NumberFormatException {

    InputStream ios;
    if (urlString.startsWith("http:")) {
      URL url = new URL(urlString);
      ios = url.openStream();
    } else {
      ios = new FileInputStream(urlString);
    }

    return readTable(ios, format, maxLines);
  }

  /**
   * Reads an input stream, containing lines of ascii in fixed width format.
   * Breaks each line into a set of Fields (space or comma delimited) which may be String, integer or double.
   *
   * @param ios      the input stream, will be closed
   * @param format   describe format of each line.
   * @param maxLines maximum number of lines to parse, set to < 0 to read all
   * @return List of TableParser.Record
   * @throws IOException           on read error
   * @throws NumberFormatException on parse number error
   */
  static public List<Record> readTable(InputStream ios, String format, int maxLines) throws IOException, NumberFormatException {
    List<Record> result;
    try {
      TableParser parser = new TableParser(format);
      result = parser.readAllRecords(ios, maxLines);
    } finally {
      ios.close();
    }
    return result;
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////

  private List<Field> fields = new ArrayList<>();
  public TableParser(String format) throws IOException, NumberFormatException {
    int start = 0;
    StringTokenizer stoker = new StringTokenizer(format, " ,");
    while (stoker.hasMoreTokens()) {
      String tok = stoker.nextToken();
      // see what type
      Class type = String.class;
      char last = tok.charAt(tok.length() - 1);
      if (last == 'i') type = int.class;
      if (last == 'd') type = double.class;
      if (last == 'L') type = long.class;
      if (type != String.class) tok = tok.substring(0, tok.length() - 1);

      int end = Integer.parseInt(tok);
      fields.add(new Field(start, end, type));
      start = end;
    }
  }

  private String comment = "#";
  public void setComment(String comment) {
    this.comment = comment;
  }

  public List<Record> readAllRecords(InputStream ios, int maxLines) throws IOException, NumberFormatException {

    List<Record> records = new ArrayList<>();

    BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios, CDM.utf8Charset));
    int count = 0;
    while ((maxLines < 0) || (count < maxLines)) {
      String line = dataIS.readLine();
      if (line == null) break;
      if (line.startsWith(comment)) continue;
      if (line.trim().length() == 0) continue;
      if (debug) System.out.printf("%s%n", line);
      Record r = Record.make(line, fields);
      if (r != null)
        records.add(r);
      count++;
    }

    return records;
  }

  public Field getField(int fldno) {
    return fields.get(fldno);
  }

  public int getNumberOfFields() {
    return fields.size();
  }

  /**
   * Describes one field in the record.
   */
  public static class Field {
    int start, end;
    Class type;

    boolean hasScale = false;
    float scale;

    Field(int start, int end, Class type) {
      this.start = start;
      this.end = end;
      this.type = type;
    }

    protected Field() {}

    public Object parse(String line) throws NumberFormatException {
      return parse(line, this.start, this.end);
    }

    public Object parse(String line, int offset) throws NumberFormatException {
      return parse(line, this.start+offset, this.end+offset);
    }

    protected Object parse(String line, int start, int end) throws NumberFormatException {
      String svalue;
      if (start >= line.length())
        svalue = "";
      else if (end >= line.length())
        svalue = line.substring(start);
      else
        svalue = line.substring(start, end);
      //System.out.printf("  [%d,%d) = %s %n",start, end, svalue);

      if (type == String.class)
        return svalue;

      try {
        svalue = StringUtil2.remove(svalue, ' ');
        boolean isBlank = (svalue.trim().length() == 0);
        if (type == double.class)
          return isBlank ? 0.0 : new Double(svalue);
        if (type == int.class) {
          Integer result = isBlank ? 0 : new Integer(svalue);
          if (hasScale)
            return result * scale;
          else
            return result;
        }
        if (type == long.class)
          return isBlank ? 0L : new Long(svalue);

      } catch (NumberFormatException e) {
        System.out.printf("  [%d,%d) = <%s> %n", start, end, svalue);
        throw e;
      }

      return null;
    }

    public void setScale(float scale) {
      this.scale = scale;
      hasScale = true;
    }

  }

  public DerivedField addDerivedField(Field from, Transform transform, Class type ) {
    DerivedField fld =  new DerivedField(from, transform, type);
    fields.add(fld);
    return fld;
  }

  public static class DerivedField extends Field {
    Field from;
    Transform transform;

    DerivedField(Field from, Transform transform, Class type) {
      this.from = from;
      this.transform = transform;
      this.type = type;
    }

    protected Object parse(String line, int start, int end) throws NumberFormatException {
      Object org = from.parse(line);
      return transform.derive(org);
    }
  }

  public interface Transform {
    Object derive(Object org);
  }

  /**
   * A set of values for one line.
   */
  static public class Record {
    List<Object> values = new ArrayList<>();

    static Record make(String line, List fields) {
      try {
        Record r = new Record();
        for (Object field : fields) {
          Field f = (Field) field;
          r.values.add(f.parse(line));
        }
        return r;
      } catch (NumberFormatException e) {
        System.out.printf("Bad line=%s %n", line);
        return null;
      }
    }

    public int nfields() {
      return values.size();
    }

    /**
     * Get the kth value of this record. Will be a String, Double, or Integer.
     *
     * @param k which one
     * @return object
     */
    public Object get(int k) {
      return values.get(k);
    }

    public void toString(Formatter f) {
      for (Object s : values)
        f.format(" %s,", s.toString());
      f.format("%n");
    }
  }

}