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