/**
   * Constructs a new file based on data in <code>in</code>.
   *
   * @param in the input stream to be decoded
   * @throws IOException if decoding fails
   */
  public DG_3_FILE(InputStream in) throws IOException {
    BERTLVInputStream tlvIn = new BERTLVInputStream(in);
    int tag = tlvIn.readTag();
    if (tag != FileStructure.EF_DG3_TAG) {
      throw new IllegalArgumentException("Expected EF_DG3_TAG");
    }
    isSourceConsistent = false;

    tlvIn.readLength();
    byte[] valueBytes = tlvIn.readValue();
    BERTLVObject mainObject = new BERTLVObject(tag, valueBytes);
    BERTLVObject tagsObject = mainObject.getSubObject(TAGS_TAG);

    byte[] tags = (byte[]) tagsObject.getValue();

    String tagString = Hex.bytesToHexString(tags);

    for (int i = 0; i < (tags.length / 2); i++) {
      String num = tagString.substring(i * 4, (i + 1) * 4);
      short tagNum = Hex.hexStringToShort(num);
      tagList.add(new Integer(tagNum));
      BERTLVObject o = mainObject.getSubObject(tagNum);
      byte[] value = (byte[]) o.getValue();
      switch (tagNum) {
        case EMTRY_TAG:
          emtry = new String(value);
          break;
        default:
          throw new IOException("Unexpected tag.");
      }
    }
  }
  /** Gets the BERTLV encoded version of this file. */
  public byte[] getEncoded() {
    if (isSourceConsistent) {
      return sourceObject.getEncoded();
    }
    try {
      Iterator<Integer> it = tagList.iterator();
      String tagValues = "";
      Vector<BERTLVObject> objs = new Vector<BERTLVObject>();
      while (it.hasNext()) {
        short tag = it.next().shortValue();
        tagValues += Hex.shortToHexString(tag);
        byte[] value = null;
        switch (tag) {
          case EMTRY_TAG:
            value = emtry.getBytes();
            break;
          default:
            break;
        }
        BERTLVObject o = new BERTLVObject(tag, value);
        objs.add(o);
      }

      BERTLVObject result =
          new BERTLVObject(EF_DG3_TAG, new BERTLVObject(TAGS_TAG, Hex.hexStringToBytes(tagValues)));

      Iterator<BERTLVObject> i = objs.iterator();
      while (i.hasNext()) {
        result.addSubObject(i.next());
      }
      result.reconstructLength();
      sourceObject = result;
      isSourceConsistent = true;
      return result.getEncoded();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }