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