]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Add verbosity when trouble occur.
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/10/27 16:52:44 $
7   Version:   $Revision: 1.316 $
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 decided 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          char *beg = (char *)&a;
535          char *end = beg + 7;
536          char t;
537          for (unsigned int i = 0; i<7; i++)
538          {
539             t    = *beg;
540             *beg = *end;
541             *end = t;
542             beg++,
543             end--;  
544          }
545          break;   
546       default :
547          gdcmErrorMacro( "Unexpected swap code:" << SwapCode );
548          a = 0.;
549    }
550    return a;
551
552
553 //
554 // -----------------File I/O ---------------
555 /**
556  * \brief  Tries to open the file \ref Document::Filename and
557  *         checks the preamble when existing.
558  * @return The FILE pointer on success. 
559  */
560 std::ifstream *Document::OpenFile()
561 {
562    HasDCMPreamble = false;
563    if (Filename.length() == 0) 
564    {
565       return 0;
566    }
567
568    if ( Fp )
569    {
570       gdcmDebugMacro( "File already open: " << Filename.c_str());
571       CloseFile();
572    }
573
574    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
575    if ( ! *Fp )
576    {
577    // Don't user gdcmErrorMacro :
578    // a spurious message will appear when you use, for instance 
579    // gdcm::FileHelper *fh = new gdcm::FileHelper( outputFileName );
580    // to create outputFileName.
581    
582    // FIXME : if the upper comment is still usefull 
583    //         --> the constructor is not so good ...
584    
585       gdcmWarningMacro( "Cannot open file: " << Filename.c_str());
586       delete Fp;
587       Fp = 0;
588       return 0;
589       //exit(1); // No function is allowed to leave the application instead
590                  // of warning the caller
591    }
592  
593    uint16_t zero = 0;
594    Fp->read((char*)&zero, (size_t)2);
595    if ( Fp->eof() )
596    {
597       CloseFile();
598       return 0;
599    }
600  
601    //-- ACR or DICOM with no Preamble; may start with a Shadow Group --
602    if ( 
603        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
604        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
605        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
606        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
607    {
608       std::string msg = Util::Format(
609         "ACR/DICOM starting by 0x(%04x) at the beginning of the file\n", zero);
610       // FIXME : is it a Warning message, or a Debug message?
611       gdcmWarningMacro( msg.c_str() );
612       return Fp;
613    }
614  
615    //-- DICOM --
616    Fp->seekg(126L, std::ios::cur);
617    char dicm[4]; // = {' ',' ',' ',' '};
618    Fp->read(dicm,  (size_t)4);
619    if ( Fp->eof() )
620    {
621       CloseFile();
622       return 0;
623    }
624    if ( memcmp(dicm, "DICM", 4) == 0 )
625    {
626       HasDCMPreamble = true;
627       return Fp;
628    }
629
630    // -- Neither ACR/No Preamble Dicom nor DICOMV3 file
631    CloseFile();
632    // Don't user Warning nor Error, not to polute the output
633    // while directory recursive parsing ...
634    gdcmDebugMacro( "Neither ACR/No Preamble Dicom nor DICOMV3 file: "
635                       << Filename.c_str()); 
636    return 0;
637 }
638
639 /**
640  * \brief closes the file  
641  * @return  TRUE if the close was successfull 
642  */
643 bool Document::CloseFile()
644 {
645    if ( Fp )
646    {
647       Fp->close();
648       delete Fp;
649       Fp = 0;
650    }
651    return true;
652 }
653
654 /**
655  * \brief Writes in a file all the Entries (Dicom Elements) 
656  * @param fp file pointer on an already open file (actually: Output File Stream)
657  * @param filetype Type of the File to be written 
658  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
659  */
660 void Document::WriteContent(std::ofstream *fp, FileType filetype)
661 {
662    // Skip if user wants to write an ACR-NEMA file
663
664    if ( filetype == ImplicitVR || filetype == ExplicitVR ||
665         filetype == JPEG )
666    {
667       // writing Dicom File Preamble
668       char filePreamble[128];
669       memset(filePreamble, 0, 128);
670       fp->write(filePreamble, 128);
671       fp->write("DICM", 4);
672    }
673
674    /*
675     * \todo rewrite later, if really usefull
676     *       - 'Group Length' element is optional in DICOM
677     *       - but un-updated odd groups lengthes can causes pb
678     *         (xmedcon breaker)
679     *
680     * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
681     *    UpdateGroupLength(false,filetype);
682     * if ( filetype == ACR)
683     *    UpdateGroupLength(true,ACR);
684     *
685     * --> Computing group length for groups with embeded Sequences
686     * --> was too much tricky / we were [in a hurry / too lazy]
687     * --> We don't write the element 0x0000 (group length)
688     */
689
690    ElementSet::WriteContent(fp, filetype); // This one is recursive
691 }
692
693 // -----------------------------------------
694 // Content entries 
695 /**
696  * \brief Loads (from disk) the element content 
697  *        when a string is not suitable
698  * @param group   group number of the Entry 
699  * @param elem  element number of the Entry
700  */
701 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
702 {
703    // Search the corresponding DocEntry
704    DocEntry *docEntry = GetDocEntry(group, elem);
705    if ( !docEntry )
706    {
707       gdcmWarningMacro(std::hex << group << "|" << elem 
708                        <<  "doesn't exist" );
709       return;
710    }
711    DataEntry *dataEntry = dynamic_cast<DataEntry *>(docEntry);
712    if ( !dataEntry )
713    {
714       gdcmWarningMacro(std::hex << group << "|" << elem 
715                        <<  "is NOT a DataEntry");
716       return;
717    }
718    LoadEntryBinArea(dataEntry);
719 }
720
721 /**
722  * \brief Loads (from disk) the element content 
723  *        when a string is not suitable
724  * @param entry  Entry whose binArea is going to be loaded
725  */
726 void Document::LoadEntryBinArea(DataEntry *entry) 
727 {
728    if( entry->GetBinArea() )
729       return;
730
731    bool openFile = !Fp;
732    if ( openFile )
733       OpenFile();
734
735    size_t o =(size_t)entry->GetOffset();
736    Fp->seekg(o, std::ios::beg);
737
738    size_t l = entry->GetLength();
739    uint8_t *data = new uint8_t[l];
740    if ( !data )
741    {
742       gdcmWarningMacro(  "Cannot allocate DataEntry content for : "
743                        << std::hex << entry->GetGroup() 
744                        << "|" << entry->GetElement() );
745       return;
746    }
747
748    // Read the data
749    Fp->read((char*)data, l);
750    if ( Fp->fail() || Fp->eof() )
751    {
752       delete[] data;
753       entry->SetState(DataEntry::STATE_UNREAD);
754       return;
755    }
756
757    // Swap the data content if necessary
758    uint32_t i;
759    unsigned short vrLgth = 
760                         Global::GetVR()->GetAtomicElementLength(entry->GetVR());
761
762 // FIXME : trouble expected if we read an ... OW Entry (LUT, etc ..)
763    if( entry->GetVR() == "OW" )
764       vrLgth = 1;
765
766    switch(vrLgth)
767    {
768       case 1:
769       {
770   std::cout << "Atomic lgt = 1 ; NO swap at reading" << std::endl;
771          break;
772       }     
773       case 2:
774       {
775          uint16_t *data16 = (uint16_t *)data;
776          for(i=0;i<l/vrLgth;i++)
777             data16[i] = SwapShort(data16[i]);
778          break;
779       }
780       case 4:
781       {
782          uint32_t *data32 = (uint32_t *)data;
783          for(i=0;i<l/vrLgth;i++)
784             data32[i] = SwapLong(data32[i]);
785          break;
786       }
787       case 8:
788       {
789          double *data64 = (double *)data;
790          for(i=0;i<l/vrLgth;i++)
791             data64[i] = SwapDouble(data64[i]);
792          break;
793       }
794    }
795    
796    entry->SetBinArea(data);
797
798    if ( openFile )
799       CloseFile();
800 }
801
802 /**
803  * \brief  Loads the element while preserving the current
804  *         underlying file position indicator as opposed to
805  *        LoadDocEntry that modifies it.
806  * @param entry   DocEntry whose value will be loaded. 
807  */
808 void Document::LoadDocEntrySafe(DocEntry *entry)
809 {
810    if ( Fp )
811    {
812       long PositionOnEntry = Fp->tellg();
813       LoadDocEntry(entry);
814       Fp->seekg(PositionOnEntry, std::ios::beg);
815    }
816 }
817
818 /**
819  * \brief   Compares two documents, according to \ref DicomDir rules
820  * \warning Does NOT work with ACR-NEMA files
821  * \todo    Find a trick to solve the pb (use RET fields ?)
822  * @param   document to compare with current one
823  * @return  true if 'smaller'
824  */
825 bool Document::operator<(Document &document)
826 {
827    // Patient Name
828    std::string s1 = GetEntryString(0x0010,0x0010);
829    std::string s2 = document.GetEntryString(0x0010,0x0010);
830    if (s1 < s2)
831    {
832       return true;
833    }
834    else if ( s1 > s2 )
835    {
836       return false;
837    }
838    else
839    {
840       // Patient ID
841       s1 = GetEntryString(0x0010,0x0020);
842       s2 = document.GetEntryString(0x0010,0x0020);
843       if ( s1 < s2 )
844       {
845          return true;
846       }
847       else if ( s1 > s2 )
848       {
849          return false;
850       }
851       else
852       {
853          // Study Instance UID
854          s1 = GetEntryString(0x0020,0x000d);
855          s2 = document.GetEntryString(0x0020,0x000d);
856          if ( s1 < s2 )
857          {
858             return true;
859          }
860          else if ( s1 > s2 )
861          {
862             return false;
863          }
864          else
865          {
866             // Serie Instance UID
867             s1 = GetEntryString(0x0020,0x000e);
868             s2 = document.GetEntryString(0x0020,0x000e);    
869             if ( s1 < s2 )
870             {
871                return true;
872             }
873             else if ( s1 > s2 )
874             {
875                return false;
876             }
877          }
878       }
879    }
880    return false;
881 }
882
883 //-----------------------------------------------------------------------------
884 // Protected
885 /**
886  * \brief Reads a supposed to be 16 Bits integer
887  *       (swaps it depending on processor endianness) 
888  * @return read value
889  */
890 uint16_t Document::ReadInt16()
891    throw( FormatError )
892 {
893    uint16_t g;
894    Fp->read ((char*)&g, (size_t)2);
895    if ( Fp->fail() )
896    {
897       throw FormatError( "Document::ReadInt16()", " file error." );
898    }
899    if ( Fp->eof() )
900    {
901       throw FormatError( "Document::ReadInt16()", "EOF." );
902    }
903    g = SwapShort(g); 
904    return g;
905 }
906
907 /**
908  * \brief  Reads a supposed to be 32 Bits integer
909  *        (swaps it depending on processor endianness)  
910  * @return read value
911  */
912 uint32_t Document::ReadInt32()
913    throw( FormatError )
914 {
915    uint32_t g;
916    Fp->read ((char*)&g, (size_t)4);
917    if ( Fp->fail() )
918    {
919       throw FormatError( "Document::ReadInt32()", " file error." );
920    }
921    if ( Fp->eof() )
922    {
923       throw FormatError( "Document::ReadInt32()", "EOF." );
924    }
925    g = SwapLong(g);
926    return g;
927 }
928
929 /**
930  * \brief skips bytes inside the source file 
931  * \warning NOT end user intended method !
932  * @return 
933  */
934 void Document::SkipBytes(uint32_t nBytes)
935 {
936    //FIXME don't dump the returned value
937    Fp->seekg((long)nBytes, std::ios::cur);
938 }
939
940 /**
941  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
942  */
943 int Document::ComputeGroup0002Length( ) 
944 {
945    uint16_t gr;
946    VRKey vr;
947    
948    int groupLength = 0;
949    bool found0002 = false;   
950   
951    // for each zero-level Tag in the DCM Header
952    DocEntry *entry = GetFirstEntry();
953    while( entry )
954    {
955       gr = entry->GetGroup();
956
957       if ( gr == 0x0002 )
958       {
959          found0002 = true;
960
961          if ( entry->GetElement() != 0x0000 )
962          {
963             vr = entry->GetVR();
964
965             // FIXME : group 0x0002 is *always* Explicit VR!
966             // --> Except for Implicit VR Transfer Syntax (GE Private) !!
967    
968             //if ( filetype == ExplicitVR )
969             //{
970             //if ( (vr == "OB")||(vr == "OW")||(vr == "UT")||(vr == "SQ"))
971             // (no SQ, OW, UT in group 0x0002;)
972                if ( vr == "OB" ) 
973                {
974                   // explicit VR AND (OB, OW, SQ, UT) : 4 more bytes
975                   groupLength +=  4;
976                }
977             //}
978             groupLength += 2 + 2 + 4 + entry->GetLength();   
979          }
980       }
981       else if (found0002 )
982          break;
983
984       entry = GetNextEntry();
985    }
986    return groupLength; 
987 }
988
989 //-----------------------------------------------------------------------------
990 // Private
991 /**
992  * \brief Loads all the needed Dictionaries
993  * \warning NOT end user intended method !   
994  */
995 void Document::Initialize() 
996 {
997    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
998    RefShaDict = NULL;
999    Filetype   = Unknown;
1000 }
1001
1002 /**
1003  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1004  * @param set DocEntrySet we are going to parse ('zero level' or a SQItem)
1005  * @param offset start of parsing
1006  * @param l_max  length to parse (meaningless when we are in 'delimitor mode')
1007  * @param delim_mode : whether we are in 'delimitor mode' (l=0xffffff) or not
1008  */ 
1009 void Document::ParseDES(DocEntrySet *set, long offset, 
1010                         long l_max, bool delim_mode)
1011 {
1012    DocEntry *newDocEntry;
1013    DataEntry *newDataEntry;
1014    SeqEntry *newSeqEntry;
1015    VRKey vr;
1016    bool used; // will be set to false when something wrong happens to an Entry.
1017               // (Entry will then be deleted)
1018    bool delim_mode_intern = delim_mode;
1019    bool first = true;
1020    gdcmDebugMacro( "Enter in ParseDES, delim-mode " <<  delim_mode
1021                      << " at offset " << std::hex << offset ); 
1022    while (true)
1023    {
1024       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1025       {
1026          break;
1027       }
1028
1029       newDocEntry = ReadNextDocEntry( );
1030
1031       // Uncoment this cerr line to be able to 'follow' the DocEntries
1032       // when something *very* strange happens
1033       if( Debug::GetDebugFlag() ) 
1034          std::cerr<<newDocEntry->GetKey()<<" "<<newDocEntry->GetVR()<<std::endl;
1035
1036       if ( !newDocEntry )
1037       {
1038          break;
1039       }
1040
1041        // an Item Starter found elsewhere but the first position
1042        // of a SeqEntry  means previous entry was a Sequence
1043        // but we didn't get it (private Sequence + Implicit VR)
1044        // we have to backtrack.
1045       if ( !first && newDocEntry->IsItemStarter() )
1046       { 
1047         // Debug message within the method !      
1048         newDocEntry = Backtrack(newDocEntry); 
1049       }
1050       else
1051       { 
1052          PreviousDocEntry = newDocEntry; 
1053       }
1054  
1055       used = true;
1056       newDataEntry = dynamic_cast<DataEntry*>(newDocEntry);
1057
1058       if ( newDataEntry )  
1059       {
1060          //////////////////////////// DataEntry
1061  
1062          vr = newDocEntry->GetVR();
1063
1064          if ( !set->AddEntry( newDataEntry ) )
1065          {
1066             gdcmDebugMacro( "in ParseDES : cannot add a DataEntry "
1067                                  << newDataEntry->GetKey()  
1068                                  << " (at offset : " 
1069                                  << newDataEntry->GetOffset() << " )" );
1070             used=false;
1071          }
1072          else
1073          {
1074             newDataEntry->Delete();
1075             // Load only if we can add (not a duplicate key)
1076             LoadDocEntry( newDataEntry );
1077          }
1078
1079          if ( newDataEntry->GetElement() == 0x0000 ) // if on group length
1080          {
1081             if ( newDataEntry->GetGroup()%2 != 0 )   // if Shadow Group
1082             {
1083                if ( LoadMode & LD_NOSHADOW ) // if user asked to skip shad.gr
1084                {
1085                   std::string strLgrGroup = newDataEntry->GetString();
1086                   int lgrGroup;
1087                   if ( newDataEntry->IsUnfound() )
1088                   {
1089                      lgrGroup = atoi(strLgrGroup.c_str());
1090                      Fp->seekg(lgrGroup, std::ios::cur);
1091                      //used = false;  // never used
1092                      RemoveEntry( newDocEntry );  // Remove and delete
1093                      // bcc 5.5 is right "assigned a value that's never used"
1094                      // newDocEntry = 0;
1095                      continue;
1096                   }
1097                }
1098             }
1099          }
1100
1101          bool delimitor = newDataEntry->IsItemDelimitor();
1102
1103          if ( (delimitor) || 
1104                (!delim_mode && ((long)(Fp->tellg())-offset) >= l_max) )
1105          {
1106             if ( !used )
1107                newDocEntry->Delete();
1108             break;
1109          }
1110
1111          // Just to make sure we are at the beginning of next entry.
1112          SkipToNextDocEntry(newDocEntry);
1113       }
1114       else
1115       {
1116          /////////////////////// SeqEntry :  VR = "SQ"
1117
1118          unsigned long l = newDocEntry->GetReadLength();          
1119          if ( l != 0 ) // don't mess the delim_mode for 'zero-length sequence'
1120          {
1121             if ( l == 0xffffffff )
1122             {
1123               delim_mode_intern = true;
1124             }
1125             else
1126             {
1127               delim_mode_intern = false;
1128             }
1129          }
1130
1131          if ( (LoadMode & LD_NOSHADOWSEQ) && ! delim_mode_intern )
1132          { 
1133            // User asked to skip SeQuences *only* if they belong to Shadow Group
1134             if ( newDocEntry->GetGroup()%2 != 0 )
1135             {
1136                 Fp->seekg( l, std::ios::cur);
1137                 newDocEntry->Delete();  // Delete, not in the set 
1138                 continue;  
1139             } 
1140          } 
1141          if ( (LoadMode & LD_NOSEQ) && ! delim_mode_intern ) 
1142          {
1143            // User asked to skip *any* SeQuence
1144             Fp->seekg( l, std::ios::cur);
1145             newDocEntry->Delete(); // Delete, not in the set
1146             continue;
1147          }
1148          // delay the dynamic cast as late as possible
1149          newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1150          
1151          // no other way to create the Delimitor ...
1152          newSeqEntry->SetDelimitorMode( delim_mode_intern );
1153
1154          // At the top of the hierarchy, stands a Document. When "set"
1155          // is a Document, then we are building the first depth level.
1156          // Hence the SeqEntry we are building simply has a depth
1157          // level of one:
1158         if ( set == this ) // ( dynamic_cast< Document* > ( set ) )
1159          {
1160             newSeqEntry->SetDepthLevel( 1 );
1161          }
1162          // But when "set" is already a SQItem, we are building a nested
1163          // sequence, and hence the depth level of the new SeqEntry
1164          // we are building, is one level deeper:
1165
1166          // time waste hunting
1167          else if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1168          {
1169             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1170          }
1171
1172          if ( l != 0 )
1173          {  // Don't try to parse zero-length sequences
1174
1175             gdcmDebugMacro( "Entry in ParseSQ, delim " << delim_mode_intern
1176                                << " at offset " << std::hex
1177                                << newDocEntry->GetOffset() );
1178
1179             ParseSQ( newSeqEntry, 
1180                      newDocEntry->GetOffset(),
1181                      l, delim_mode_intern);
1182
1183             gdcmDebugMacro( "Exit from ParseSQ, delim " << delim_mode_intern);
1184  
1185          }
1186          if ( !set->AddEntry( newSeqEntry ) )
1187          {
1188             gdcmWarningMacro( "in ParseDES : cannot add a SeqEntry "
1189                                 << newSeqEntry->GetKey()
1190                                 << " (at offset : " 
1191                                 << newSeqEntry->GetOffset() << " )" ); 
1192             used = false;
1193          }
1194          else
1195          {
1196             newDocEntry->Delete();
1197          }
1198  
1199          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1200          {
1201             if ( !used )
1202                newDocEntry->Delete();
1203             break;
1204          }
1205       }  // end SeqEntry : VR = "SQ"
1206
1207       if ( !used )
1208       {
1209          newDocEntry->Delete();
1210       }
1211       first = false;
1212    }                               // end While
1213    gdcmDebugMacro( "Exit from ParseDES, delim-mode " << delim_mode );
1214 }
1215
1216 /**
1217  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1218  * @return  parsed length for this level
1219  */ 
1220 void Document::ParseSQ( SeqEntry *seqEntry,
1221                         long offset, long l_max, bool delim_mode)
1222 {
1223    int SQItemNumber = 0;
1224    bool dlm_mod;
1225    long offsetStartCurrentSQItem = offset;
1226
1227    while (true)
1228    {
1229       // the first time, we read the fff0,e000 of the first SQItem
1230       DocEntry *newDocEntry = ReadNextDocEntry();
1231
1232       if ( !newDocEntry )
1233       {
1234          gdcmWarningMacro("in ParseSQ : should never get here!");
1235          break;
1236       }
1237       if ( delim_mode )
1238       {
1239          if ( newDocEntry->IsSequenceDelimitor() )
1240          {
1241             seqEntry->SetDelimitationItem( newDocEntry ); 
1242             newDocEntry->Delete();
1243             break;
1244          }
1245       }
1246       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1247       {
1248          newDocEntry->Delete();
1249          break;
1250       }
1251       // create the current SQItem
1252       SQItem *itemSQ = SQItem::New( seqEntry->GetDepthLevel() );
1253       unsigned int l = newDocEntry->GetReadLength();
1254       
1255       if ( l == 0xffffffff )
1256       {
1257          dlm_mod = true;
1258       }
1259       else
1260       {
1261          dlm_mod = false;
1262       }
1263
1264       // remove fff0,e000, created out of the SQItem
1265       Fp->seekg(offsetStartCurrentSQItem, std::ios::beg);
1266       // fill up the current SQItem, starting at the beginning of fff0,e000
1267
1268       ParseDES(itemSQ, offsetStartCurrentSQItem, l+8, dlm_mod);
1269
1270       offsetStartCurrentSQItem = Fp->tellg();
1271  
1272       seqEntry->AddSQItem( itemSQ, SQItemNumber ); 
1273       itemSQ->Delete();
1274       newDocEntry->Delete();
1275       SQItemNumber++;
1276       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1277       {
1278          break;
1279       }
1280    }
1281 }
1282
1283 /**
1284  * \brief   When a private Sequence + Implicit VR is encountered
1285  *           we cannot guess it's a Sequence till we find the first
1286  *           Item Starter. We then backtrack to do the job.
1287  * @param   docEntry Item Starter that warned us 
1288  */
1289 DocEntry *Document::Backtrack(DocEntry *docEntry)
1290 {
1291    // delete the Item Starter, built erroneously out of any Sequence
1292    // it's not yet in the HTable/chained list
1293    docEntry->Delete();
1294
1295    // Get all info we can from PreviousDocEntry
1296    uint16_t group = PreviousDocEntry->GetGroup();
1297    uint16_t elem  = PreviousDocEntry->GetElement();
1298    uint32_t lgt   = PreviousDocEntry->GetLength();
1299    long offset    = PreviousDocEntry->GetOffset();
1300
1301    gdcmDebugMacro( "Backtrack :" << std::hex << group 
1302                                    << "|" << elem
1303                                    << " at offset " << offset );
1304    RemoveEntry( PreviousDocEntry );
1305
1306    // forge the Seq Entry
1307    DocEntry *newEntry = NewSeqEntry(group, elem);
1308    newEntry->SetLength(lgt);
1309    newEntry->SetOffset(offset);
1310
1311    // Move back to the beginning of the Sequence
1312    Fp->seekg( 0, std::ios::beg);
1313    Fp->seekg(offset, std::ios::cur);
1314
1315    return newEntry;
1316 }
1317
1318 /**
1319  * \brief   Loads (or not) the element content depending if its length exceeds
1320  *          or not the value specified with Document::SetMaxSizeLoadEntry()
1321  * @param   entry Header Entry (Dicom Element) to be dealt with
1322  * @param forceLoad whether you want to force loading of 'long' elements
1323  */
1324 void Document::LoadDocEntry(DocEntry *entry, bool forceLoad)
1325 {
1326    uint16_t group  = entry->GetGroup();
1327    uint16_t elem  = entry->GetElement();
1328    const VRKey  &vr = entry->GetVR();
1329    uint32_t length = entry->GetLength();
1330
1331    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1332
1333    // A SeQuence "contains" a set of Elements.  
1334    //          (fffe e000) tells us an Element is beginning
1335    //          (fffe e00d) tells us an Element just ended
1336    //          (fffe e0dd) tells us the current SeQuence just ended
1337    //
1338    //          (fffe 0000) is an 'impossible' tag value, 
1339    //                                    found in MR-PHILIPS-16-Multi-Seq.dcm
1340    
1341    if ( (group == 0xfffe && elem != 0x0000 ) || vr == "SQ" )
1342    {
1343       // NO more value field for SQ !
1344       return;
1345    }
1346
1347    DataEntry *dataEntryPtr = dynamic_cast< DataEntry* >(entry);
1348    if( !dataEntryPtr )
1349    {
1350       return;
1351    }
1352
1353    // When the length is zero things are easy:
1354    if ( length == 0 )
1355    {
1356       dataEntryPtr->SetBinArea(NULL,true);
1357       return;
1358    }
1359
1360    // The elements whose length is bigger than the specified upper bound
1361    // are not loaded.
1362
1363    std::ostringstream s;
1364
1365    if (!forceLoad)
1366    {
1367       if (length > MaxSizeLoadEntry)
1368       {
1369          dataEntryPtr->SetBinArea(NULL,true);
1370          dataEntryPtr->SetState(DataEntry::STATE_NOTLOADED);
1371
1372          // to be sure we are at the end of the value ...
1373          Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1374                    std::ios::beg);
1375          return;
1376       }
1377    }
1378
1379    LoadEntryBinArea(dataEntryPtr); // last one, not to erase length !
1380 }
1381
1382 /**
1383  * \brief  Find the value Length of the passed Doc Entry
1384  * @param  entry Header Entry whose length of the value shall be loaded. 
1385  */
1386 void Document::FindDocEntryLength( DocEntry *entry )
1387    throw ( FormatError )
1388 {
1389    const VRKey &vr  = entry->GetVR();
1390    uint16_t length16;       
1391    
1392    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1393    {
1394       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UT" 
1395                                                            || vr == "UN" )
1396       {
1397          // The following reserved two bytes (see PS 3.5-2003, section
1398          // "7.1.2 Data element structure with explicit vr", p 27) must be
1399          // skipped before proceeding on reading the length on 4 bytes.
1400          Fp->seekg( 2L, std::ios::cur);
1401          uint32_t length32 = ReadInt32();
1402
1403          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1404          {
1405             uint32_t lengthOB;
1406             try 
1407             {
1408                lengthOB = FindDocEntryLengthOBOrOW();
1409             }
1410             catch ( FormatUnexpected )
1411             {
1412                // Computing the length failed (this happens with broken
1413                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1414                // chance to get the pixels by deciding the element goes
1415                // until the end of the file. Hence we artificially fix the
1416                // the length and proceed.
1417                gdcmWarningMacro( " Computing the length failed for " << 
1418                                    entry->GetKey() <<" in " <<GetFileName());
1419
1420                long currentPosition = Fp->tellg();
1421                Fp->seekg(0L,std::ios::end);
1422
1423                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1424                Fp->seekg(currentPosition, std::ios::beg);
1425
1426                entry->SetReadLength(lengthUntilEOF);
1427                entry->SetLength(lengthUntilEOF);
1428                return;
1429             }
1430             entry->SetReadLength(lengthOB);
1431             entry->SetLength(lengthOB);
1432             return;
1433          }
1434          FixDocEntryFoundLength(entry, length32); 
1435          return;
1436       }
1437
1438       // Length is encoded on 2 bytes.
1439       length16 = ReadInt16();
1440   
1441       // 0xffff means that we deal with 'No Length' Sequence 
1442       //        or 'No Length' SQItem
1443       if ( length16 == 0xffff) 
1444       {           
1445          length16 = 0;
1446       }
1447       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1448       return;
1449    }
1450    else
1451    {
1452       // Either implicit VR or a non DICOM conformal (see note below) explicit
1453       // VR that ommited the VR of (at least) this element. Farts happen.
1454       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1455       // on Data elements "Implicit and Explicit VR Data Elements shall
1456       // not coexist in a Data Set and Data Sets nested within it".]
1457       // Length is on 4 bytes.
1458
1459      // Well ... group 0002 is always coded in 'Explicit VR Litle Endian'
1460      // even if Transfer Syntax is 'Implicit VR ...'
1461      // --> Except for 'Implicit VR Big Endian Transfer Syntax GE Private' 
1462       
1463       FixDocEntryFoundLength( entry, ReadInt32() );
1464       return;
1465    }
1466 }
1467
1468 /**
1469  * \brief  Find the Length till the next sequence delimiter
1470  * \warning NOT end user intended method !
1471  * @return 
1472  */
1473 uint32_t Document::FindDocEntryLengthOBOrOW()
1474    throw( FormatUnexpected )
1475 {
1476    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1477    long positionOnEntry = Fp->tellg();
1478    bool foundSequenceDelimiter = false;
1479    uint32_t totalLength = 0;
1480
1481    while ( !foundSequenceDelimiter )
1482    {
1483       uint16_t group;
1484       uint16_t elem;
1485       try
1486       {
1487          group = ReadInt16();
1488          elem  = ReadInt16();   
1489       }
1490       catch ( FormatError )
1491       {
1492          throw FormatError("Unexpected end of file encountered during ",
1493                            "Document::FindDocEntryLengthOBOrOW()");
1494       }
1495       // We have to decount the group and element we just read
1496       totalLength += 4;     
1497       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
1498       {
1499          long filePosition = Fp->tellg();
1500          gdcmWarningMacro( 
1501               "Neither an Item tag nor a Sequence delimiter tag on :" 
1502            << std::hex << group << " , " << elem 
1503            << ") -before- position x(" << filePosition << ")" );
1504   
1505          Fp->seekg(positionOnEntry, std::ios::beg);
1506          throw FormatUnexpected( 
1507                "Neither an Item tag nor a Sequence delimiter tag.");
1508       }
1509       if ( elem == 0xe0dd )
1510       {
1511          foundSequenceDelimiter = true;
1512       }
1513       uint32_t itemLength = ReadInt32();
1514       // We add 4 bytes since we just read the ItemLength with ReadInt32
1515       totalLength += itemLength + 4;
1516       SkipBytes(itemLength);
1517       
1518       if ( foundSequenceDelimiter )
1519       {
1520          break;
1521       }
1522    }
1523    Fp->seekg( positionOnEntry, std::ios::beg);
1524    return totalLength;
1525 }
1526
1527 /**
1528  * \brief     Find the Value Representation of the current Dicom Element.
1529  * @return    Value Representation of the current Entry
1530  */
1531 VRKey Document::FindDocEntryVR()
1532 {
1533    if ( Filetype != ExplicitVR )
1534       return GDCM_VRUNKNOWN;
1535
1536    long positionOnEntry = Fp->tellg();
1537    // Warning: we believe this is explicit VR (Value Representation) because
1538    // we used a heuristic that found "UL" in the first tag and/or
1539    // 'Transfer Syntax' told us it is.
1540    // Alas this doesn't guarantee that all the tags will be in explicit VR. 
1541    // In some cases one finds implicit VR tags mixed within an explicit VR file.
1542    // Hence we make sure the present tag is in explicit VR and try to fix things
1543    // if it happens not to be the case.
1544
1545    VRKey vr;
1546    Fp->read(&(vr[0]),(size_t)2);
1547
1548    if ( !CheckDocEntryVR(vr) )
1549    {
1550       gdcmWarningMacro( "Unknown VR " << std::hex << "0x(" 
1551                         << (unsigned int)vr[0] << "|" << (unsigned int)vr[1] 
1552                         << ") at offset :" << positionOnEntry );
1553       Fp->seekg(positionOnEntry, std::ios::beg);
1554       return GDCM_VRUNKNOWN;
1555    }
1556    return vr;
1557 }
1558
1559 /**
1560  * \brief     Check the correspondance between the VR of the header entry
1561  *            and the taken VR. If they are different, the header entry is 
1562  *            updated with the new VR.
1563  * @param     vr    Dicom Value Representation
1564  * @return    false if the VR is incorrect or if the VR isn't referenced
1565  *            otherwise, it returns true
1566 */
1567 bool Document::CheckDocEntryVR(const VRKey &vr)
1568 {
1569    return Global::GetVR()->IsValidVR(vr);
1570 }
1571
1572 /**
1573  * \brief   Skip a given Header Entry 
1574  * \warning NOT end user intended method !
1575  * @param   entry entry to skip
1576  */
1577 void Document::SkipDocEntry(DocEntry *entry) 
1578 {
1579    SkipBytes(entry->GetLength());
1580 }
1581
1582 /**
1583  * \brief   Skips to the beginning of the next Header Entry 
1584  * \warning NOT end user intended method !
1585  * @param   currentDocEntry entry to skip
1586  */
1587 void Document::SkipToNextDocEntry(DocEntry *currentDocEntry) 
1588 {
1589    int l = currentDocEntry->GetReadLength();
1590    if ( l == -1 ) // length = 0xffff shouldn't appear here ...
1591                   // ... but PMS imagers happen !
1592       return;
1593    Fp->seekg((long)(currentDocEntry->GetOffset()), std::ios::beg);
1594    if (currentDocEntry->GetGroup() != 0xfffe)  // for fffe pb
1595    {
1596       Fp->seekg( (long)(currentDocEntry->GetReadLength()),std::ios::cur);
1597    }
1598 }
1599
1600 /**
1601  * \brief   When the length of an element value is obviously wrong (because
1602  *          the parser went Jabberwocky) one can hope improving things by
1603  *          applying some heuristics.
1604  * @param   entry entry to check
1605  * @param   foundLength first assumption about length    
1606  */
1607 void Document::FixDocEntryFoundLength(DocEntry *entry,
1608                                       uint32_t foundLength)
1609 {
1610    entry->SetReadLength( foundLength );// will be updated only if a bug is found
1611    if ( foundLength == 0xffffffff)
1612    {
1613       foundLength = 0;
1614    }
1615    
1616    uint16_t gr   = entry->GetGroup();
1617    uint16_t elem = entry->GetElement(); 
1618      
1619    if ( foundLength % 2)
1620    {
1621       gdcmWarningMacro( "Warning : Tag with uneven length " << foundLength
1622         <<  " in x(" << std::hex << gr << "," << elem <<")");
1623    }
1624       
1625    //////// Fix for some naughty General Electric images.
1626    // Allthough not recent many such GE corrupted images are still present
1627    // on Creatis hard disks. Hence this fix shall remain when such images
1628    // are no longer in use (we are talking a few years, here)...
1629    // Note: XMedCon probably uses such a trick since it is able to read
1630    //       those pesky GE images ...
1631    if ( foundLength == 13)
1632    {
1633       // Only happens for this length !
1634       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1635       {
1636          foundLength = 10;
1637          entry->SetReadLength(10); // a bug is to be fixed !?
1638       }
1639    }
1640
1641    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1642    // Occurence of such images is quite low (unless one leaves close to a
1643    // 'Leonardo' source. Hence, one might consider commenting out the
1644    // following fix on efficiency reasons.
1645    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1646    {
1647       foundLength = 4;
1648       entry->SetReadLength(4); // a bug is to be fixed !
1649    } 
1650  
1651    else if ( entry->GetVR() == "SQ" )
1652    {
1653       foundLength = 0;      // ReadLength is unchanged 
1654    } 
1655     
1656    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1657    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1658    // taken into account.
1659    else if ( gr == 0xfffe )
1660    {    
1661      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1662      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1663      // causes extra troubles...
1664      if ( entry->GetElement() != 0x0000 )
1665      {
1666         foundLength = 0;
1667      }
1668      else
1669      {
1670         foundLength=12; // to skip the mess that follows this bugged Tag !
1671      }
1672    }                
1673    entry->SetLength(foundLength);
1674 }
1675
1676 /**
1677  * \brief   Apply some heuristics to predict whether the considered 
1678  *          element value contains/represents an integer or not.
1679  * @param   entry The element value on which to apply the predicate.
1680  * @return  The result of the heuristical predicate.
1681  */
1682 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1683 {
1684    uint16_t elem         = entry->GetElement();
1685    uint16_t group        = entry->GetGroup();
1686    const VRKey &vr       = entry->GetVR();
1687    uint32_t length       = entry->GetLength();
1688
1689    // When we have some semantics on the element we just read, and if we
1690    // a priori know we are dealing with an integer, then we shall be
1691    // able to swap it's element value properly.
1692    if ( elem == 0 )  // This is the group length of the group
1693    {  
1694       if ( length == 4 )
1695       {
1696          return true;
1697       }
1698       else 
1699       {
1700          // Although this should never happen, still some images have a
1701          // corrupted group length [e.g. have a glance at offset x(8336) of
1702          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm.
1703          // Since for dicom compliant and well behaved headers, the present
1704          // test is useless (and might even look a bit paranoid), when we
1705          // encounter such an ill-formed image, we simply display a warning
1706          // message and proceed on parsing (while crossing fingers).
1707          long filePosition = Fp->tellg();
1708          gdcmWarningMacro( "Erroneous Group Length element length  on : (" 
1709            << std::hex << group << " , " << elem
1710            << ") -before- position x(" << filePosition << ")"
1711            << "lgt : " << length );
1712       }
1713    }
1714
1715    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
1716    {
1717       return true;
1718    }   
1719    return false;
1720 }
1721
1722 /**
1723  * \brief   Discover what the swap code is (among little endian, big endian,
1724  *          bad little endian, bad big endian).
1725  *          sw is set
1726  * @return false when we are absolutely sure 
1727  *               it's neither ACR-NEMA nor DICOM
1728  *         true  when we hope ours assuptions are OK
1729  */
1730 bool Document::CheckSwap()
1731 {   
1732    uint32_t  s32;
1733    uint16_t  s16;
1734        
1735    char deb[256];
1736     
1737    // First, compare HostByteOrder and NetworkByteOrder in order to
1738    // determine if we shall need to swap bytes (i.e. the Endian type).
1739    bool net2host = Util::IsCurrentProcessorBigEndian();
1740          
1741    // The easiest case is the one of a 'true' DICOM header, we just have
1742    // to look for the string "DICM" inside the file preamble.
1743    Fp->read(deb, 256);
1744    
1745    char *entCur = deb + 128;
1746    if ( memcmp(entCur, "DICM", (size_t)4) == 0 )
1747    {
1748       gdcmDebugMacro( "Looks like DICOM Version3 (preamble + DCM)" );
1749       
1750       // Group 0002 should always be VR, and the first element 0000
1751       // Let's be carefull (so many wrong headers ...)
1752       // and determine the value representation (VR) : 
1753       // Let's skip to the first element (0002,0000) and check there if we find
1754       // "UL"  - or "OB" if the 1st one is (0002,0001) -,
1755       // in which case we (almost) know it is explicit VR.
1756       // WARNING: if it happens to be implicit VR then what we will read
1757       // is the length of the group. If this ascii representation of this
1758       // length happens to be "UL" then we shall believe it is explicit VR.
1759       // We need to skip :
1760       // * the 128 bytes of File Preamble (often padded with zeroes),
1761       // * the 4 bytes of "DICM" string,
1762       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
1763       // i.e. a total of  136 bytes.
1764       entCur = deb + 136;
1765      
1766       // group 0x0002 *is always* Explicit VR Sometimes ,
1767       // even if elem 0002,0010 (Transfer Syntax) tells us the file is
1768       // *Implicit* VR  (see former 'gdcmData/icone.dcm')
1769       
1770       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1771            memcmp(entCur, "OB", (size_t)2) == 0 ||
1772            memcmp(entCur, "UI", (size_t)2) == 0 ||
1773            memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
1774                                                    // when Write DCM *adds*
1775       // FIXME
1776       // Use Document::dicom_vr to test all the possibilities
1777       // instead of just checking for UL, OB and UI !? group 0000 
1778       {
1779          Filetype = ExplicitVR;
1780          gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1781       } 
1782       else 
1783       {
1784          Filetype = ImplicitVR;
1785          gdcmWarningMacro( "Group 0002 :Not an explicit Value Representation;"
1786                         << "Looks like a bugged Header!");
1787       }
1788       
1789       if ( net2host )
1790       {
1791          SwapCode = 4321;
1792          gdcmDebugMacro( "HostByteOrder != NetworkByteOrder, SwapCode = 4321");
1793       }
1794       else 
1795       {
1796          SwapCode = 1234;
1797          gdcmDebugMacro( "HostByteOrder = NetworkByteOrder, SwapCode = 1234");
1798       }
1799       
1800       // Position the file position indicator at first tag 
1801       // (i.e. after the file preamble and the "DICM" string).
1802
1803       Fp->seekg(0, std::ios::beg); // FIXME : Is it usefull?
1804
1805       Fp->seekg ( 132L, std::ios::beg);
1806       return true;
1807    } // ------------------------------- End of DicomV3 ----------------
1808
1809    // Alas, this is not a DicomV3 file and whatever happens there is no file
1810    // preamble. We can reset the file position indicator to where the data
1811    // is (i.e. the beginning of the file).
1812
1813    gdcmWarningMacro( "Not a Kosher DICOM Version3 file (no preamble)");
1814
1815    Fp->seekg(0, std::ios::beg);
1816
1817    // Let's check 'No Preamble Dicom File' :
1818    // Should start with group 0x0002
1819    // and be Explicit Value Representation
1820
1821    s16 = *((uint16_t *)(deb));
1822    SwapCode = 0;     
1823    switch ( s16 )
1824    {
1825       case 0x0002 :
1826          SwapCode = 1234;
1827          entCur = deb + 4;
1828          break;
1829       case 0x0200 :
1830          SwapCode = 4321;
1831          entCur = deb + 6;
1832     } 
1833
1834    if ( SwapCode != 0 )
1835    {
1836       if ( memcmp(entCur, "UL", (size_t)2) == 0 ||
1837            memcmp(entCur, "OB", (size_t)2) == 0 ||
1838            memcmp(entCur, "UI", (size_t)2) == 0 ||
1839            memcmp(entCur, "SH", (size_t)2) == 0 ||
1840            memcmp(entCur, "AE", (size_t)2) == 0 ||
1841            memcmp(entCur, "OB", (size_t)2) == 0 )
1842          {
1843             Filetype = ExplicitVR;
1844             gdcmDebugMacro( "Group 0002 : Explicit Value Representation");
1845             return true;
1846           }
1847     }
1848 // ------------------------------- End of 'No Preamble' DicomV3 -------------
1849
1850    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
1851    // By clean we mean that the length of the first group is written down.
1852    // If this is the case and since the length of the first group HAS to be
1853    // four (bytes), then determining the proper swap code is straightforward.
1854
1855    entCur = deb + 4;
1856    // We assume the array of char we are considering contains the binary
1857    // representation of a 32 bits integer. Hence the following dirty
1858    // trick :
1859    s32 = *((uint32_t *)(entCur));
1860    switch( s32 )
1861    {
1862       case 0x00040000 :
1863          SwapCode = 3412;
1864          Filetype = ACR;
1865          return true;
1866       case 0x04000000 :
1867          SwapCode = 4321;
1868          Filetype = ACR;
1869          return true;
1870       case 0x00000400 :
1871          SwapCode = 2143;
1872          Filetype = ACR;
1873          return true;
1874       case 0x00000004 :
1875          SwapCode = 1234;
1876          Filetype = ACR;
1877          return true;
1878       default :
1879          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
1880          // It is time for despaired wild guesses. 
1881          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
1882          //  i.e. the 'group length' element is not present :     
1883          
1884          //  check the supposed-to-be 'group number'
1885          //  in ( 0x0001 .. 0x0008 )
1886          //  to determine ' SwapCode' value .
1887          //  Only 0 or 4321 will be possible 
1888          //  (no oportunity to check for the formerly well known
1889          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
1890          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc-3, 4, ..., 8-)
1891          //  the file IS NOT ACR-NEMA nor DICOM V3
1892          //  Find a trick to tell it the caller...
1893       
1894          s16 = *((uint16_t *)(deb));
1895       
1896          switch ( s16 )
1897          {
1898             case 0x0001 :
1899             case 0x0002 :
1900             case 0x0003 :
1901             case 0x0004 :
1902             case 0x0005 :
1903             case 0x0006 :
1904             case 0x0007 :
1905             case 0x0008 :
1906                SwapCode = 1234;
1907                Filetype = ACR;
1908                return true;
1909             case 0x0100 :
1910             case 0x0200 :
1911             case 0x0300 :
1912             case 0x0400 :
1913             case 0x0500 :
1914             case 0x0600 :
1915             case 0x0700 :
1916             case 0x0800 :
1917                SwapCode = 4321;
1918                Filetype = ACR;
1919                return true;
1920             default :
1921                gdcmWarningMacro("ACR/NEMA unfound swap info (Hopeless !)");
1922                Filetype = Unknown;
1923                return false;
1924          }
1925    }
1926 }
1927
1928 /**
1929  * \brief Change the Byte Swap code. 
1930  */
1931 void Document::SwitchByteSwapCode() 
1932 {
1933    gdcmDebugMacro( "Switching Byte Swap code from "<< SwapCode
1934                      << " at: 0x" << std::hex << Fp->tellg() );
1935    if ( SwapCode == 1234 ) 
1936    {
1937       SwapCode = 4321;
1938    }
1939    else if ( SwapCode == 4321 ) 
1940    {
1941       SwapCode = 1234;
1942    }
1943    else if ( SwapCode == 3412 ) 
1944    {
1945       SwapCode = 2143;
1946    }
1947    else if ( SwapCode == 2143 )
1948    {
1949       SwapCode = 3412;
1950    }
1951    gdcmDebugMacro( " Into: "<< SwapCode );
1952 }
1953
1954 /**
1955  * \brief  during parsing, Header Elements too long are not loaded in memory
1956  * @param newSize new size
1957  */
1958 void Document::SetMaxSizeLoadEntry(long newSize) 
1959 {
1960    if ( newSize < 0 )
1961    {
1962       return;
1963    }
1964    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
1965    {
1966       MaxSizeLoadEntry = 0xffffffff;
1967       return;
1968    }
1969    MaxSizeLoadEntry = newSize;
1970 }
1971
1972 /**
1973  * \brief   Read the next tag WITHOUT loading it's value
1974  *          (read the 'Group Number', the 'Element Number',
1975  *          gets the Dict Entry
1976  *          gets the VR, gets the length, gets the offset value)
1977  * @return  On succes : the newly created DocEntry, NULL on failure.      
1978  */
1979 DocEntry *Document::ReadNextDocEntry()
1980 {
1981    uint16_t group;
1982    uint16_t elem;
1983
1984    try
1985    {
1986       group = ReadInt16();
1987       elem  = ReadInt16();
1988    }
1989    catch ( FormatError )
1990    {
1991       // We reached the EOF (or an error occured) therefore 
1992       // header parsing has to be considered as finished.
1993       return 0;
1994    }
1995
1996    // Sometimes file contains groups of tags with reversed endianess.
1997    HandleBrokenEndian(group, elem);
1998
1999    // In 'true DICOM' files Group 0002 is always little endian
2000    if ( HasDCMPreamble )
2001       HandleOutOfGroup0002(group, elem);
2002  
2003    VRKey vr = FindDocEntryVR();
2004    
2005    VRKey realVR = vr;
2006
2007    if ( vr == GDCM_VRUNKNOWN )
2008    {
2009       if ( elem == 0x0000 ) // Group Length
2010       {
2011          realVR = "UL";     // must be UL
2012       }
2013       else if (group%2 == 1 &&  (elem >= 0x0010 && elem <=0x00ff ))
2014       {  
2015       // DICOM PS 3-5 7.8.1 a) states that those 
2016       // (gggg-0010->00FF where gggg is odd) attributes have to be LO
2017          realVR = "LO";
2018       }
2019       else
2020       {
2021          DictEntry *dictEntry = GetDictEntry(group,elem);
2022          if ( dictEntry )
2023          {
2024             realVR = dictEntry->GetVR();
2025             dictEntry->Unregister();
2026          }
2027       }
2028    }
2029   // gdcmDebugMacro( "Found VR: " << vr << " / Real VR: " << realVR );
2030
2031    DocEntry *newEntry;
2032    if ( Global::GetVR()->IsVROfSequence(realVR) )
2033       newEntry = NewSeqEntry(group, elem);
2034    else 
2035    {
2036       newEntry = NewDataEntry(group, elem, realVR);
2037       static_cast<DataEntry *>(newEntry)->SetState(DataEntry::STATE_NOTLOADED);
2038    }
2039
2040    if ( vr == GDCM_VRUNKNOWN )
2041    {
2042       if ( Filetype == ExplicitVR )
2043       {
2044          // We thought this was explicit VR, but we end up with an
2045          // implicit VR tag. Let's backtrack.
2046          if ( newEntry->GetGroup() != 0xfffe )
2047          { 
2048             std::string msg;
2049             int offset = Fp->tellg();
2050             msg = Util::Format(
2051                         "Entry (%04x,%04x) at x(%x) should be Explicit VR\n", 
2052                         newEntry->GetGroup(), newEntry->GetElement(), offset );
2053             gdcmWarningMacro( msg.c_str() );
2054           }
2055       }
2056       newEntry->SetImplicitVR();
2057    }
2058
2059    try
2060    {
2061       FindDocEntryLength(newEntry);
2062    }
2063    catch ( FormatError )
2064    {
2065       // Call it quits
2066       newEntry->Delete();
2067       return 0;
2068    }
2069
2070    newEntry->SetOffset(Fp->tellg());  
2071    
2072    return newEntry;
2073 }
2074
2075 /**
2076  * \brief   Handle broken private tag from Philips NTSCAN
2077  *          where the endianess is being switched to BigEndian 
2078  *          for no apparent reason
2079  * @return  no return
2080  */
2081 void Document::HandleBrokenEndian(uint16_t &group, uint16_t &elem)
2082 {
2083    // Endian reversion. 
2084    // Some files contain groups of tags with reversed endianess.
2085    static int reversedEndian = 0;
2086    // try to fix endian switching in the middle of headers
2087    if ((group == 0xfeff) && (elem == 0x00e0))
2088    {
2089      // start endian swap mark for group found
2090      reversedEndian++;
2091      SwitchByteSwapCode();
2092      // fix the tag
2093      group = 0xfffe;
2094      elem  = 0xe000;
2095    } 
2096    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2097    {
2098      // end of reversed endian group
2099      reversedEndian--;
2100      SwitchByteSwapCode();
2101    }
2102    else if (group == 0xfeff && elem == 0xdde0) 
2103    {
2104      // reversed Sequence Terminator found
2105      // probabely a bug in the header !
2106      // Do what you want, it breaks !
2107      //reversedEndian--;
2108      //SwitchByteSwapCode();
2109      gdcmWarningMacro( "Should never get here! reversed Sequence Terminator!" );
2110      // fix the tag
2111       group = 0xfffe;
2112       elem  = 0xe0dd;  
2113    }
2114    else if (group == 0xfffe && elem == 0xe0dd) 
2115    {
2116       gdcmDebugMacro( "Straight Sequence Terminator." );  
2117    }
2118 }
2119
2120 /**
2121  * \brief   Group 0002 is always coded Little Endian
2122  *          whatever Transfer Syntax is
2123  * @return  no return
2124  */
2125 void Document::HandleOutOfGroup0002(uint16_t &group, uint16_t &elem)
2126 {
2127    // Endian reversion. 
2128    // Some files contain groups of tags with reversed endianess.
2129    if ( !Group0002Parsed && group != 0x0002)
2130    {
2131       Group0002Parsed = true;
2132       // we just came out of group 0002
2133       // if Transfer Syntax is Big Endian we have to change CheckSwap
2134
2135       std::string ts = GetTransferSyntax();
2136       if ( ts == GDCM_UNKNOWN )
2137       {
2138          gdcmDebugMacro("True DICOM File, with NO Transfer Syntax (?!) " );
2139          return;      
2140       }
2141       if ( !Global::GetTS()->IsTransferSyntax(ts) )
2142       {
2143          gdcmWarningMacro("True DICOM File, with illegal Transfer Syntax: [" 
2144                           << ts << "]");
2145          return;
2146       }
2147
2148       // Group 0002 is always 'Explicit ...' 
2149       // even when Transfer Syntax says 'Implicit ..." 
2150
2151       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == 
2152                                                     TS::ImplicitVRLittleEndian )
2153       {
2154          Filetype = ImplicitVR;
2155       }
2156        
2157       // FIXME Strangely, this works with 
2158       //'Implicit VR BigEndian Transfer Syntax (GE Private)
2159       //
2160       // --> Probabely normal, since we considered we never have 
2161       // to trust manufacturers.
2162       // (we find very often 'Implicit VR' tag, 
2163       // even when Transfer Syntax tells us it's Explicit ...
2164       if ( Global::GetTS()->GetSpecialTransferSyntax(ts) == 
2165                                                        TS::ExplicitVRBigEndian )
2166       {
2167          gdcmDebugMacro("Transfer Syntax Name = [" 
2168                         << GetTransferSyntaxName() << "]" );
2169          SwitchByteSwapCode();
2170          group = SwapShort(group);
2171          elem  = SwapShort(elem);
2172       }
2173    }
2174 }
2175
2176 //-----------------------------------------------------------------------------
2177 // Print
2178
2179 //-----------------------------------------------------------------------------
2180 } // end namespace gdcm