]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Don't warn user with useless messages.
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/11/03 14:39:47 $
7   Version:   $Revision: 1.322 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmDocument.h"
20 #include "gdcmSeqEntry.h"
21 #include "gdcmGlobal.h"
22 #include "gdcmUtil.h"
23 #include "gdcmDebug.h"
24 #include "gdcmTS.h"
25 #include "gdcmDictSet.h"
26 #include "gdcmDocEntrySet.h"
27 #include "gdcmSQItem.h"
28 #include "gdcmDataEntry.h"
29
30 #include <vector>
31 #include <iomanip>
32 #include <fstream>
33 #include <ctype.h>  // for isdigit
34 #include <stdlib.h> // for atoi
35
36 namespace gdcm 
37 {
38 //-----------------------------------------------------------------------------
39
40 // Refer to Document::SetMaxSizeLoadEntry()
41 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
42
43 //-----------------------------------------------------------------------------
44 // Constructor / Destructor
45 // Constructors and destructors are protected to avoid user to invoke directly
46
47 /**
48  * \brief This default constructor neither loads nor parses the file. 
49  *        You should then invoke \ref Document::Load.
50  *         
51  */
52 Document::Document() 
53          :ElementSet()
54 {
55    Fp = 0;
56
57    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
58    Initialize();
59    SwapCode = 1234;
60    Filetype = ExplicitVR;
61    // Load will set it to true if sucessfull
62    Group0002Parsed = false;
63    IsDocumentAlreadyLoaded = false;
64    IsDocumentModified = true;
65    LoadMode = LD_ALL; // default : load everything, later
66    SetFileName("");
67 }
68
69 /**
70  * \brief   Canonical destructor.
71  */
72 Document::~Document ()
73 {
74    CloseFile();
75 }
76
77 //-----------------------------------------------------------------------------
78 // Public
79
80 /**
81  * \brief   Loader. use SetLoadMode(), SetFileName() before ! 
82  * @return false if file cannot be open or no swap info was found,
83  *         or no tag was found.
84  */
85 bool Document::Load(  ) 
86 {
87    if ( GetFileName() == "" )
88    {
89       gdcmWarningMacro( "Use SetFileName, before !" );
90       return false;
91    }
92    return DoTheLoadingDocumentJob( );
93
94 /**
95  * \brief   Loader. (DEPRECATED : not to break the API)   
96  * @param   fileName 'Document' (File or DicomDir) to be open for parsing
97  * @return false if file cannot be open or no swap info was found,
98  *         or no tag was found.
99  */
100 bool Document::Load( std::string const &fileName ) 
101 {
102    Filename = fileName;
103    return DoTheLoadingDocumentJob( );
104 }
105
106 /**
107  * \brief   Performs the Loading Job (internal use only)  
108  * @return false if file cannot be open or no swap info was found,
109  *         or no tag was found.
110  */
111 bool Document::DoTheLoadingDocumentJob(  ) 
112 {
113    if ( ! IsDocumentModified ) // Nothing to do !
114       return true;
115
116    ClearEntry();
117
118    Fp = 0;
119    if ( !OpenFile() )
120    {
121       // warning already performed in OpenFile()
122       Filetype = Unknown;
123       return false;
124    }
125
126    Group0002Parsed = false;
127
128    gdcmDebugMacro( "Starting parsing of file: " << Filename.c_str());
129
130    Fp->seekg(0, std::ios::end);
131    long lgt = Fp->tellg();       // total length of the file
132
133    Fp->seekg(0, std::ios::beg);
134
135    // CheckSwap returns a boolean 
136    // (false if no swap info of any kind was found)
137    if (! CheckSwap() )
138    {
139       gdcmWarningMacro( "Neither a DICOM V3 nor an ACR-NEMA file: " 
140                    << Filename.c_str());
141       CloseFile(); 
142       return false;      
143     }
144
145    long beg = Fp->tellg();      // just after DICOM preamble (if any)
146
147    lgt -= beg;                  // remaining length to parse    
148
149    // Recursive call.
150    // Loading is done during parsing
151    ParseDES( this, beg, lgt, false); // delim_mode is first defaulted to false
152
153    if ( IsEmpty() )
154    { 
155       gdcmErrorMacro( "No tag in internal hash table for: "
156                         << Filename.c_str());
157       CloseFile(); 
158       return false;
159    }
160    IsDocumentAlreadyLoaded = true;
161
162    Fp->seekg( 0, std::ios::beg);
163    
164    // Load 'non string' values
165       
166    std::string PhotometricInterpretation = GetEntryString(0x0028,0x0004);   
167    if ( PhotometricInterpretation == "PALETTE COLOR " )
168    {
169    // FIXME
170    // Probabely this line should be outside the 'if'
171    // Try to find an image sample holding a 'gray LUT'
172       LoadEntryBinArea(0x0028,0x1200);  // gray LUT
173    
174       /// FIXME
175       /// --> FIXME : The difference between BinEntry and DataEntry
176       /// --> no longer exists, but the alteration of Dicom Dictionary remains.
177       /// --> Old comment restored on purpose.
178       /// --> New one (replacing both BinEntry and ValEntry by DataEntry)
179       /// --> had absolutely no meaning.
180       /// --> The whole comment will be removed when the stuff is cleaned !
181       /// -->
182       /// The tags refered by the three following lines used to be CORRECTLY
183       /// defined as having an US Value Representation in the public
184       /// dictionary. BUT the semantics implied by the three following
185       /// lines state that the corresponding tag contents are in fact
186       /// the ones of a BinEntry.
187       /// In order to fix things "Quick and Dirty" the dictionary was
188       /// altered on PURPOSE but now contains a WRONG value.
189       /// In order to fix things and restore the dictionary to its
190       /// correct value, one needs to decide of the semantics by deciding
191       /// whether the following tags are either :
192       /// - multivaluated US, and hence loaded as ValEntry, but afterwards
193       ///   also used as BinEntry, which requires the proper conversion,
194       /// - OW, and hence loaded as BinEntry, but afterwards also used
195       ///   as ValEntry, which requires the proper conversion.
196       
197       // --> OB (byte aray) or OW (short int aray)
198       // The actual VR has to be deduced from other entries.
199       // Our way of loading them may fail in some cases :
200       // We must or not SwapByte depending on other field values.
201              
202       LoadEntryBinArea(0x0028,0x1201);  // R    LUT
203       LoadEntryBinArea(0x0028,0x1202);  // G    LUT
204       LoadEntryBinArea(0x0028,0x1203);  // B    LUT
205       
206       // Segmented Red   Palette Color LUT Data
207       LoadEntryBinArea(0x0028,0x1221);
208       // Segmented Green Palette Color LUT Data
209       LoadEntryBinArea(0x0028,0x1222);
210       // Segmented Blue  Palette Color LUT Data
211       LoadEntryBinArea(0x0028,0x1223);
212    }
213  
214    //FIXME later : how to use it?
215    SeqEntry *modLutSeq = GetSeqEntry(0x0028,0x3000);
216    if ( modLutSeq !=0 )
217    {
218       SQItem *sqi= modLutSeq->GetFirstSQItem();
219       if ( sqi != 0 )
220       {
221          DataEntry *dataEntry = sqi->GetDataEntry(0x0028,0x3006);
222          if ( dataEntry != 0 )
223          {
224             if ( dataEntry->GetLength() != 0 )
225             {
226                // FIXME : CTX dependent means : contexted dependant.
227                //         see upper comment.
228                LoadEntryBinArea(dataEntry);    //LUT Data (CTX dependent)
229             }   
230         }
231      }      
232    }
233
234    // Force Loading some more elements if user asked to.
235
236    gdcm::DocEntry *d;
237    for (ListElements::iterator it = UserForceLoadList.begin();  
238                                it != UserForceLoadList.end();
239                              ++it)
240    {
241       gdcmDebugMacro( "Force Load " << std::hex 
242                        << (*it).Group << "|" <<(*it).Elem );
243   
244       d = GetDocEntry( (*it).Group, (*it).Elem);
245   
246       if ( d == NULL)
247       {
248          gdcmWarningMacro( "You asked toForce Load "  << std::hex
249                           << (*it).Group <<"|"<< (*it).Elem
250                           << " that doesn't exist" );
251          continue;
252       }
253
254       LoadDocEntry(d, true);
255    }
256
257    CloseFile(); 
258   
259    // ----------------------------
260    // Specific code to allow gdcm to read ACR-LibIDO formated images
261    // Note: ACR-LibIDO is an extension of the ACR standard that was
262    //       used at CREATIS. For the time being (say a couple of years)
263    //       we keep this kludge to allow CREATIS users 
264    //       reading their old images.
265    //
266    // if recognition code tells us we deal with a LibIDO image
267    // we switch lineNumber and columnNumber
268    //
269    std::string RecCode;
270    RecCode = GetEntryString(0x0008, 0x0010); // recognition code (RET)
271    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
272        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
273                                           // with "little-endian strings"
274    {
275          Filetype = ACR_LIBIDO; 
276          std::string rows    = GetEntryString(0x0028, 0x0010);
277          std::string columns = GetEntryString(0x0028, 0x0011);
278          SetEntryString(columns, 0x0028, 0x0010);
279          SetEntryString(rows   , 0x0028, 0x0011);
280    }
281    // --- End of ACR-LibIDO kludge --- 
282    return true;
283 }
284
285
286 /**
287  * \brief Adds a new element we want to load anyway
288  * @param   group  Group number of the target tag.
289  * @param   elem Element number of the target tag.
290  */
291 void Document::AddForceLoadElement (uint16_t group, uint16_t elem) 
292
293    DicomElement el;
294    el.Group = group;
295    el.Elem  = elem;
296    UserForceLoadList.push_back(el); 
297 }
298 /**
299  * \brief   Get the public dictionary used
300  */
301 Dict *Document::GetPubDict()
302 {
303    return RefPubDict;
304 }
305
306 /**
307  * \brief   Get the shadow dictionary used
308  */
309 Dict *Document::GetShaDict()
310 {
311    return RefShaDict;
312 }
313
314 /**
315  * \brief   Set the shadow dictionary used
316  * @param   dict dictionary to use in shadow
317  */
318 bool Document::SetShaDict(Dict *dict)
319 {
320    RefShaDict = dict;
321    return !RefShaDict;
322 }
323
324 /**
325  * \brief   Set the shadow dictionary used
326  * @param   dictName name of the dictionary to use in shadow
327  */
328 bool Document::SetShaDict(DictKey const &dictName)
329 {
330    RefShaDict = Global::GetDicts()->GetDict(dictName);
331    return !RefShaDict;
332 }
333
334 /**
335  * \brief  This predicate tells us whether or not the current Document 
336  *         was properly parsed and contains at least *one* Dicom Element
337  *         (and nothing more, sorry).
338  * @return false when we're 150 % sure it's NOT a Dicom/Acr file,
339  *         true otherwise. 
340  */
341 bool Document::IsReadable()
342 {
343    if ( Filetype == Unknown )
344    {
345       gdcmErrorMacro( "Wrong filetype");
346       return false;
347    }
348
349    if ( IsEmpty() )
350    { 
351       gdcmErrorMacro( "No tag in internal hash table.");
352       return false;
353    }
354
355    return true;
356 }
357
358 /**
359  * \brief   Predicate for dicom version 3 file.
360  * @return  True when the file is a dicom version 3.
361  */
362 bool Document::IsDicomV3()
363 {
364    // Checking if Transfer Syntax exists is enough
365    // Anyway, it's too late check if the 'Preamble' was found ...
366    // And ... would it be a rich idea to check ?
367    // (some 'no Preamble' DICOM images exist !)
368    return GetDocEntry(0x0002, 0x0010) != NULL;
369 }
370
371 /**
372  * \brief   Predicate for Papyrus file
373  *          Dedicated to whomsoever it may concern
374  * @return  True when the file is a Papyrus file.
375  */
376 bool Document::IsPapyrus()
377 {
378    // check for Papyrus private Sequence
379    DocEntry *e = GetDocEntry(0x0041, 0x1050);
380    if ( !e )
381       return false;
382    // check if it's actually a Sequence
383    if ( !dynamic_cast<SeqEntry*>(e) )
384       return  false;
385    return true;
386 }
387
388 /**
389  * \brief  returns the File Type 
390  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
391  * @return the FileType code
392  */
393 FileType Document::GetFileType()
394 {
395    return Filetype;
396 }
397
398 /**
399  * \brief   Accessor to the Transfer Syntax (when present) of the
400  *          current document (it internally handles reading the
401  *          value from disk when only parsing occured).
402  * @return  The encountered Transfer Syntax of the current document, if DICOM.
403  *          GDCM_UNKNOWN for ACR-NEMA files (or broken headers ...)
404  */
405 std::string Document::GetTransferSyntax()
406 {
407    DocEntry *entry = GetDocEntry(0x0002, 0x0010);
408    if ( !entry )
409    {
410       return GDCM_UNKNOWN;
411    }
412
413    // The entry might be present but not loaded (parsing and loading
414    // happen at different stages): try loading and proceed with check...
415    LoadDocEntrySafe(entry);
416    if (DataEntry *dataEntry = dynamic_cast<DataEntry *>(entry) )
417    {
418       std::string transfer = dataEntry->GetString();
419       // The actual transfer (as read from disk) might be padded. We
420       // first need to remove the potential padding. We can make the
421       // weak assumption that padding was not executed with digits...
422       if  ( transfer.length() == 0 )
423       {
424          // for brain damaged headers
425          gdcmWarningMacro( "Transfer Syntax has length = 0.");
426          return GDCM_UNKNOWN;
427       }
428       while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
429       {
430          transfer.erase(transfer.length()-1, 1);
431          if  ( transfer.length() == 0 )
432          {
433             // for brain damaged headers
434             gdcmWarningMacro( "Transfer Syntax contains no valid character.");
435             return GDCM_UNKNOWN;
436          }
437       }
438       return transfer;
439    }
440    return GDCM_UNKNOWN;
441 }
442
443 /**
444  * \brief Accesses the info from 0002,0010 : Transfer Syntax and TS
445  * @return The full Transfer Syntax Name (as opposed to Transfer Syntax UID)
446  */
447 std::string Document::GetTransferSyntaxName()
448 {
449    // use the TS (TS : Transfer Syntax)
450    std::string transferSyntax = GetEntryString(0x0002,0x0010);
451
452    if ( (transferSyntax.find(GDCM_NOTLOADED) < transferSyntax.length()) )
453    {
454       gdcmErrorMacro( "Transfer Syntax not loaded. " << std::endl
455                << "Better you increase MAX_SIZE_LOAD_ELEMENT_VALUE" );
456       return "Uncompressed ACR-NEMA";
457    }
458    if ( transferSyntax == GDCM_UNFOUND )
459    {
460       gdcmDebugMacro( "Unfound Transfer Syntax (0002,0010)");
461       return "Uncompressed ACR-NEMA";
462    }
463
464    // we do it only when we need it
465    const TSKey &tsName = Global::GetTS()->GetValue( transferSyntax );
466
467    // Global::GetTS() is a global static you shall never try to delete it!
468    return tsName;
469 }
470 //
471 // --------------- Swap Code ------------------
472 /**
473  * \brief   Swaps the bytes so they agree with the processor order
474  * @return  The properly swaped 16 bits integer.
475  */
476 uint16_t Document::SwapShort(uint16_t a)
477 {
478    if ( SwapCode == 4321 || SwapCode == 2143 )
479    {
480       //a = ((( a << 8 ) & 0xff00 ) | (( a >> 8 ) & 0x00ff ) );
481       // Save CPU time
482       a = ( a << 8 ) | ( a >> 8 );
483    }
484    return a;
485 }
486
487 /**
488  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
489  *          processor order.
490  * @return  The properly swaped 32 bits integer.
491  */
492 uint32_t Document::SwapLong(uint32_t a)
493 {
494    switch (SwapCode)
495    {
496       case 1234 :
497          break;
498       case 4321 :
499 //         a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
500 //             ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
501 // save CPU time
502          a=( ( a<<24)               | ((a<<8)  & 0x00ff0000) | 
503              ((a>>8)  & 0x0000ff00) |  (a>>24)                );
504          break;   
505       case 3412 :
506 //       a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
507          a=( (a<<16)                | (a>>16)  );
508          break;  
509       case 2143 :
510          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
511       break;
512       default :
513          gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
514          a = 0;
515    }
516    return a;
517
518
519 /**
520  * \brief   Swaps back the bytes of 8-byte long 'double' accordingly to
521  *          processor order.
522  * @return  The properly swaped 64 bits double.
523  */
524 double Document::SwapDouble(double a)
525 {
526    switch (SwapCode)
527    {
528       // There were no 'double' at ACR-NEMA time.
529       // We just have to deal with 'straight Little Endian' and 
530       // 'straight Big Endian'
531       case 1234 :
532          break;
533       case 4321 :
534          {
535          char *beg = (char *)&a;
536          char *end = beg + 7;
537          char t;
538          for (unsigned int i = 0; i<7; i++)
539          {
540             t    = *beg;
541             *beg = *end;
542             *end = t;
543             beg++,
544             end--;  
545          }
546          }
547          break;   
548       default :
549          gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
550          a = 0.;
551    }
552    return a;
553
554
555 //
556 // -----------------File I/O ---------------
557 /**
558  * \brief  Tries to open the file \ref Document::Filename and
559  *         checks the preamble when existing.
560  * @return The FILE pointer on success. 
561  */
562 std::ifstream *Document::OpenFile()
563 {
564    HasDCMPreamble = false;
565    if (Filename.length() == 0) 
566    {
567       return 0;
568    }
569
570    if ( Fp )
571    {
572       gdcmDebugMacro( "File already open: " << Filename.c_str());
573       CloseFile();
574    }
575
576    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
577    if ( ! *Fp )
578    {
579    // Don't user gdcmErrorMacro :
580    // a spurious message will appear when you use, for instance 
581    // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
582    // to create outputFileName.
583    
584    // FIXME : if the upper comment is still usefull 
585    //         --> the constructor is not so good ...
586    
587       gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
588       delete Fp;
589       Fp = 0;
590       return 0;
591       //exit(1); // No function is allowed to leave the application instead
592                  // of warning the caller
593    }
594  
595    uint16_t zero = 0;
596    Fp->read((char*)&zero, (size_t)2);
597    if ( Fp->eof() )
598    {
599       CloseFile();
600       return 0;
601    }
602  
603    //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
604    if ( 
605        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
606        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
607        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
608        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
609    {
610       std::string msg = Util::Format(
611         "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
612       // FIXME : is it a Warning message, or a Debug message?
613       gdcmWarningMacro( msg.c_str() );
614       return Fp;
615    }
616  
617    //-- DICOM --
618    Fp->seekg(126L, std::ios::cur);
619    char dicm[4]; // = {' ',' ',' ',' '};
620    Fp->read(dicm,  (size_t)4);
621    if ( Fp->eof() )
622    {
623       CloseFile();
624       return 0;
625    }
626    if ( memcmp(dicm, "DICM", 4) == 0 )
627    {
628       HasDCMPreamble = true;
629       return Fp;
630    }
631
632    // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
633    CloseFile();
634    // Don't user Warning nor Error, not to polute the output
635    // while directory recursive parsing ...
636    gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
637                       << Filename.c_str()); 
638    return 0;
639 }
640
641 /**
642  * \brief closes the file  
643  * @return  TRUE if the close was successfull 
644  */
645 bool Document::CloseFile()
646 {
647    if ( Fp )
648    {
649       Fp->close();
650       delete Fp;
651       Fp = 0;
652    }
653    return true;
654 }
655
656 /**
657  * \brief Writes in a file all the Entries (Dicom Elements) 
658  * @param fp file pointer on an already open file (actually: Output File Stream)
659  * @param filetype Type of the File to be written 
660  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
661  */
662 void Document::WriteContent(std::ofstream *fp, FileType filetype)
663 {
664    // Skip if user wants to write an ACR-NEMA file
665
666    if ( filetype == ImplicitVR || filetype == ExplicitVR ||
667         filetype == JPEG )
668    {
669       // writing Dicom File Preamble
670       char filePreamble[128];
671       memset(filePreamble, 0, 128);
672       fp->write(filePreamble, 128);
673       fp->write("DICM", 4);
674    }
675
676    /*
677     * \todo rewrite later, if really usefull
678     *       - 'Group Length' element is optional in DICOM
679     *       - but un-updated odd groups lengthes can causes pb
680     *         (xmedcon breaker)
681     *
682     * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
683     *    UpdateGroupLength(false,filetype);
684     * if ( filetype == ACR)
685     *    UpdateGroupLength(true,ACR);
686     *
687     * --> Computing group length for groups with embeded Sequences
688     * --> was too much tricky / we were [in a hurry / too lazy]
689     * --> We don't write the element 0x0000 (group length)
690     */
691
692    ElementSet::WriteContent(fp, filetype); // This one is recursive
693 }
694
695 // -----------------------------------------
696 // Content entries 
697 /**
698  * \brief Loads (from disk) the element content 
699  *        when a string is not suitable
700  * @param group   group number of the Entry 
701  * @param elem  element number of the Entry
702  */
703 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
704 {
705    // Search the corresponding DocEntry
706    DocEntry *docEntry = GetDocEntry(group, elem);
707    if ( !docEntry )
708    {
709       gdcmWarningMacro(std::hex << group << "|" << elem 
710                        <<  "doesn't exist" );
711       return;
712    }
713    DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
714    if ( !dataEntry )
715    {
716       gdcmWarningMacro(std::hex << group << "|" << elem 
717                        <<  "is NOT a DataEntry");
718       return;
719    }
720    LoadEntryBinArea(dataEntry);
721 }
722
723 /**
724  * \brief Loads (from disk) the element content 
725  *        when a string is not suitable
726  * @param entry  Entry whose binArea is going to be loaded
727  */
728 void Document::LoadEntryBinArea(DataEntry *entry) 
729 {
730    if( entry->GetBinArea() )
731       return;
732
733    bool openFile = !Fp;
734    if ( openFile )
735       OpenFile();
736
737    size_t o =(size_t)entry->GetOffset();
738    Fp->seekg(o, std::ios::beg);
739
740    size_t l = entry->GetLength();
741    uint8_t *data = new uint8_t[l];
742    if ( !data )
743    {
744       gdcmWarningMacro(  "Cannot allocate DataEntry content for : "
745                        << std::hex << entry->GetGroup() 
746                        << "|" << entry->GetElement() );
747       return;
748    }
749
750    // Read the data
751    Fp->read((char*)data, l);
752    if ( Fp->fail() || Fp->eof() )
753    {
754       delete[] data;
755       entry->SetState(DataEntry::STATE_UNREAD);
756       return;
757    }
758
759    // Swap the data content if necessary
760    uint32_t i;
761    unsigned short vrLgth = 
762                         Global::GetVR()->GetAtomicElementLength(entry->GetVR());
763
764 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
765 //   if( entry->GetVR() == "OW" )
766 //      vrLgth = 1;
767
768    switch(vrLgth)
769    {
770       case 1:
771       {
772          break;
773       }     
774       case 2:
775       {
776          uint16_t *data16 = (uint16_t *)data;
777          for(i=0;i<l/vrLgth;i++)
778             data16[i] = SwapShort(data16[i]);
779          break;
780       }
781       case 4:
782       {
783          uint32_t *data32 = (uint32_t *)data;
784          for(i=0;i<l/vrLgth;i++)
785             data32[i] = SwapLong(data32[i]);
786          break;
787       }
788       case 8:
789       {
790          double *data64 = (double *)data;
791          for(i=0;i<l/vrLgth;i++)
792             data64[i] = SwapDouble(data64[i]);
793          break;
794       }
795    }
796    
797    entry->SetBinArea(data);
798
799    if ( openFile )
800       CloseFile();
801 }
802
803 /**
804  * \brief  Loads the element while preserving the current
805  *         underlying file position indicator as opposed to
806  *        LoadDocEntry that modifies it.
807  * @param entry   DocEntry whose value will be loaded. 
808  */
809 void Document::LoadDocEntrySafe(DocEntry *entry)
810 {
811    if ( Fp )
812    {
813       long PositionOnEntry = Fp->tellg();
814       LoadDocEntry(entry);
815       Fp->seekg(PositionOnEntry, std::ios::beg);
816    }
817 }
818
819 /**
820  * \brief   Compares two documents, according to \ref DicomDir rules
821  * \warning Does NOT work with ACR-NEMA files
822  * \todo    Find a trick to solve the pb (use RET fields ?)
823  * @param   document to compare with current one
824  * @return  true if 'smaller'
825  */
826 bool Document::operator<(Document &document)
827 {
828    // Patient Name
829    std::string s1 = GetEntryString(0x0010,0x0010);
830    std::string s2 = document.GetEntryString(0x0010,0x0010);
831    if (s1 < s2)
832    {
833       return true;
834    }
835    else if ( s1 > s2 )
836    {
837       return false;
838    }
839    else
840    {
841       // Patient ID
842       s1 = GetEntryString(0x0010,0x0020);
843       s2 = document.GetEntryString(0x0010,0x0020);
844       if ( s1 < s2 )
845       {
846          return true;
847       }
848       else if ( s1 > s2 )
849       {
850          return false;
851       }
852       else
853       {
854          // Study Instance UID
855          s1 = GetEntryString(0x0020,0x000d);
856          s2 = document.GetEntryString(0x0020,0x000d);
857          if ( s1 < s2 )
858          {
859             return true;
860          }
861          else if ( s1 > s2 )
862          {
863             return false;
864          }
865          else
866          {
867             // Serie Instance UID
868             s1 = GetEntryString(0x0020,0x000e);
869             s2 = document.GetEntryString(0x0020,0x000e);    
870             if ( s1 < s2 )
871             {
872                return true;
873             }
874             else if ( s1 > s2 )
875             {
876                return false;
877             }
878          }
879       }
880    }
881    return false;
882 }
883
884 //-----------------------------------------------------------------------------
885 // Protected
886 /**
887  * \brief Reads a supposed to be 16 Bits integer
888  *       (swaps it depending on processor endianness) 
889  * @return read value
890  */
891 uint16_t Document::ReadInt16()
892    throw( FormatError )
893 {
894    uint16_t g;
895    Fp->read ((char*)&g, (size_t)2);
896    if ( Fp->fail() )
897    {
898       throw FormatError( "Document::ReadInt16()", " file error." );
899    }
900    if ( Fp->eof() )
901    {
902       throw FormatError( "Document::ReadInt16()", "EOF." );
903    }
904    g = SwapShort(g); 
905    return g;
906 }
907
908 /**
909  * \brief  Reads a supposed to be 32 Bits integer
910  *        (swaps it depending on processor endianness)  
911  * @return read value
912  */
913 uint32_t Document::ReadInt32()
914    throw( FormatError )
915 {
916    uint32_t g;
917    Fp->read ((char*)&g, (size_t)4);
918    if ( Fp->fail() )
919    {
920       throw FormatError( "Document::ReadInt32()", " file error." );
921    }
922    if ( Fp->eof() )
923    {
924       throw FormatError( "Document::ReadInt32()", "EOF." );
925    }
926    g = SwapLong(g);
927    return g;
928 }
929
930 /**
931  * \brief skips bytes inside the source file 
932  * \warning NOT end user intended method !
933  * @return 
934  */
935 void Document::SkipBytes(uint32_t nBytes)
936 {
937    //FIXME don't dump the returned value
938    Fp->seekg((long)nBytes, std::ios::cur);
939 }
940
941 /**
942  * \brief   Re-computes the length of the Dicom group 0002.
943  */
944 int Document::ComputeGroup0002Length( ) 
945 {
946    uint16_t gr;
947    VRKey vr;
948    
949    int groupLength = 0;
950    bool found0002 = false;   
951   
952    // for each zero-level Tag in the DCM Header
953    DocEntry *entry = GetFirstEntry();
954    while( entry )
955    {
956       gr = entry->GetGroup();
957
958       if ( gr == 0x0002 )
959       {
960          found0002 = true;
961
962          if ( entry->GetElement() != 0x0000 )
963          {
964             vr = entry->GetVR();
965
966             //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
967             // (no SQ, OW, UT in group 0x0002;)
968                if ( vr == "OB" ) 
969                {
970                   // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
971                   groupLength +=  4;
972                }
973  
974             groupLength += 2 + 2 + 4 + entry->GetLength();   
975          }
976       }
977       else if (found0002 )
978          break;
979
980       entry = GetNextEntry();
981    }
982    return groupLength; 
983 }
984
985 //-----------------------------------------------------------------------------
986 // Private
987 /**
988  * \brief Loads all the needed Dictionaries
989  * \warning NOT end user intended method !   
990  */
991 void Document::Initialize() 
992 {
993    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
994    RefShaDict = NULL;
995    Filetype   = Unknown;
996 }
997
998 /**
999  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1000  * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1001  * @param offset start of parsing
1002  * @param l_max  length to parse (meaningless when we are in 'delimitor mode')
1003  * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1004  */ 
1005 void Document::ParseDES(DocEntrySet *set, long offset, 
1006                         long l_max, bool delim_mode)
1007 {
1008    DocEntry *newDocEntry;
1009    DataEntry *newDataEntry;
1010    SeqEntry *newSeqEntry;
1011    VRKey vr;
1012    bool used; // will be set to false when something wrong happens to an Entry.
1013               // (Entry will then be deleted)
1014    bool delim_mode_intern = delim_mode;
1015    bool first = true;
1016    gdcmDebugMacro( "Enter in ParseDES, delim-mode " <<  delim_mode
1017                      << " at offset " << std::hex << offset ); 
1018    while (true)
1019    {
1020       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1021       {
1022          break;
1023       }
1024
1025       newDocEntry = ReadNextDocEntry( );
1026
1027       // Uncoment this cerr line to be able to 'follow' the DocEntries
1028       // when something *very* strange happens
1029       if( Debug::GetDebugFlag() ) 
1030          std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1031
1032       if ( !newDocEntry )
1033       {
1034          break;
1035       }
1036
1037        // an Item Starter found elsewhere but the first position
1038        // of a SeqEntry  means previous entry was a Sequence
1039        // but we didn't get it (private Sequence + Implicit VR)
1040        // we have to backtrack.
1041       if ( !first && newDocEntry->IsItemStarter() )
1042       { 
1043         // Debug message within the method !      
1044         newDocEntry = Backtrack(newDocEntry); 
1045       }
1046       else
1047       { 
1048          PreviousDocEntry = newDocEntry; 
1049       }
1050  
1051       used = true;
1052       newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1053
1054       if ( newDataEntry )  
1055       {
1056          //////////////////////////// DataEntry
1057  
1058          vr = newDocEntry->GetVR();
1059
1060          if ( !set->AddEntry( newDataEntry ) )
1061          {
1062             gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1063                                  << newDataEntry->GetKey()  
1064                                  << " (at offset : " 
1065                                  << newDataEntry->GetOffset() << " )" );
1066             used=false;
1067          }
1068          else
1069          {
1070             newDataEntry->Delete();
1071             // Load only if we can add (not a duplicate key)
1072             LoadDocEntry( newDataEntry );
1073          }
1074
1075          if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1076          {
1077             if ( newDataEntry->GetGroup()%2 != 0 )   // if Shadow Group
1078             {
1079                if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1080                {
1081                   std::string strLgrGroup = newDataEntry->GetString();
1082                   int lgrGroup;
1083                   if ( newDataEntry->IsUnfound() )
1084                   {
1085                      lgrGroup = atoi(strLgrGroup.c_str());
1086                      Fp->seekg(lgrGroup, std::ios::cur);
1087                      //used = false;  // never used
1088                      RemoveEntry( newDocEntry );  // Remove and delete
1089                      // bcc 5.5 is right "assigned a value that's never used"
1090                      // newDocEntry = 0;
1091                      continue;
1092                   }
1093                }
1094             }
1095          }
1096
1097          bool delimitor = newDataEntry->IsItemDelimitor();
1098
1099          if ( (delimitor) || 
1100                (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1101          {
1102             if ( !used )
1103                newDocEntry->Delete();
1104             break;
1105          }
1106
1107          // Just to make sure we are at the beginning of next entry.
1108          SkipToNextDocEntry(newDocEntry);
1109       }
1110       else
1111       {
1112          /////////////////////// SeqEntry :  VR = "SQ"
1113
1114          unsigned long l = newDocEntry->GetReadLength();          
1115          if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1116          {
1117             if ( l == 0xffffffff )
1118             {
1119               delim_mode_intern = true;
1120             }
1121             else
1122             {
1123               delim_mode_intern = false;
1124             }
1125          }
1126
1127          if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1128          { 
1129            // User asked to skip SeQuences *only* if they belong to Shadow Group
1130             if ( newDocEntry->GetGroup()%2 != 0 )
1131             {
1132                 Fp->seekg( l, std::ios::cur);
1133                 newDocEntry->Delete();  // Delete, not in the set 
1134                 continue;  
1135             } 
1136          } 
1137          if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern ) 
1138          {
1139            // User asked to skip *any* SeQuence
1140             Fp->seekg( l, std::ios::cur);
1141             newDocEntry->Delete(); // Delete, not in the set
1142             continue;
1143          }
1144          // delay the dynamic cast as late as possible
1145          newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1146          
1147          // no other way to create the Delimitor ...
1148          newSeqEntry->SetDelimitorMode( delim_mode_intern );
1149
1150          // At the top of the hierarchy, stands a Document. When "set"
1151          // is a Document, then we are building the first depth level.
1152          // Hence the SeqEntry we are building simply has a depth
1153          // level of one:
1154         if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1155          {
1156             newSeqEntry->SetDepthLevel( 1 );
1157          }
1158          // But when "set" is already a SQItem, we are building a nested
1159          // sequence, and hence the depth level of the new SeqEntry
1160          // we are building, is one level deeper:
1161
1162          // time waste hunting
1163          else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1164          {
1165             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1166          }
1167
1168          if ( l != 0 )
1169          {  // Don't try to parse zero-length sequences
1170
1171             gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1172                                << " at offset " << std::hex
1173                                << newDocEntry->GetOffset() );
1174
1175             ParseSQ( newSeqEntry, 
1176                      newDocEntry->GetOffset(),
1177                      l, delim_mode_intern);
1178
1179             gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1180  
1181          }
1182          if ( !set->AddEntry( newSeqEntry ) )
1183          {
1184             gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1185                                 << newSeqEntry->GetKey()
1186                                 << " (at offset : " 
1187                                 << newSeqEntry->GetOffset() << " )" ); 
1188             used = false;
1189          }
1190          else
1191          {
1192             newDocEntry->Delete();
1193          }
1194  
1195          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1196          {
1197             if ( !used )
1198                newDocEntry->Delete();
1199             break;
1200          }
1201       }  // end SeqEntry : VR = "SQ"
1202
1203       if ( !used )
1204       {
1205          newDocEntry->Delete();
1206       }
1207       first = false;
1208    }                               // end While
1209    gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1210 }
1211
1212 /**
1213  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1214  * @return  parsed length for this level
1215  */ 
1216 void Document::ParseSQ( SeqEntry *seqEntry,
1217                         long offset, long l_max, bool delim_mode)
1218 {
1219    int SQItemNumber = 0;
1220    bool dlm_mod;
1221    long offsetStartCurrentSQItem = offset;
1222
1223    while (true)
1224    {
1225       // the first time, we read the fff0,e000 of the first SQItem
1226       DocEntry *newDocEntry = ReadNextDocEntry();
1227
1228       if ( !newDocEntry )
1229       {
1230          gdcmWarningMacro("in ParseSQ : should never get here!");
1231          break;
1232       }
1233       if ( delim_mode )
1234       {
1235          if ( newDocEntry->IsSequenceDelimitor() )
1236          {
1237             seqEntry->SetDelimitationItem( newDocEntry ); 
1238             newDocEntry->Delete();
1239             break;
1240          }
1241       }
1242       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1243       {
1244          newDocEntry->Delete();
1245          break;
1246       }
1247       // create the current SQItem
1248       SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1249       unsigned int l = newDocEntry->GetReadLength();
1250       
1251       if ( l == 0xffffffff )
1252       {
1253          dlm_mod = true;
1254       }
1255       else
1256       {
1257          dlm_mod = false;
1258       }
1259
1260       // remove fff0,e000, created out of the SQItem
1261       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1262       // fill up the current SQItem, starting at the beginning of fff0,e000
1263
1264       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1265
1266       offsetStartCurrentSQItem = Fp->tellg();
1267  
1268       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1269       itemSQ->Delete();
1270       newDocEntry->Delete();
1271       SQItemNumber++;
1272       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1273       {
1274          break;
1275       }
1276    }
1277 }
1278
1279 /**
1280  * \brief   When a private Sequence + Implicit VR is encountered
1281  *           we cannot guess it's a Sequence till we find the first
1282  *           Item Starter. We then backtrack to do the job.
1283  * @param   docEntry Item Starter that warned us 
1284  */
1285 DocEntry *Document::Backtrack(DocEntry *docEntry)
1286 {
1287    // delete the Item Starter, built erroneously out of any Sequence
1288    // it's not yet in the HTable/chained list
1289    docEntry->Delete();
1290
1291    // Get all info we can from PreviousDocEntry
1292    uint16_t group = PreviousDocEntry->GetGroup();
1293    uint16_t elem  = PreviousDocEntry->GetElement();
1294    uint32_t lgt   = PreviousDocEntry->GetLength();
1295    long offset    = PreviousDocEntry->GetOffset();
1296
1297    gdcmDebugMacro( "Backtrack :" << std::hex << group 
1298                                    << "|" << elem
1299                                    << " at offset " << offset );
1300    RemoveEntry( PreviousDocEntry );
1301
1302    // forge the Seq Entry
1303    DocEntry *newEntry = NewSeqEntry(group, elem);
1304    newEntry->SetLength(lgt);
1305    newEntry->SetOffset(offset);
1306
1307    // Move back to the beginning of the Sequence
1308    Fp->seekg( 0, std::ios::beg);
1309    Fp->seekg(offset, std::ios::cur);
1310
1311    return newEntry;
1312 }
1313
1314 /**
1315  * \brief   Loads (or not) the element content depending if its length exceeds
1316  *          or not the value specified with Document::SetMaxSizeLoadEntry()
1317  * @param   entry Header Entry (Dicom Element) to be dealt with
1318  * @param forceLoad whether you want to force loading of 'long' elements
1319  */
1320 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1321 {
1322    uint16_t group  = entry->GetGroup();
1323    uint16_t elem  = entry->GetElement();
1324    const VRKey  &vr = entry->GetVR();
1325    uint32_t length = entry->GetLength();
1326
1327    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1328
1329    // A SeQuence "contains" a set of Elements.  
1330    //          (fffe e000) tells us an Element is beginning
1331    //          (fffe e00d) tells us an Element just ended
1332    //          (fffe e0dd) tells us the current SeQuence just ended
1333    //
1334    //          (fffe 0000) is an 'impossible' tag value, 
1335    //                                    found in MR-PHILIPS-16-Multi-Seq.dcm
1336    
1337    if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1338    {
1339       // NO more value field for SQ !
1340       return;
1341    }
1342
1343    DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1344    if( !dataEntryPtr )
1345    {
1346       return;
1347    }
1348
1349    // When the length is zero things are easy:
1350    if ( length == 0 )
1351    {
1352       dataEntryPtr->SetBinArea(NULL,true);
1353       return;
1354    }
1355
1356    // The elements whose length is bigger than the specified upper bound
1357    // are not loaded.
1358
1359    std::ostringstream s;
1360
1361    if (!forceLoad)
1362    {
1363       if (length > MaxSizeLoadEntry)
1364       {
1365          dataEntryPtr->SetBinArea(NULL,true);
1366          dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1367
1368          // to be sure we are at the end of the value ...
1369          Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1370                    std::ios::beg);
1371          return;
1372       }
1373    }
1374
1375    LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1376 }
1377
1378 /**
1379  * \brief  Find the value Length of the passed Doc Entry
1380  * @param  entry Header Entry whose length of the value shall be loaded. 
1381  */
1382 void Document::FindDocEntryLength( DocEntry *entry )
1383    throw ( FormatError )
1384 {
1385    const VRKey &vr  = entry->GetVR();
1386    uint16_t length16;       
1387    
1388    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1389    {
1390       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" 
1391                                                            || vr == "UN" )
1392       {
1393          // The following reserved two bytes (see PS 3.5-2003, section
1394          // "7.1.2 Data element structure with explicit vr", p 27) must be
1395          // skipped before proceeding on reading the length on 4 bytes.
1396          Fp->seekg( 2L, std::ios::cur);
1397          uint32_t length32 = ReadInt32();
1398
1399          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1400          {
1401             uint32_t lengthOB;
1402             try 
1403             {
1404                lengthOB = FindDocEntryLengthOBOrOW();
1405             }
1406             catch ( FormatUnexpected )
1407             {
1408                // Computing the length failed (this happens with broken
1409                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1410                // chance to get the pixels by deciding the element goes
1411                // until the end of the file. Hence we artificially fix the
1412                // the length and proceed.
1413                gdcmWarningMacro( " Computing the length failed for " << 
1414                                    entry->GetKey() <<" in " <<GetFileName());
1415
1416                long currentPosition = Fp->tellg();
1417                Fp->seekg(0L,std::ios::end);
1418
1419                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1420                Fp->seekg(currentPosition, std::ios::beg);
1421
1422                entry->SetReadLength(lengthUntilEOF);
1423                entry->SetLength(lengthUntilEOF);
1424                return;
1425             }
1426             entry->SetReadLength(lengthOB);
1427             entry->SetLength(lengthOB);
1428             return;
1429          }
1430          FixDocEntryFoundLength(entry, length32); 
1431          return;
1432       }
1433
1434       // Length is encoded on 2 bytes.
1435       length16 = ReadInt16();
1436   
1437       // 0xffff means that we deal with 'No Length' Sequence 
1438       //        or 'No Length' SQItem
1439       if ( length16 == 0xffff) 
1440       {           
1441          length16 = 0;
1442       }
1443       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1444       return;
1445    }
1446    else
1447    {
1448       // Either implicit VR or a non DICOM conformal (see note below) explicit
1449       // VR that ommited the VR of (at least) this element. Farts happen.
1450       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1451       // on Data elements "Implicit and Explicit VR Data Elements shall
1452       // not coexist in a Data Set and Data Sets nested within it".]
1453       // Length is on 4 bytes.
1454
1455      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1456      // even if Transfer Syntax is 'Implicit VR ...'
1457      // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private' 
1458       
1459       FixDocEntryFoundLength( entry, ReadInt32() );
1460       return;
1461    }
1462 }
1463
1464 /**
1465  * \brief  Find the Length till the next sequence delimiter
1466  * \warning NOT end user intended method !
1467  * @return 
1468  */
1469 uint32_t Document::FindDocEntryLengthOBOrOW()
1470    throw( FormatUnexpected )
1471 {
1472    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1473    long positionOnEntry = Fp->tellg();
1474    bool foundSequenceDelimiter = false;
1475    uint32_t totalLength = 0;
1476
1477    while ( !foundSequenceDelimiter )
1478    {
1479       uint16_t group;
1480       uint16_t elem;
1481       try
1482       {
1483          group = ReadInt16();
1484          elem  = ReadInt16();   
1485       }
1486       catch ( FormatError )
1487       {
1488          throw FormatError("Unexpected end of file encountered during ",
1489                            "Document::FindDocEntryLengthOBOrOW()");
1490       }
1491       // We have to decount the group and element we just read
1492       totalLength += 4;     
1493       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1494       {
1495          long filePosition = Fp->tellg();
1496          gdcmWarningMacro( 
1497               "Neither an Item tag nor a Sequence delimiter tag on :" 
1498            << std::hex << group << " , " << elem 
1499            << ") -before- position x(" << filePosition << ")" );
1500   
1501          Fp->seekg(positionOnEntry, std::ios::beg);
1502          throw FormatUnexpected( 
1503                "Neither an Item tag nor a Sequence delimiter tag.");
1504       }
1505       if ( elem == 0xe0dd )
1506       {
1507          foundSequenceDelimiter = true;
1508       }
1509       uint32_t itemLength = ReadInt32();
1510       // We add 4 bytes since we just read the ItemLength with ReadInt32
1511       totalLength += itemLength + 4;
1512       SkipBytes(itemLength);
1513       
1514       if ( foundSequenceDelimiter )
1515       {
1516          break;
1517       }
1518    }
1519    Fp->seekg( positionOnEntry, std::ios::beg);
1520    return totalLength;
1521 }
1522
1523 /**
1524  * \brief     Find the Value Representation of the current Dicom Element.
1525  * @return    Value Representation of the current Entry
1526  */
1527 VRKey Document::FindDocEntryVR()
1528 {
1529    if ( Filetype != ExplicitVR )
1530       return GDCM_VRUNKNOWN;
1531
1532    long positionOnEntry = Fp->tellg();
1533    // Warning: we believe this is explicit VR (Value Representation) because
1534    // we used a heuristic that found "UL" in the first tag and/or
1535    // 'Transfer Syntax' told us it is.
1536    // Alas this doesn't guarantee that all the tags will be in explicit VR. 
1537    // In some cases one finds implicit VR tags mixed within an explicit VR file.
1538    // Hence we make sure the present tag is in explicit VR and try to fix things
1539    // if it happens not to be the case.
1540
1541    VRKey vr;
1542    Fp->read(&(vr[0]),(size_t)2);
1543
1544    if ( !CheckDocEntryVR(vr) )
1545    {
1546       // Don't warn user with useless messages
1547       if ( vr[0] != 0xff || vr[1] != 0xff )
1548          gdcmWarningMacro( "Unknown VR " << std::hex << "0x(" 
1549                         << (unsigned int)vr[0] << "|" << (unsigned int)vr[1] 
1550                         << ") at offset :" << positionOnEntry );
1551       Fp->seekg(positionOnEntry, std::ios::beg);
1552       return GDCM_VRUNKNOWN;
1553    }
1554    return vr;
1555 }
1556
1557 /**
1558  * \brief     Check the correspondance between the VR of the header entry
1559  *            and the taken VR. If they are different, the header entry is 
1560  *            updated with the new VR.
1561  * @param     vr    Dicom Value Representation
1562  * @return    false if the VR is incorrect or if the VR isn't referenced
1563  *            otherwise, it returns true
1564 */
1565 bool Document::CheckDocEntryVR(const VRKey &vr)
1566 {
1567    return Global::GetVR()->IsValidVR(vr);
1568 }
1569
1570 /**
1571  * \brief   Skip a given Header Entry 
1572  * \warning NOT end user intended method !
1573  * @param   entry entry to skip
1574  */
1575 void Document::SkipDocEntry(DocEntry *entry) 
1576 {
1577    SkipBytes(entry->GetLength());
1578 }
1579
1580 /**
1581  * \brief   Skips to the beginning of the next Header Entry 
1582  * \warning NOT end user intended method !
1583  * @param   currentDocEntry entry to skip
1584  */
1585 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1586 {
1587    int l = currentDocEntry->GetReadLength();
1588    if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1589                   // ... but PMS imagers happen !
1590       return;
1591    Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1592    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1593    {
1594       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1595    }
1596 }
1597
1598 /**
1599  * \brief   When the length of an element value is obviously wrong (because
1600  *          the parser went Jabberwocky) one can hope improving things by
1601  *          applying some heuristics.
1602  * @param   entry entry to check
1603  * @param   foundLength first assumption about length    
1604  */
1605 void Document::FixDocEntryFoundLength(DocEntry *entry,
1606                                       uint32_t foundLength)
1607 {
1608    entry->SetReadLength( foundLength );// will be updated only if a bug is found
1609    if ( foundLength == 0xffffffff)
1610    {
1611       foundLength = 0;
1612    }
1613    
1614    uint16_t gr   = entry->GetGroup();
1615    uint16_t elem = entry->GetElement(); 
1616      
1617    if ( foundLength % 2)
1618    {
1619       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1620         <<  " in x(" << std::hex << gr << "," << elem <<")");
1621    }
1622       
1623    //////// Fix for some naughty General Electric images.
1624    // Allthough not recent many such GE corrupted images are still present
1625    // on Creatis hard disks. Hence this fix shall remain when such images
1626    // are no longer in use (we are talking a few years, here)...
1627    // Note: XMedCon probably uses such a trick since it is able to read
1628    //       those pesky GE images ...
1629    if ( foundLength == 13)
1630    {
1631       // Only happens for this length !
1632       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1633       {
1634          foundLength = 10;
1635          entry->SetReadLength(10); // a bug is to be fixed !?
1636       }
1637    }
1638
1639    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1640    // Occurence of such images is quite low (unless one leaves close to a
1641    // 'Leonardo' source. Hence, one might consider commenting out the
1642    // following fix on efficiency reasons.
1643    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1644    {
1645       foundLength = 4;
1646       entry->SetReadLength(4); // a bug is to be fixed !
1647    } 
1648  
1649    else if ( entry->GetVR() == "SQ" )
1650    {
1651       foundLength = 0;      // ReadLength is unchanged 
1652    } 
1653     
1654    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1655    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1656    // taken into account.
1657    else if ( gr == 0xfffe )
1658    {    
1659      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1660      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1661      // causes extra troubles...
1662      if ( entry->GetElement() != 0x0000 )
1663      {
1664         foundLength = 0;
1665      }
1666      else
1667      {
1668         foundLength=12; // to skip the mess that follows this bugged Tag !
1669      }
1670    }                
1671    entry->SetLength(foundLength);
1672 }
1673
1674 /**
1675  * \brief   Apply some heuristics to predict whether the considered 
1676  *          element value contains/represents an integer or not.
1677  * @param   entry The element value on which to apply the predicate.
1678  * @return  The result of the heuristical predicate.
1679  */
1680 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1681 {
1682    uint16_t elem         = entry->GetElement();
1683    uint16_t group        = entry->GetGroup();
1684    const VRKey &vr       = entry->GetVR();
1685    uint32_t length       = entry->GetLength();
1686
1687    // When we have some semantics on the element we just read, and if we
1688    // a priori know we are dealing with an integer, then we shall be
1689    // able to swap it's element value properly.
1690    if ( elem == 0 )  // This is the group length of the group
1691    {  
1692       if ( length == 4 )
1693       {
1694          return true;
1695       }
1696       else 
1697       {
1698          // Although this should never happen, still some images have a
1699          // corrupted group length [e.g. have a glance at offset x(8336) of
1700          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1701          // Since for dicom compliant and well behaved headers, the present
1702          // test is useless (and might even look a bit paranoid), when we
1703          // encounter such an ill-formed image, we simply display a warning
1704          // message and proceed on parsing (while crossing fingers).
1705          long filePosition = Fp->tellg();
1706          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1707            << std::hex << group << " , " << elem
1708            << ") -before- position x(" << filePosition << ")"
1709            << "lgt : " << length );
1710       }
1711    }
1712
1713    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1714    {
1715       return true;
1716    }   
1717    return false;
1718 }
1719
1720 /**
1721  * \brief   Discover what the swap code is (among little endian, big endian,
1722  *          bad little endian, bad big endian).
1723  *          sw is set
1724  * @return false when we are absolutely sure 
1725  *               it's neither ACR-NEMA nor DICOM
1726  *         true  when we hope ours assuptions are OK
1727  */
1728 bool Document::CheckSwap()
1729 {   
1730    uint32_t  s32;
1731    uint16_t  s16;
1732        
1733    char deb[256];
1734     
1735    // First, compare HostByteOrder and NetworkByteOrder in order to
1736    // determine if we shall need to swap bytes (i.e. the Endian type).
1737    bool net2host = Util::IsCurrentProcessorBigEndian();
1738          
1739    // The easiest case is the one of a 'true' DICOM header, we just have
1740    // to look for the string "DICM" inside the file preamble.
1741    Fp->read(deb, 256);
1742    
1743    char *entCur = deb + 128;
1744    if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1745    {
1746       gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1747       
1748       // Group 0002 should always be VR, and the first element 0000
1749       // Let's be carefull (so many wrong headers ...)
1750       // and determine the value representation (VR) : 
1751       // Let's skip to the first element (0002,0000) and check there if we find
1752       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1753       // in which case we (almost) know it is explicit VR.
1754       // WARNING: if it happens to be implicit VR then what we will read
1755       // is the length of the group. If this ascii representation of this
1756       // length happens to be "UL" then we shall believe it is explicit VR.
1757       // We need to skip :
1758       // * the 128 bytes of File Preamble (often padded with zeroes),
1759       // * the 4 bytes of "DICM" string,
1760       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1761       // i.e. a total of  136 bytes.
1762       entCur = deb + 136;
1763      
1764       // group 0x0002 *is always* Explicit VR Sometimes ,
1765       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1766       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1767       
1768       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1769            memcmp(entCur, "OB", (size_t)2) == 0 ||
1770            memcmp(entCur, "UI", (size_t)2) == 0 ||
1771            memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1772                                                    // when Write DCM *adds*
1773       // FIXME
1774       // Use Document::dicom_vr to test all the possibilities
1775       // instead of just checking for UL, OB and UI !? group 0000 
1776       {
1777          Filetype = ExplicitVR;
1778          gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1779       } 
1780       else 
1781       {
1782          Filetype = ImplicitVR;
1783          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1784                         << "Looks like a bugged Header!");
1785       }
1786       
1787       if ( net2host )
1788       {
1789          SwapCode = 4321;
1790          gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1791       }
1792       else 
1793       {
1794          SwapCode = 1234;
1795          gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1796       }
1797       
1798       // Position the file position indicator at first tag 
1799       // (i.e. after the file preamble and the "DICM" string).
1800
1801       Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1802
1803       Fp->seekg ( 132L, std::ios::beg);
1804       return true;
1805    } // ------------------------------- End of DicomV3 ----------------
1806
1807    // Alas, this is not a DicomV3 file and whatever happens there is no file
1808    // preamble. We can reset the file position indicator to where the data
1809    // is (i.e. the beginning of the file).
1810
1811    gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1812
1813    Fp->seekg(0, std::ios::beg);
1814
1815    // Let's check 'No Preamble Dicom File' :
1816    // Should start with group 0x0002
1817    // and be Explicit Value Representation
1818
1819    s16 = *((uint16_t *)(deb));
1820    SwapCode = 0;     
1821    switch ( s16 )
1822    {
1823       case 0x0002 :
1824          SwapCode = 1234;
1825          entCur = deb + 4;
1826          break;
1827       case 0x0200 :
1828          SwapCode = 4321;
1829          entCur = deb + 6;
1830     } 
1831
1832    if ( SwapCode != 0 )
1833    {
1834       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1835            memcmp(entCur, "OB", (size_t)2) == 0 ||
1836            memcmp(entCur, "UI", (size_t)2) == 0 ||
1837            memcmp(entCur, "SH", (size_t)2) == 0 ||
1838            memcmp(entCur, "AE", (size_t)2) == 0 ||
1839            memcmp(entCur, "OB", (size_t)2) == 0 )
1840          {
1841             Filetype = ExplicitVR;
1842             gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1843             return true;
1844           }
1845     }
1846 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1847
1848    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1849    // By clean we mean that the length of the first group is written down.
1850    // If this is the case and since the length of the first group HAS to be
1851    // four (bytes), then determining the proper swap code is straightforward.
1852
1853    entCur = deb + 4;
1854    // We assume the array of char we are considering contains the binary
1855    // representation of a 32 bits integer. Hence the following dirty
1856    // trick :
1857    s32 = *((uint32_t *)(entCur));
1858    switch( s32 )
1859    {
1860       case 0x00040000 :
1861          SwapCode = 3412;
1862          Filetype = ACR;
1863          return true;
1864       case 0x04000000 :
1865          SwapCode = 4321;
1866          Filetype = ACR;
1867          return true;
1868       case 0x00000400 :
1869          SwapCode = 2143;
1870          Filetype = ACR;
1871          return true;
1872       case 0x00000004 :
1873          SwapCode = 1234;
1874          Filetype = ACR;
1875          return true;
1876       default :
1877          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1878          // It is time for despaired wild guesses. 
1879          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1880          //  i.e. the 'group length' element is not present :     
1881          
1882          //  check the supposed-to-be 'group number'
1883          //  in ( 0x0001 .. 0x0008 )
1884          //  to determine ' SwapCode' value .
1885          //  Only 0 or 4321 will be possible 
1886          //  (no oportunity to check for the formerly well known
1887          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1888          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1889          //  the file IS NOT ACR-NEMA nor DICOM V3
1890          //  Find a trick to tell it the caller...
1891       
1892          s16 = *((uint16_t *)(deb));
1893       
1894          switch ( s16 )
1895          {
1896             case 0x0001 :
1897             case 0x0002 :
1898             case 0x0003 :
1899             case 0x0004 :
1900             case 0x0005 :
1901             case 0x0006 :
1902             case 0x0007 :
1903             case 0x0008 :
1904                SwapCode = 1234;
1905                Filetype = ACR;
1906                return true;
1907             case 0x0100 :
1908             case 0x0200 :
1909             case 0x0300 :
1910             case 0x0400 :
1911             case 0x0500 :
1912             case 0x0600 :
1913             case 0x0700 :
1914             case 0x0800 :
1915                SwapCode = 4321;
1916                Filetype = ACR;
1917                return true;
1918             default :
1919                gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1920                Filetype = Unknown;
1921                return false;
1922          }
1923    }
1924 }
1925
1926 /**
1927  * \brief Change the Byte Swap code. 
1928  */
1929 void Document::SwitchByteSwapCode() 
1930 {
1931    gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1932                      << " at: 0x" << std::hex << Fp->tellg() );
1933    if ( SwapCode == 1234 ) 
1934    {
1935       SwapCode = 4321;
1936    }
1937    else if ( SwapCode == 4321 ) 
1938    {
1939       SwapCode = 1234;
1940    }
1941    else if ( SwapCode == 3412 ) 
1942    {
1943       SwapCode = 2143;
1944    }
1945    else if ( SwapCode == 2143 )
1946    {
1947       SwapCode = 3412;
1948    }
1949    gdcmDebugMacro( " Into: "<< SwapCode );
1950 }
1951
1952 /**
1953  * \brief  during parsing, Header Elements too long are not loaded in memory
1954  * @param newSize new size
1955  */
1956 void Document::SetMaxSizeLoadEntry(long newSize) 
1957 {
1958    if ( newSize < 0 )
1959    {
1960       return;
1961    }
1962    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1963    {
1964       MaxSizeLoadEntry = 0xffffffff;
1965       return;
1966    }
1967    MaxSizeLoadEntry = newSize;
1968 }
1969
1970 /**
1971  * \brief   Read the next tag WITHOUT loading it's value
1972  *          (read the 'Group Number', the 'Element Number',
1973  *          gets the Dict Entry
1974  *          gets the VR, gets the length, gets the offset value)
1975  * @return  On succes : the newly created DocEntry, NULL on failure.      
1976  */
1977 DocEntry *Document::ReadNextDocEntry()
1978 {
1979    uint16_t group;
1980    uint16_t elem;
1981
1982    try
1983    {
1984       group = ReadInt16();
1985       elem  = ReadInt16();
1986    }
1987    catch ( FormatError )
1988    {
1989       // We reached the EOF (or an error occured) therefore 
1990       // header parsing has to be considered as finished.
1991       return 0;
1992    }
1993
1994    // Sometimes file contains groups of tags with reversed endianess.
1995    HandleBrokenEndian(group, elem);
1996
1997    // In 'true DICOM' files Group 0002 is always little endian
1998    if ( HasDCMPreamble )
1999       HandleOutOfGroup0002(group, elem);
2000  
2001    VRKey vr = FindDocEntryVR();
2002    
2003    VRKey realVR = vr;
2004
2005    if ( vr == GDCM_VRUNKNOWN )
2006    {
2007       if ( elem == 0x0000 ) // Group Length
2008       {
2009          realVR = "UL";     // must be UL
2010       }
2011       else if (group%2 == 1 &&  (elem >= 0x0010 && elem <=0x00ff ))
2012       {  
2013       // DICOM PS 3-5 7.8.1 a) states that those 
2014       // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2015          realVR = "LO";
2016       }
2017       else
2018       {
2019          DictEntry *dictEntry = GetDictEntry(group,elem);
2020          if ( dictEntry )
2021          {
2022             realVR = dictEntry->GetVR();
2023             dictEntry->Unregister();
2024          }
2025       }
2026    }
2027   // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2028
2029    DocEntry *newEntry;
2030    if ( Global::GetVR()->IsVROfSequence(realVR) )
2031       newEntry = NewSeqEntry(group, elem);
2032    else 
2033    {
2034       newEntry = NewDataEntry(group, elem, realVR);
2035       static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2036    }
2037
2038    if ( vr == GDCM_VRUNKNOWN )
2039    {
2040       if ( Filetype == ExplicitVR )
2041       {
2042          // We thought this was explicit VR, but we end up with an
2043          // implicit VR tag. Let's backtrack.
2044          if ( newEntry->GetGroup() != 0xfffe )
2045          { 
2046             std::string msg;
2047             int offset = Fp->tellg();
2048             msg = Util::Format(
2049                         "Entry (%04x,%04x) at x(%x) should be Explicit VR\n", 
2050                         newEntry->GetGroup(), newEntry->GetElement(), offset );
2051             gdcmWarningMacro( msg.c_str() );
2052           }
2053       }
2054       newEntry->SetImplicitVR();
2055    }
2056
2057    try
2058    {
2059       FindDocEntryLength(newEntry);
2060    }
2061    catch ( FormatError )
2062    {
2063       // Call it quits
2064       newEntry->Delete();
2065       return 0;
2066    }
2067
2068    newEntry->SetOffset(Fp->tellg());  
2069    
2070    return newEntry;
2071 }
2072
2073 /**
2074  * \brief   Handle broken private tag from Philips NTSCAN
2075  *          where the endianess is being switched to BigEndian 
2076  *          for no apparent reason
2077  * @return  no return
2078  */
2079 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2080 {
2081    // Endian reversion. 
2082    // Some files contain groups of tags with reversed endianess.
2083    static int reversedEndian = 0;
2084    // try to fix endian switching in the middle of headers
2085    if ((group == 0xfeff) && (elem == 0x00e0))
2086    {
2087      // start endian swap mark for group found
2088      reversedEndian++;
2089      SwitchByteSwapCode();
2090      // fix the tag
2091      group = 0xfffe;
2092      elem  = 0xe000;
2093    } 
2094    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2095    {
2096      // end of reversed endian group
2097      reversedEndian--;
2098      SwitchByteSwapCode();
2099    }
2100    else if (group == 0xfeff && elem == 0xdde0) 
2101    {
2102      // reversed Sequence Terminator found
2103      // probabely a bug in the header !
2104      // Do what you want, it breaks !
2105      //reversedEndian--;
2106      //SwitchByteSwapCode();
2107      gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2108      // fix the tag
2109       group = 0xfffe;
2110       elem  = 0xe0dd;  
2111    }
2112    else if (group == 0xfffe && elem == 0xe0dd) 
2113    {
2114       gdcmDebugMacro( "Straight Sequence Terminator." );  
2115    }
2116 }
2117
2118 /**
2119  * \brief   Group 0002 is always coded Little Endian
2120  *          whatever Transfer Syntax is
2121  * @return  no return
2122  */
2123 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2124 {
2125    // Endian reversion. 
2126    // Some files contain groups of tags with reversed endianess.
2127    if ( !Group0002Parsed && group != 0x0002)
2128    {
2129       Group0002Parsed = true;
2130       // we just came out of group 0002
2131       // if Transfer Syntax is Big Endian we have to change CheckSwap
2132
2133       std::string ts = GetTransferSyntax();
2134       if ( ts == GDCM_UNKNOWN )
2135       {
2136          gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2137          return;      
2138       }
2139       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2140       {
2141          gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: [" 
2142                           << ts << "]");
2143          return;
2144       }
2145
2146       // Group 0002 is always 'Explicit ...' 
2147       // even when Transfer Syntax says 'Implicit ..." 
2148
2149       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == 
2150                                                     TS::ImplicitVRLittleEndian )
2151       {
2152          Filetype = ImplicitVR;
2153       }
2154        
2155       // FIXME Strangely, this works with 
2156       //'Implicit VR BigEndian Transfer Syntax (GE Private)
2157       //
2158       // --> Probabely normal, since we considered we never have 
2159       // to trust manufacturers.
2160       // (we find very often 'Implicit VR' tag, 
2161       // even when Transfer Syntax tells us it's Explicit ...
2162       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == 
2163                                                        TS::ExplicitVRBigEndian )
2164       {
2165          gdcmDebugMacro("Transfer Syntax Name = [" 
2166                         << GetTransferSyntaxName() << "]" );
2167          SwitchByteSwapCode();
2168          group = SwapShort(group);
2169          elem  = SwapShort(elem);
2170       }
2171    }
2172 }
2173
2174 //-----------------------------------------------------------------------------
2175 // Print
2176
2177 //-----------------------------------------------------------------------------
2178 } // end namespace gdcm