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