class IospHelper {

  public static long copyToOutputStream(Array data, OutputStream out) throws java.io.IOException {
    Class classType = data.getElementType();

    DataOutputStream dataOut;
    if (out instanceof DataOutputStream)
      dataOut = (DataOutputStream) out;
    else
      dataOut = new DataOutputStream(out);

    /*
     * if (data instanceof ArrayStructure) { // use NcStream encoding
     * return NcStream.encodeArrayStructure((ArrayStructure) data, null, dataOut);
     * }
     */

    IndexIterator iterA = data.getIndexIterator();

    if (classType == double.class) {
      while (iterA.hasNext())
        dataOut.writeDouble(iterA.getDoubleNext());

    } else if (classType == float.class) {
      while (iterA.hasNext())
        dataOut.writeFloat(iterA.getFloatNext());

    } else if (classType == long.class) {
      while (iterA.hasNext())
        dataOut.writeLong(iterA.getLongNext());

    } else if (classType == int.class) {
      while (iterA.hasNext())
        dataOut.writeInt(iterA.getIntNext());

    } else if (classType == short.class) {
      while (iterA.hasNext())
        dataOut.writeShort(iterA.getShortNext());

    } else if (classType == char.class) { // LOOK why are we using chars anyway ?
      byte[] pa = convertCharToByte((char[]) data.get1DJavaArray(DataType.CHAR));
      dataOut.write(pa, 0, pa.length);

    } else if (classType == byte.class) {
      while (iterA.hasNext())
        dataOut.writeByte(iterA.getByteNext());

    } else if (classType == boolean.class) {
      while (iterA.hasNext())
        dataOut.writeBoolean(iterA.getBooleanNext());

    } else if (classType == String.class) {
      long size = 0;
      while (iterA.hasNext()) {
        String s = (String) iterA.getObjectNext();
        size += NcStream.writeString(dataOut, s);
      }
      return size;

    } else if (classType == ByteBuffer.class) { // OPAQUE
      long size = 0;
      while (iterA.hasNext()) {
        ByteBuffer bb = (ByteBuffer) iterA.getObjectNext();
        size += NcStream.writeByteBuffer(dataOut, bb);
      }
      return size;

    } else if (data instanceof ArrayObject) { // vlen
      long size = 0;
      // size += NcStream.writeVInt(outStream, (int) data.getSize()); // nelems already written
      while (iterA.hasNext()) {
        Array row = (Array) iterA.getObjectNext();
        ByteBuffer bb = row.getDataAsByteBuffer();
        size += NcStream.writeByteBuffer(dataOut, bb);
      }
      return size;

    } else
      throw new UnsupportedOperationException("Class type = " + classType.getName());

    return data.getSizeBytes();
  }

}