File: virtual_stream.h

package info (click to toggle)
seqan2 2.4.0%2Bdfsg-17
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 224,224 kB
  • sloc: cpp: 256,886; ansic: 91,672; python: 8,330; sh: 995; xml: 570; makefile: 255; awk: 51; javascript: 21
file content (693 lines) | stat: -rw-r--r-- 25,292 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
// Virtual stream class to automatically compress/decompress files/streams.
// It adapts the zipstream and bzip2stream classes (Jonathan de Halleux, 2003)
// http://www.codeproject.com/Articles/4457/zipstream-bzip2stream-iostream-wrappers-for-the-zl
// and our own implementation of a parallel bgzfstream.
// ==========================================================================

#ifndef SEQAN_STREAM_VIRTUAL_STREAM_
#define SEQAN_STREAM_VIRTUAL_STREAM_

namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

template <typename TStream>
struct StreamFormat;

// ============================================================================
// Tags, Enums
// ============================================================================

// --------------------------------------------------------------------------
// TagList CompressedFileTypes
// --------------------------------------------------------------------------

typedef
#if SEQAN_HAS_ZLIB
    TagList<BgzfFile,
    TagList<GZFile,
#endif
#if SEQAN_HAS_BZIP2
    TagList<BZ2File,
#endif
    TagList<Nothing>
#if SEQAN_HAS_BZIP2
    >
#endif
#if SEQAN_HAS_ZLIB
    >
    >
#endif
    CompressedFileTypes;  // if TagSelector is set to -1, the file format is auto-detected

// ============================================================================
// Metafunctions
// ============================================================================

#if SEQAN_HAS_ZLIB

template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
struct Value<basic_bgzf_istream<Elem, Tr, ElemA, ByteT, ByteAT> > :
    Value<std::basic_istream<Elem, Tr> > {};

template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
struct Position<basic_bgzf_istream<Elem, Tr, ElemA, ByteT, ByteAT> > :
    Position<std::basic_istream<Elem, Tr> > {};


template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
struct Value<basic_bgzf_ostream<Elem, Tr, ElemA, ByteT, ByteAT> > :
    Value<std::basic_ostream<Elem, Tr> > {};

template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
struct Position<basic_bgzf_ostream<Elem, Tr, ElemA, ByteT, ByteAT> > :
    Position<std::basic_ostream<Elem, Tr> > {};


template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
SEQAN_CONCEPT_IMPL((basic_bgzf_istream<Elem, Tr, ElemA, ByteT, ByteAT>), (InputStreamConcept));

template <typename Elem, typename Tr, typename ElemA, typename ByteT, typename ByteAT>
SEQAN_CONCEPT_IMPL((basic_bgzf_ostream<Elem, Tr, ElemA, ByteT, ByteAT>), (OutputStreamConcept));

#endif

// --------------------------------------------------------------------------
// Metafunction VirtualStreamSwitch_
// --------------------------------------------------------------------------

template <typename TValue, typename TDirection, typename TFormatTag>
struct VirtualStreamSwitch_
{
    typedef Nothing Type;
};

#if SEQAN_HAS_ZLIB
template <typename TValue>
struct VirtualStreamSwitch_<TValue, Input, GZFile>
{
    typedef zlib_stream::basic_zip_istream<TValue> Type;
};

template <typename TValue>
struct VirtualStreamSwitch_<TValue, Output, GZFile>
{
    typedef zlib_stream::basic_zip_ostream<TValue> Type;
};

template <typename TValue>
struct VirtualStreamSwitch_<TValue, Input, BgzfFile>
{
    typedef basic_bgzf_istream<TValue> Type;
};

template <typename TValue>
struct VirtualStreamSwitch_<TValue, Output, BgzfFile>
{
    typedef basic_bgzf_ostream<TValue> Type;
};

#endif

#if SEQAN_HAS_BZIP2

template <typename TValue>
struct VirtualStreamSwitch_<TValue, Input, BZ2File>
{
    typedef bzip2_stream::basic_bzip2_istream<TValue> Type;
};

template <typename TValue>
struct VirtualStreamSwitch_<TValue, Output, BZ2File>
{
    typedef bzip2_stream::basic_bzip2_ostream<TValue> Type;
};
#endif

// ==========================================================================
// Classes
// ==========================================================================

// --------------------------------------------------------------------------
// Class VirtualStreamFactoryContext_
// --------------------------------------------------------------------------

template <typename TVirtualStream>
struct VirtualStreamFactoryContext_;

// --------------------------------------------------------------------------
// Class VirtualStreamContext_
// --------------------------------------------------------------------------

// a compressed stream lives in the VirtualStreamContext_ and provides a basic_streambuf

// base class
template <typename TValue, typename TTraits>
struct VirtualStreamContextBase_
{
    std::basic_streambuf<TValue, TTraits> *streamBuf;
    VirtualStreamContextBase_(): streamBuf() {}
    virtual ~VirtualStreamContextBase_() {}
};

// generic subclass with virtual destructor
template <typename TValue, typename TDirection, typename TTraits, typename TFormatTag = void>
struct VirtualStreamContext_:
    VirtualStreamContextBase_<TValue, TTraits>
{
    typename VirtualStreamSwitch_<TValue, TDirection, TFormatTag>::Type stream;

    template <typename TObject>
    VirtualStreamContext_(TObject &object):
        stream(object)
    {
        this->streamBuf = stream.rdbuf();
    }
};

// special case: no compression, we simply forward the file stream
template <typename TValue, typename TDirection, typename TTraits>
struct VirtualStreamContext_<TValue, TDirection, TTraits, Nothing>:
    VirtualStreamContextBase_<TValue, TTraits>
{
    template <typename TObject>
    VirtualStreamContext_(TObject &object)
    {
        this->streamBuf = object.rdbuf();
    }
};

// --------------------------------------------------------------------------
// Class VirtualStream
// --------------------------------------------------------------------------
// The VirtualStream class auto-detects data compression from file name or stream.
// It inherits from std::basic_Xstream to provide the convenient stream interface.
// It accepts a file or stream.

/*!
 * @class VirtualStream
 * @implements StreamConcept
 * @headerfile <seqan/stream.h>
 * @brief Provides seamless (de)compression for another @link StreamConcept stream @endlink.
 *
 * @signature template <typename TValue, typename TDirection, typename TTraits>
 *            class VirtualStream;
 *
 * @tparam TValue       The stream value type, e.g. <tt>char</tt>.
 * @tparam TDirection   The stream direction, one of @link DirectionTags @endlink.
 * @tparam TTraits      The stream traits, defaults to <tt>std::char_traits&lt;TValue&gt;</tt>.
 */

template <typename TValue, typename TDirection, typename TTraits = std::char_traits<TValue> >
class VirtualStream: public BasicStream<TValue, TDirection, TTraits>::Type
{
public:
    typedef typename BasicStream<TValue, TDirection, TTraits>::Type TStream;                // the stream base class we expose
    typedef std::basic_fstream<TValue, TTraits>                     TFile;                  // if a real file should be opened
//    typedef FileStream<TValue, TDirection>                          TFile;                  // if a real file should be opened
    typedef BufferedStream<TStream, TDirection>                     TBufferedStream;        // if input stream is not buffered
    typedef std::basic_streambuf<TValue, TTraits>                   TStreamBuffer;          // the streambuf to use
    typedef VirtualStreamContextBase_<TValue, TTraits>              TVirtualStreamContext;  // the owner of the streambuf
    typedef typename StreamFormat<VirtualStream>::Type              TFormat;                // detected stream format

    TFile                   file;
    TBufferedStream         bufferedStream;
    TStreamBuffer           *streamBuf;
    TVirtualStreamContext   *context;
    TFormat                 format;

    /*!
     * @fn VirtualStream::VirtualStream
     * @brief Default constructor and construction from stream, stream buffer, or filename.
     *
     * @signature VirtualStream::VirtualStream();
     * @signature VirtualStream::VirtualStream(stream);
     * @signature VirtualStream::VirtualStream(streamBuf);
     * @signature VirtualStream::VirtualStream(fileName, openMode);
     *
     * @param[in] stream    The @link StreamConcept stream @endlink to attach to.
     * @param[in] streamBuf The @link StreamBuffer stream buffer @endlink to attach to.
     * @param[in] fileName  Path to the file to open. Type: <tt>char const *</tt>.
     * @param[in] openMode  The open mode. Type: <tt>int</tt>.
     */
    VirtualStream():
        TStream(NULL),
        streamBuf(),
        context()
    {}

    VirtualStream(TStreamBuffer &streamBuf):
        TStream(NULL),
        streamBuf(streamBuf),
        context()
    {}

    VirtualStream(TStream &stream):
        TStream(NULL),
        streamBuf(),
        context()
    {
        open(*this, stream);
    }

    VirtualStream(const char *fileName,
                  int openMode = DefaultOpenMode<VirtualStream>::VALUE):
        TStream(NULL),
        streamBuf(),
        context()
    {
        open(*this, fileName, openMode);
    }

    ~VirtualStream()
    {
        close(*this);
    }


    operator TStreamBuffer*() const
    {
        return streamBuf;
    }

    operator bool() const
    {
        return streamBuf != NULL;
    }

    void _init()
    {
        this->init(streamBuf);
    }

    TStreamBuffer* rdbuf() const
    {
        return streamBuf;
    }

    /*!
     * @fn VirtualStream::getFileExtensions
     * @brief Static function that returns a list of allowed file format extension.
     *
     * @signature TExtensionVector getFileExtensions()
     *
     * @return TExtensionVector A <tt>std::vector&lt;std::string&gt;</tt> with the allowed file extensions.
     */
    static std::vector<std::string>
    getFileExtensions()
    {
        std::vector<std::string> extensions;
        _getFileExtensions(extensions, TFormat());
        return extensions;
    }
};

// ----------------------------------------------------------------------------
// Metafunction StreamFormat
// ----------------------------------------------------------------------------

/*!
 * @defgroup StreamFormats Stream Formats
 * @brief Tags for identifying stream formats.
 */

/*!
 * @mfn VirtualStream#StreamFormat
 * @brief Metafunction for retrieving the format type of a @link VirtualStream @endlink.
 *
 * @signature StreamFormat<TStream>::Type;
 *
 * @tparam TStream  The stream file type to query for its file format type.
 * @return Type     The resulting @link VirtualStream @endlink file formats type.
 */

template <typename TValue, typename TDirection, typename TTraits>
struct StreamFormat<VirtualStream<TValue, TDirection, TTraits> >
{
    typedef TagSelector<CompressedFileTypes> Type;
};

// ----------------------------------------------------------------------------
// Metafunction Value
// ----------------------------------------------------------------------------

template <typename TValue, typename TDirection, typename TTraits>
struct Value<VirtualStream<TValue, TDirection, TTraits> >
{
    typedef TValue Type;
};

// ----------------------------------------------------------------------------
// Metafunction Position
// ----------------------------------------------------------------------------

template <typename TValue, typename TDirection, typename TTraits>
struct Position<VirtualStream<TValue, TDirection, TTraits> >:
    Position<typename VirtualStream<TValue, TDirection, TTraits>::TFile> {};

// ----------------------------------------------------------------------------
// Metafunction Iterator<Standard>
// ----------------------------------------------------------------------------

template <typename TValue, typename TDirection, typename TTraits>
struct Iterator<VirtualStream<TValue, TDirection, TTraits>, TDirection>
{
    typedef Iter<VirtualStream<TValue, TDirection, TTraits>, StreamIterator<TDirection> > Type;
};

// --------------------------------------------------------------------------
// Metafunction DefaultOpenMode<Input>
// --------------------------------------------------------------------------

template <typename TValue, typename TDummy, typename TTraits>
struct DefaultOpenMode<VirtualStream<TValue, Input, TTraits>, TDummy>
{
    enum { VALUE = OPEN_RDONLY };
};

// --------------------------------------------------------------------------
// Metafunction DefaultOpenMode<Output>
// --------------------------------------------------------------------------

template <typename TValue, typename TDummy, typename TTraits>
struct DefaultOpenMode<VirtualStream<TValue, Output, TTraits>, TDummy>
{
    enum { VALUE = OPEN_WRONLY | OPEN_CREATE };
};

// ----------------------------------------------------------------------------
// Concepts
// ----------------------------------------------------------------------------

template <typename TValue>
SEQAN_CONCEPT_IMPL((VirtualStream<TValue, Input>), (InputStreamConcept));

template <typename TValue>
SEQAN_CONCEPT_IMPL((VirtualStream<TValue, Output>), (OutputStreamConcept));

template <typename TValue>
SEQAN_CONCEPT_IMPL((VirtualStream<TValue, Bidirectional>), (BidirectionalStreamConcept));

// --------------------------------------------------------------------------
// Class VirtualStreamFactoryContext_
// --------------------------------------------------------------------------

template <typename TValue, typename TDirection, typename TTraits>
struct VirtualStreamFactoryContext_<VirtualStream<TValue, TDirection, TTraits> >
{
    typedef VirtualStream<TValue, TDirection, TTraits>  TVirtualStream;
    typedef typename TVirtualStream::TStream            TStream;

    TStream &stream;
    VirtualStreamFactoryContext_(TStream &stream):
        stream(stream) {}
};

template <typename TVirtualStream>
struct Value<VirtualStreamFactoryContext_<TVirtualStream> >
{
    typedef typename TVirtualStream::TVirtualStreamContext *Type;
};

// ============================================================================
// Functions
// ============================================================================

// --------------------------------------------------------------------------
// Function tagApply()
// --------------------------------------------------------------------------
// NOTE(esiragusa): private / impl.

template <typename TValue, typename TDirection, typename TTraits, typename TFormat>
inline VirtualStreamContextBase_<TValue, TTraits> *
tagApply(VirtualStreamFactoryContext_<VirtualStream<TValue, TDirection, TTraits> > &ctx, Tag<TFormat>)
{
    return new VirtualStreamContext_<TValue, TDirection, TTraits, Tag<TFormat> >(ctx.stream);
}

// ----------------------------------------------------------------------------
// _guessFormat wrapper
// ----------------------------------------------------------------------------

template <typename TValue, typename TStream, typename TCompressionType>
inline bool _guessFormat(VirtualStream<TValue, Input> &, TStream &fileStream, TCompressionType &compressionType)
{
    // peek the first character to initialize the underlying streambuf
    fileStream.rdbuf()->sgetc();
    return guessFormatFromStream(fileStream, compressionType);
}

template <typename TValue, typename TStream, typename TCompressionType>
inline bool _guessFormat(VirtualStream<TValue, Output> &, TStream &, TCompressionType &)
{
    return true;
}

// ----------------------------------------------------------------------------
// Function _getUncompressedBasename()
// ----------------------------------------------------------------------------

// single format
template <typename TFilename, typename TFormat>
inline typename Prefix<TFilename const>::Type
_getUncompressedBasename(TFilename const & fileName, TFormat const & format)
{
    return getBasename(fileName, format);
}

// make sure not to only cut the ".bgzf" extension and not ".bam"
template <typename TFilename>
inline typename Prefix<TFilename const>::Type
_getUncompressedBasename(TFilename const & fileName, BgzfFile const &)
{
    typedef typename Value<TFilename>::Type                                     TValue;
    typedef ModifiedString<TFilename const, ModView<FunctorLowcase<TValue> > >    TLowcase;

    TLowcase lowcaseFileName(fileName);

    if (endsWith(lowcaseFileName, ".bgzf"))
        return prefix(fileName, length(fileName) - 5);

    if (endsWith(lowcaseFileName, ".gz"))
        return prefix(fileName, length(fileName) - 3);

    return prefix(fileName, length(fileName));
}

// TagSelector
template <typename TFilename>
inline typename Prefix<TFilename const>::Type
_getUncompressedBasename(TFilename const & fname, TagSelector<> const & format)
{
    return getBasename(fname, format);
}

template <typename TFilename, typename TTagList>
inline typename Prefix<TFilename const>::Type
_getUncompressedBasename(TFilename const & fname, TagSelector<TTagList> const & format)
{
    typedef typename TTagList::Type TFormat;

    if (isEqual(format, TFormat()))
        return _getUncompressedBasename(fname, TFormat());
    else
        return _getUncompressedBasename(fname, static_cast<typename TagSelector<TTagList>::Base const &>(format));
}

// --------------------------------------------------------------------------
// Function open()
// --------------------------------------------------------------------------

/*!
 * @fn VirtualStream#open
 * @brief Open a VirtualStream.
 *
 * @signature bool open(stream, fileStream);
 * @signature bool open(stream, fileName, openMode);
 *
 * @param[in,out] stream        The VirtualStream to open.
 * @param[in,out  fileStream    File stream to attach to. Type: <tt>std::fstream</tt>.
 * @param[in]     fileName      Path to the file to open. Type: <tt>char const *</tt>.
 * @param[in]     openMode      The open mode. Type: <tt>int</tt>.
 * @return bool <tt>true</tt> in the case of success, <tt>false</tt> otherwise.
 */

template <typename TValue, typename TDirection, typename TTraits, typename TStream, typename TCompressionType>
inline SEQAN_FUNC_DISABLE_IF(IsPointer<TStream>, bool)
open(VirtualStream<TValue, TDirection, TTraits> &stream, TStream &fileStream, TCompressionType & compressionType)
{
    SEQAN_ASSERT_MSG(stream.context == NULL, "VirtualStream: close() must be called before re-opening.");

    typedef VirtualStream<TValue, TDirection, TTraits> TVirtualStream;
    typedef typename TVirtualStream::TBufferedStream TBufferedStream;

    // peek the first character to initialize the underlying streambuf (for in_avail)
    SEQAN_IF_CONSTEXPR (IsSameType<TDirection, Input>::VALUE)  // Only getc if input stream.
        fileStream.rdbuf()->sgetc();

    SEQAN_IF_CONSTEXPR (IsSameType<TDirection, Input>::VALUE && !IsSameType<TStream, TBufferedStream>::VALUE)
    {
        if (fileStream.rdbuf()->in_avail() < 2)
        {
            stream.bufferedStream.setStream(fileStream);
            return open(stream, stream.bufferedStream, compressionType);
        }
    }

    VirtualStreamFactoryContext_<TVirtualStream> ctx(fileStream);

    // try to detect/verify format
    if (!_guessFormat(stream, fileStream, compressionType))
        return false;

    // create a new (un)zipper buffer
    stream.context = tagApply(ctx, compressionType);
    if (stream.context == NULL)
        return false;

    SEQAN_ASSERT(stream.context->streamBuf != NULL);
    stream.streamBuf = stream.context->streamBuf;

    // reset our outer stream interface
    stream._init();
    return true;
}

template <typename TValue, typename TDirection, typename TTraits, typename TStream, typename TCompressionType>
inline SEQAN_FUNC_DISABLE_IF(IsPointer<TStream>, bool)
open(VirtualStream<TValue, TDirection, TTraits> &stream, TStream &fileStream, TCompressionType const & compressionType)
{
    assign(stream.format, compressionType);
    return open(stream, fileStream, stream.format);
}

template <typename TValue, typename TStream>
inline SEQAN_FUNC_DISABLE_IF(IsPointer<TStream>, bool)
open(VirtualStream<TValue, Input> &stream, TStream &fileStream)
{
    // detect compression type from file extension
    assign(stream.format, typename StreamFormat<VirtualStream<TValue, Input> >::Type());
    return open(stream, fileStream, stream.format);
}

template <typename TValue, typename TDirection, typename TTraits>
inline bool
open(VirtualStream<TValue, TDirection, TTraits> &stream,
     const char *fileName,
     int openMode = DefaultOpenMode<VirtualStream<TValue, TDirection, TTraits> >::VALUE)
{
    SEQAN_ASSERT_MSG(stream.context == NULL, "VirtualStream: close() must be called before re-opening.");

    typedef VirtualStream<TValue, TDirection, TTraits> TVirtualStream;

    if (!open(stream.file, fileName, openMode))
        return false;

    // detect compression type from file extension
    assign(stream.format, typename StreamFormat<TVirtualStream>::Type());

    if (IsSameType<TDirection, Input>::VALUE && _isPipe(fileName))
        open(stream, stream.file, stream.format);               // read from a pipe (without file extension)
    else
        guessFormatFromFilename(fileName, stream.format);       // read/write from/to a file (with extension)

    VirtualStreamFactoryContext_<TVirtualStream> ctx(stream.file);

    // create a new (un)zipper buffer
    stream.context = tagApply(ctx, stream.format);
    if (stream.context == NULL)
    {
        close(stream.file);
        return false;
    }
    stream.streamBuf = stream.context->streamBuf;

    // reset our outer stream interface
    stream._init();
    return true;
}

// --------------------------------------------------------------------------
// Function close()
// --------------------------------------------------------------------------

/*!
 * @fn VirtualStream#close
 * @brief Close a VirtualStream.
 *
 * @signature bool close(stream);
 *
 * @param[in,out] stream The VirtualStream to close.
 * @return bool <tt>true</tt> in the case of success, <tt>false</tt> otherwise.
 */

template <typename TValue, typename TDirection, typename TTraits>
inline bool
close(VirtualStream<TValue, TDirection, TTraits> &stream)
{
    delete stream.context;
    stream.context = NULL;
    stream.streamBuf = NULL;
    assign(stream.format, typename StreamFormat<VirtualStream<TValue, TDirection, TTraits> >::Type());
    return !stream.file.is_open() || close(stream.file);
}

// ----------------------------------------------------------------------------
// Function format()
// ----------------------------------------------------------------------------

/*!
 * @fn VirtualStream#format
 * @brief Return the format of a VirtualStream.
 *
 * @signature TFormat format(stream);
 *
 * @param[in] stream The VirtualStream to check.
 * @return TFormat   The type as returned from @link VirtualStream#StreamFormat @endlink.
 */

template <typename TValue, typename TDirection, typename TTraits>
inline typename StreamFormat<VirtualStream<TValue, TDirection, TTraits> >::Type &
format(VirtualStream<TValue, TDirection, TTraits> &stream)
{
    return stream.format;
}

}  // namespace seqan

#endif  // #ifndef SEQAN_STREAM_VIRTUAL_STREAM_