]> Creatis software - gdcm.git/blob - src/gdcmDocument.cxx
Add some verbosity
[gdcm.git] / src / gdcmDocument.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmDocument.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/01/10 17:09:49 $
7   Version:   $Revision: 1.170 $
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 "gdcmException.h"
28 #include "gdcmDictSet.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
31 #include "gdcmDocEntrySet.h"
32 #include "gdcmSQItem.h"
33
34 #include <vector>
35 #include <iomanip>
36
37 // For nthos:
38 #if defined(_MSC_VER) || defined(__BORLANDC__)
39    #include <winsock.h>
40 #else
41    #include <netinet/in.h>
42 #endif
43
44 namespace gdcm 
45 {
46 //-----------------------------------------------------------------------------
47 static const char *TransferSyntaxStrings[] =  {
48   // Implicit VR Little Endian
49   "1.2.840.10008.1.2",
50   // Implicit VR Big Endian DLX (G.E Private)
51   "1.2.840.113619.5.2",
52   // Explicit VR Little Endian
53   "1.2.840.10008.1.2.1",
54   // Deflated Explicit VR Little Endian
55   "1.2.840.10008.1.2.1.99",
56   // Explicit VR Big Endian
57   "1.2.840.10008.1.2.2",
58   // JPEG Baseline (Process 1)
59   "1.2.840.10008.1.2.4.50",
60   // JPEG Extended (Process 2 & 4)
61   "1.2.840.10008.1.2.4.51",
62   // JPEG Extended (Process 3 & 5)
63   "1.2.840.10008.1.2.4.52",
64   // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
65   "1.2.840.10008.1.2.4.53",
66   // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
67   "1.2.840.10008.1.2.4.55",
68   // JPEG Lossless, Non-Hierarchical (Process 14)
69   "1.2.840.10008.1.2.4.57",
70   // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14, [Selection Value 1])
71   "1.2.840.10008.1.2.4.70",
72   // JPEG 2000 Lossless
73   "1.2.840.10008.1.2.4.90",
74   // JPEG 2000
75   "1.2.840.10008.1.2.4.91",
76   // RLE Lossless
77   "1.2.840.10008.1.2.5",
78   // Unknown
79   "Unknown Transfer Syntax"
80 };
81
82 //-----------------------------------------------------------------------------
83 // Refer to Document::CheckSwap()
84 //const unsigned int Document::HEADER_LENGTH_TO_READ = 256;
85
86 // Refer to Document::SetMaxSizeLoadEntry()
87 const unsigned int Document::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
88 const unsigned int Document::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
89
90 //-----------------------------------------------------------------------------
91 // Constructor / Destructor
92
93 /**
94  * \brief   constructor  
95  * @param   filename file to be opened for parsing
96  */
97 Document::Document( std::string const &filename ) : ElementSet(-1)
98 {
99    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE); 
100    Filename = filename;
101    Initialise();
102
103    Fp = 0;
104    if ( !OpenFile() )
105    {
106       return;
107    }
108
109    gdcmVerboseMacro( "Starting parsing of file: " << Filename.c_str());
110    Fp->seekg( 0,  std::ios::beg);
111    
112    Fp->seekg(0,  std::ios::end);
113    long lgt = Fp->tellg();
114            
115    Fp->seekg( 0,  std::ios::beg);
116    CheckSwap();
117    long beg = Fp->tellg();
118    lgt -= beg;
119    
120    ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
121
122    Fp->seekg( 0,  std::ios::beg);
123    
124    // Load 'non string' values
125       
126    std::string PhotometricInterpretation = GetEntry(0x0028,0x0004);   
127    if( PhotometricInterpretation == "PALETTE COLOR " )
128    {
129       LoadEntryBinArea(0x0028,0x1200);  // gray LUT   
130       /// FIXME FIXME FIXME
131       /// The tags refered by the three following lines used to be CORRECTLY
132       /// defined as having an US Value Representation in the public
133       /// dictionnary. BUT the semantics implied by the three following
134       /// lines state that the corresponding tag contents are in fact
135       /// the ones of a BinEntry.
136       /// In order to fix things "Quick and Dirty" the dictionnary was
137       /// altered on PURPOUS but now contains a WRONG value.
138       /// In order to fix things and restore the dictionary to its
139       /// correct value, one needs to decided of the semantics by deciding
140       /// wether the following tags are either:
141       /// - multivaluated US, and hence loaded as ValEntry, but afterwards
142       ///   also used as BinEntry, which requires the proper conversion,
143       /// - OW, and hence loaded as BinEntry, but afterwards also used
144       ///   as ValEntry, which requires the proper conversion.
145       LoadEntryBinArea(0x0028,0x1201);  // R    LUT
146       LoadEntryBinArea(0x0028,0x1202);  // G    LUT
147       LoadEntryBinArea(0x0028,0x1203);  // B    LUT
148       
149       // Segmented Red   Palette Color LUT Data
150       LoadEntryBinArea(0x0028,0x1221);
151       // Segmented Green Palette Color LUT Data
152       LoadEntryBinArea(0x0028,0x1222);
153       // Segmented Blue  Palette Color LUT Data
154       LoadEntryBinArea(0x0028,0x1223);
155    } 
156    //FIXME later : how to use it?
157    LoadEntryBinArea(0x0028,0x3006);  //LUT Data (CTX dependent) 
158
159    CloseFile(); 
160   
161    // --------------------------------------------------------------
162    // Specific code to allow gdcm to read ACR-LibIDO formated images
163    // Note: ACR-LibIDO is an extension of the ACR standard that was
164    //       used at CREATIS. For the time being (say a couple years)
165    //       we keep this kludge to allow a smooth move to gdcm for
166    //       CREATIS developpers (sorry folks).
167    //
168    // if recognition code tells us we deal with a LibIDO image
169    // we switch lineNumber and columnNumber
170    //
171    std::string RecCode;
172    RecCode = GetEntry(0x0008, 0x0010); // recognition code
173    if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
174        RecCode == "CANRME_AILIBOD1_1." )  // for brain-damaged softwares
175                                           // with "little-endian strings"
176    {
177          Filetype = ACR_LIBIDO; 
178          std::string rows    = GetEntry(0x0028, 0x0010);
179          std::string columns = GetEntry(0x0028, 0x0011);
180          SetEntry(columns, 0x0028, 0x0010);
181          SetEntry(rows   , 0x0028, 0x0011);
182    }
183    // ----------------- End of ACR-LibIDO kludge ------------------ 
184 }
185
186 /**
187  * \brief This default constructor doesn't parse the file. You should
188  *        then invoke \ref Document::SetFileName and then the parsing.
189  */
190 Document::Document() : ElementSet(-1)
191 {
192    Fp = 0;
193
194    SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
195    Initialise();
196    SwapCode = 0;
197    Filetype = ExplicitVR;
198 }
199
200 /**
201  * \brief   Canonical destructor.
202  */
203 Document::~Document ()
204 {
205    RefPubDict = NULL;
206    RefShaDict = NULL;
207
208    delete RLEInfo;
209    delete JPEGInfo;
210 }
211
212 //-----------------------------------------------------------------------------
213 // Print
214
215 /**
216   * \brief   Prints The Dict Entries of THE public Dicom Dictionary
217   * @return
218   */  
219 void Document::PrintPubDict(std::ostream &os)
220 {
221    RefPubDict->SetPrintLevel(PrintLevel);
222    RefPubDict->Print(os);
223 }
224
225 /**
226   * \brief   Prints The Dict Entries of THE shadow Dicom Dictionary
227   * @return
228   */
229 void Document::PrintShaDict(std::ostream &os)
230 {
231    RefShaDict->SetPrintLevel(PrintLevel);
232    RefShaDict->Print(os);
233 }
234
235 //-----------------------------------------------------------------------------
236 // Public
237 /**
238  * \brief   Get the public dictionary used
239  */
240 Dict *Document::GetPubDict()
241 {
242    return RefPubDict;
243 }
244
245 /**
246  * \brief   Get the shadow dictionary used
247  */
248 Dict *Document::GetShaDict()
249 {
250    return RefShaDict;
251 }
252
253 /**
254  * \brief   Set the shadow dictionary used
255  * @param   dict dictionary to use in shadow
256  */
257 bool Document::SetShaDict(Dict *dict)
258 {
259    RefShaDict = dict;
260    return !RefShaDict;
261 }
262
263 /**
264  * \brief   Set the shadow dictionary used
265  * @param   dictName name of the dictionary to use in shadow
266  */
267 bool Document::SetShaDict(DictKey const &dictName)
268 {
269    RefShaDict = Global::GetDicts()->GetDict(dictName);
270    return !RefShaDict;
271 }
272
273 /**
274  * \brief  This predicate, based on hopefully reasonable heuristics,
275  *         decides whether or not the current Document was properly parsed
276  *         and contains the mandatory information for being considered as
277  *         a well formed and usable Dicom/Acr File.
278  * @return true when Document is the one of a reasonable Dicom/Acr file,
279  *         false otherwise. 
280  */
281 bool Document::IsReadable()
282 {
283    if( Filetype == Unknown)
284    {
285       gdcmVerboseMacro( "Wrong filetype");
286       return false;
287    }
288
289    if( TagHT.empty() )
290    {
291       gdcmVerboseMacro( "No tags in internal hash table.");
292       return false;
293    }
294
295    return true;
296 }
297
298 /**
299  * \brief   Accessor to the Transfer Syntax (when present) of the
300  *          current document (it internally handles reading the
301  *          value from disk when only parsing occured).
302  * @return  The encountered Transfer Syntax of the current document.
303  */
304 TransferSyntaxType Document::GetTransferSyntax()
305 {
306    DocEntry *entry = GetDocEntry(0x0002, 0x0010);
307    if ( !entry )
308    {
309       return UnknownTS;
310    }
311
312    // The entry might be present but not loaded (parsing and loading
313    // happen at different stages): try loading and proceed with check...
314    LoadDocEntrySafe(entry);
315    if (ValEntry *valEntry = dynamic_cast< ValEntry* >(entry) )
316    {
317       std::string transfer = valEntry->GetValue();
318       // The actual transfer (as read from disk) might be padded. We
319       // first need to remove the potential padding. We can make the
320       // weak assumption that padding was not executed with digits...
321       if  ( transfer.length() == 0 )
322       {
323          // for brain damaged headers
324          return UnknownTS;
325       }
326       while ( !isdigit((unsigned char)transfer[transfer.length()-1]) )
327       {
328          transfer.erase(transfer.length()-1, 1);
329       }
330       for (int i = 0; TransferSyntaxStrings[i] != NULL; i++)
331       {
332          if ( TransferSyntaxStrings[i] == transfer )
333          {
334             return TransferSyntaxType(i);
335          }
336       }
337    }
338    return UnknownTS;
339 }
340
341 bool Document::IsJPEGLossless()
342 {
343    TransferSyntaxType r = GetTransferSyntax();
344    return    r ==  JPEGFullProgressionProcess10_12
345           || r == JPEGLosslessProcess14
346           || r == JPEGLosslessProcess14_1;
347 }
348                                                                                 
349 /**
350  * \brief   Determines if the Transfer Syntax was already encountered
351  *          and if it corresponds to a JPEG2000 one
352  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
353  *          other cases.
354  */
355 bool Document::IsJPEG2000()
356 {
357    TransferSyntaxType r = GetTransferSyntax();
358    return r == JPEG2000Lossless || r == JPEG2000;
359 }
360
361 /**
362  * \brief   Determines if the Transfer Syntax corresponds to any form
363  *          of Jpeg encoded Pixel data.
364  * @return  True when any form of JPEG found. False otherwise.
365  */
366 bool Document::IsJPEG()
367 {
368    TransferSyntaxType r = GetTransferSyntax();
369    return r == JPEGBaselineProcess1 
370      || r == JPEGExtendedProcess2_4
371      || r == JPEGExtendedProcess3_5
372      || r == JPEGSpectralSelectionProcess6_8
373      ||      IsJPEGLossless()
374      ||      IsJPEG2000();
375 }
376
377 /**
378  * \brief   Determines if the Transfer Syntax corresponds to encapsulated
379  *          of encoded Pixel Data (as opposed to native).
380  * @return  True when encapsulated. False when native.
381  */
382 bool Document::IsEncapsulate()
383 {
384    TransferSyntaxType r = GetTransferSyntax();
385    return IsJPEG() || r == RLELossless;
386 }
387
388 /**
389  * \brief   Predicate for dicom version 3 file.
390  * @return  True when the file is a dicom version 3.
391  */
392 bool Document::IsDicomV3()
393 {
394    // Checking if Transfert Syntax exists is enough
395    // Anyway, it's to late check if the 'Preamble' was found ...
396    // And ... would it be a rich idea to check ?
397    // (some 'no Preamble' DICOM images exist !)
398    return GetDocEntry(0x0002, 0x0010) != NULL;
399 }
400
401 /**
402  * \brief  returns the File Type 
403  *         (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
404  * @return the FileType code
405  */
406 FileType Document::GetFileType()
407 {
408    return Filetype;
409 }
410
411 /**
412  * \brief  Tries to open the file \ref Document::Filename and
413  *         checks the preamble when existing.
414  * @return The FILE pointer on success. 
415  */
416 std::ifstream *Document::OpenFile()
417 {
418    if (Filename.length() == 0) 
419    {
420       return 0;
421    }
422
423    if(Fp)
424    {
425       gdcmVerboseMacro( "Is already opened when opening: " << Filename.c_str());
426    }
427
428    Fp = new std::ifstream(Filename.c_str(), std::ios::in | std::ios::binary);
429    if( ! *Fp )
430    {
431       gdcmVerboseMacro( "Cannot open file: " << Filename.c_str());
432       delete Fp;
433       Fp = 0;
434       return 0;
435    }
436  
437    uint16_t zero;
438    Fp->read((char*)&zero, (size_t)2);
439    if( Fp->eof() )
440    {
441       CloseFile();
442       return 0;
443    }
444  
445    //ACR -- or DICOM with no Preamble; may start with a Shadow Group --
446    if( 
447        zero == 0x0001 || zero == 0x0100 || zero == 0x0002 || zero == 0x0200 ||
448        zero == 0x0003 || zero == 0x0300 || zero == 0x0004 || zero == 0x0400 ||
449        zero == 0x0005 || zero == 0x0500 || zero == 0x0006 || zero == 0x0600 ||
450        zero == 0x0007 || zero == 0x0700 || zero == 0x0008 || zero == 0x0800 )
451    {
452       std::string msg 
453          = Util::Format("ACR/DICOM with no preamble: (%04x)\n", zero);
454       gdcmVerboseMacro( msg.c_str() );
455       return Fp;
456    }
457  
458    //DICOM
459    Fp->seekg(126L, std::ios::cur);
460    char dicm[4];
461    Fp->read(dicm,  (size_t)4);
462    if( Fp->eof() )
463    {
464       CloseFile();
465       return 0;
466    }
467    if( memcmp(dicm, "DICM", 4) == 0 )
468    {
469       return Fp;
470    }
471  
472    CloseFile();
473    gdcmVerboseMacro( "Not DICOM/ACR (missing preamble)" << Filename.c_str());
474  
475    return 0;
476 }
477
478 /**
479  * \brief closes the file  
480  * @return  TRUE if the close was successfull 
481  */
482 bool Document::CloseFile()
483 {
484    if( Fp )
485    {
486       Fp->close();
487       delete Fp;
488       Fp = 0;
489    }
490
491    return true; //FIXME how do we detect a non-close ifstream ?
492 }
493
494 /**
495  * \brief Writes in a file all the Header Entries (Dicom Elements) 
496  * @param fp file pointer on an already open file
497  * @param filetype Type of the File to be written 
498  *          (ACR-NEMA, ExplicitVR, ImplicitVR)
499  * \return Always true.
500  */
501 void Document::WriteContent(std::ofstream *fp, FileType filetype)
502 {
503    /// \todo move the following lines (and a lot of others, to be written)
504    /// to a future function CheckAndCorrectHeader  
505    /// (necessary if user wants to write a DICOM V3 file
506    /// starting from an  ACR-NEMA (V2)  Header
507
508    if ( filetype == ImplicitVR || filetype == ExplicitVR )
509    {
510       // writing Dicom File Preamble
511       char filePreamble[128];
512       memset(filePreamble, 0, 128);
513       fp->write(filePreamble, 128);
514       fp->write("DICM", 4);
515    }
516
517 /**
518  * \todo rewrite later, if really usefull
519  *       - 'Group Length' element is optional in DICOM
520  *       - but un-updated odd groups lengthes can causes pb
521  *         (xmedcon breaker)
522  *
523  * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
524  *    UpdateGroupLength(false,filetype);
525  * if ( filetype == ACR)
526  *    UpdateGroupLength(true,ACR);
527  */
528  
529    ElementSet::WriteContent(fp, filetype); // This one is recursive
530 }
531
532 /**
533  * \brief   Modifies the value of a given Doc Entry (Dicom Element)
534  *          when it exists. Create it with the given value when unexistant.
535  * @param   value (string) Value to be set
536  * @param   group   Group number of the Entry 
537  * @param   elem  Element number of the Entry
538  * @param   vr  V(alue) R(epresentation) of the Entry -if private Entry-
539  * \return  pointer to the modified/created Header Entry (NULL when creation
540  *          failed).
541  */ 
542 ValEntry *Document::ReplaceOrCreate(std::string const &value, 
543                                     uint16_t group, 
544                                     uint16_t elem,
545                                     TagName const &vr )
546 {
547    ValEntry *valEntry = 0;
548    DocEntry *currentEntry = GetDocEntry( group, elem);
549    
550    if (currentEntry)
551    {
552       valEntry = dynamic_cast< ValEntry* >(currentEntry);
553
554       // Verify the VR
555       if( valEntry )
556          if( valEntry->GetVR()!=vr )
557             valEntry=NULL;
558
559       // if currentEntry doesn't correspond to the requested valEntry
560       if( !valEntry)
561       {
562          if (!RemoveEntry(currentEntry))
563          {
564             gdcmVerboseMacro( "Removal of previous DocEntry failed.");
565
566             return NULL;
567          }
568       }
569    }
570
571    // Create a new valEntry if necessary
572    if (!valEntry)
573    {
574       valEntry = NewValEntry(group, elem, vr);
575
576       if ( !AddEntry(valEntry))
577       {
578          gdcmVerboseMacro("AddEntry failed although this is a creation.");
579
580          delete valEntry;
581          return NULL;
582       }
583    }
584
585    // Set the binEntry value
586    SetEntry(value, valEntry);
587    return valEntry;
588 }   
589
590 /*
591  * \brief   Modifies the value of a given Header Entry (Dicom Element)
592  *          when it exists. Create it with the given value when unexistant.
593  *          A copy of the binArea is made to be kept in the Document.
594  * @param   binArea (binary) value to be set
595  * @param   Group   Group number of the Entry 
596  * @param   Elem  Element number of the Entry
597  * @param   vr  V(alue) R(epresentation) of the Entry -if private Entry-
598  * \return  pointer to the modified/created Header Entry (NULL when creation
599  *          failed).
600  */
601 BinEntry *Document::ReplaceOrCreate(uint8_t *binArea,
602                                     int lgth, 
603                                     uint16_t group, 
604                                     uint16_t elem,
605                                     TagName const &vr )
606 {
607    BinEntry *binEntry = 0;
608    DocEntry *currentEntry = GetDocEntry( group, elem);
609
610    // Verify the currentEntry
611    if (currentEntry)
612    {
613       binEntry = dynamic_cast< BinEntry* >(currentEntry);
614
615       // Verify the VR
616       if( binEntry )
617          if( binEntry->GetVR()!=vr )
618             binEntry=NULL;
619
620       // if currentEntry doesn't correspond to the requested valEntry
621       if( !binEntry)
622       {
623          if (!RemoveEntry(currentEntry))
624          {
625             gdcmVerboseMacro( "Removal of previous DocEntry failed.");
626
627             return NULL;
628          }
629       }
630    }
631
632    // Create a new binEntry if necessary
633    if (!binEntry)
634    {
635       binEntry = NewBinEntry(group, elem, vr);
636
637       if ( !AddEntry(binEntry))
638       {
639          gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
640
641          delete binEntry;
642          return NULL;
643       }
644    }
645
646    // Set the binEntry value
647    uint8_t *tmpArea;
648    if (lgth>0 && binArea)
649    {
650       tmpArea = new uint8_t[lgth];
651       memcpy(tmpArea,binArea,lgth);
652    }
653    else
654    {
655       tmpArea = 0;
656    }
657    if (!SetEntry(tmpArea,lgth,binEntry))
658    {
659       if (tmpArea)
660       {
661          delete[] tmpArea;
662       }
663    }
664
665    return binEntry;
666 }  
667
668 /*
669  * \brief   Modifies the value of a given Header Entry (Dicom Element)
670  *          when it exists. Create it when unexistant.
671  * @param   Group   Group number of the Entry 
672  * @param   Elem  Element number of the Entry
673  * \return  pointer to the modified/created SeqEntry (NULL when creation
674  *          failed).
675  */
676 SeqEntry *Document::ReplaceOrCreate( uint16_t group, uint16_t elem)
677 {
678    SeqEntry *seqEntry = 0;
679    DocEntry *currentEntry = GetDocEntry( group, elem);
680
681    // Verify the currentEntry
682    if (currentEntry)
683    {
684       seqEntry = dynamic_cast< SeqEntry* >(currentEntry);
685
686       // Verify the VR
687       if( seqEntry )
688          if( seqEntry->GetVR()!="SQ" )
689             seqEntry=NULL;
690
691       // if currentEntry doesn't correspond to the requested valEntry
692       if( !seqEntry)
693       {
694          if (!RemoveEntry(currentEntry))
695          {
696             gdcmVerboseMacro( "Removal of previous DocEntry failed.");
697
698             return NULL;
699          }
700       }
701    }
702
703    // Create a new seqEntry if necessary
704    if (!seqEntry)
705    {
706       seqEntry = NewSeqEntry(group, elem);
707
708       if ( !AddEntry(seqEntry))
709       {
710          gdcmVerboseMacro( "AddEntry failed allthough this is a creation.");
711
712          delete seqEntry;
713          return NULL;
714       }
715    }
716
717    return seqEntry;
718
719  
720 /**
721  * \brief Set a new value if the invoked element exists
722  *        Seems to be useless !!!
723  * @param value new element value
724  * @param group  group number of the Entry 
725  * @param elem element number of the Entry
726  * \return  boolean 
727  */
728 bool Document::ReplaceIfExist(std::string const &value, 
729                               uint16_t group, uint16_t elem ) 
730 {
731    SetEntry(value, group, elem);
732
733    return true;
734
735
736 std::string Document::GetTransferSyntaxValue(TransferSyntaxType type)
737 {
738    return TransferSyntaxStrings[type];
739 }
740
741 //-----------------------------------------------------------------------------
742 // Protected
743
744 /**
745  * \brief   Checks if a given Dicom Element exists within the H table
746  * @param   group      Group number of the searched Dicom Element 
747  * @param   element  Element number of the searched Dicom Element 
748  * @return true is found
749  */
750 bool Document::CheckIfEntryExist(uint16_t group, uint16_t element )
751 {
752    const std::string &key = DictEntry::TranslateToKey(group, element );
753    return TagHT.count(key) != 0;
754 }
755
756
757 /**
758  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
759  *          the public and private dictionaries 
760  *          for the element value representation of a given tag.
761  * @param   group Group number of the searched tag.
762  * @param   element Element number of the searched tag.
763  * @return  Corresponding element value representation when it exists,
764  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
765  */
766 std::string Document::GetEntry(uint16_t group, uint16_t element)
767 {
768    TagKey key = DictEntry::TranslateToKey(group, element);
769    if ( !TagHT.count(key))
770    {
771       return GDCM_UNFOUND;
772    }
773
774    return ((ValEntry *)TagHT.find(key)->second)->GetValue();
775 }
776
777 /**
778  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
779  *          the public and private dictionaries 
780  *          for the element value representation of a given tag..
781  *
782  *          Obtaining the VR (Value Representation) might be needed by caller
783  *          to convert the string typed content to caller's native type 
784  *          (think of C++ vs Python). The VR is actually of a higher level
785  *          of semantics than just the native C++ type.
786  * @param   group     Group number of the searched tag.
787  * @param   element Element number of the searched tag.
788  * @return  Corresponding element value representation when it exists,
789  *          and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
790  */
791 std::string Document::GetEntryVR(uint16_t group, uint16_t element)
792 {
793    DocEntry *elem = GetDocEntry(group, element);
794    if ( !elem )
795    {
796       return GDCM_UNFOUND;
797    }
798    return elem->GetVR();
799 }
800
801 /**
802  * \brief   Searches within Header Entries (Dicom Elements) parsed with 
803  *          the public and private dictionaries 
804  *          for the value length of a given tag..
805  * @param   group     Group number of the searched tag.
806  * @param   element Element number of the searched tag.
807  * @return  Corresponding element length; -2 if not found
808  */
809 int Document::GetEntryLength(uint16_t group, uint16_t element)
810 {
811    DocEntry *elem =  GetDocEntry(group, element);
812    if ( !elem )
813    {
814       return -2;  //magic number
815    }
816    return elem->GetLength();
817 }
818
819 /**
820  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
821  *          through it's (group, element) and modifies it's content with
822  *          the given value.
823  * @param   content new value (string) to substitute with
824  * @param   group     group number of the Dicom Element to modify
825  * @param   element element number of the Dicom Element to modify
826  */
827 bool Document::SetEntry(std::string const& content, 
828                         uint16_t group, uint16_t element) 
829 {
830    ValEntry *entry = GetValEntry(group, element);
831    if (!entry )
832    {
833       gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
834       return false;
835    }
836    return SetEntry(content,entry);
837
838
839 /**
840  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
841  *          through it's (group, element) and modifies it's content with
842  *          the given value.
843  * @param   content new value (void*  -> uint8_t*) to substitute with
844  * @param   lgth new value length
845  * @param   group     group number of the Dicom Element to modify
846  * @param   element element number of the Dicom Element to modify
847  */
848 bool Document::SetEntry(uint8_t*content, int lgth, 
849                         uint16_t group, uint16_t element) 
850 {
851    BinEntry *entry = GetBinEntry(group, element);
852    if (!entry )
853    {
854       gdcmVerboseMacro( "No corresponding ValEntry (try promotion first).");
855       return false;
856    }
857
858    return SetEntry(content,lgth,entry);
859
860
861 /**
862  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
863  *          and modifies it's content with the given value.
864  * @param  content new value (string) to substitute with
865  * @param  entry Entry to be modified
866  */
867 bool Document::SetEntry(std::string const &content,ValEntry *entry)
868 {
869    if(entry)
870    {
871       entry->SetValue(content);
872       return true;
873    }
874    return false;
875 }
876
877 /**
878  * \brief   Accesses an existing BinEntry (i.e. a Dicom Element)
879  *          and modifies it's content with the given value.
880  * @param   content new value (void*  -> uint8_t*) to substitute with
881  * @param  entry Entry to be modified 
882  * @param   lgth new value length
883  */
884 bool Document::SetEntry(uint8_t *content, int lgth, BinEntry *entry)
885 {
886    if(entry)
887    {
888       // Hope Binary field length is *never* wrong    
889       /*if(lgth%2) // Non even length are padded with a space (020H).
890       {  
891          lgth++;
892          //content = content + '\0'; // fing a trick to enlarge a binary field?
893       }*/
894       
895       entry->SetBinArea(content);  
896       entry->SetLength(lgth);
897       entry->SetValue(GDCM_BINLOADED);
898       return true;
899    }
900    return false;
901 }
902
903 /**
904  * \brief   Gets (from Header) a 'non string' element value 
905  *          (LoadElementValues has already be executed)  
906  * @param group   group number of the Entry 
907  * @param elem  element number of the Entry
908  * @return Pointer to the 'non string' area
909  */
910 void *Document::GetEntryBinArea(uint16_t group, uint16_t elem) 
911 {
912    DocEntry *entry = GetDocEntry(group, elem);
913    if (!entry) 
914    {
915       gdcmVerboseMacro( "No entry");
916       return 0;
917    }
918    if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(entry) )
919    {
920       return binEntry->GetBinArea();
921    }
922
923    return 0;
924 }
925
926 /**
927  * \brief         Loads (from disk) the element content 
928  *                when a string is not suitable
929  * @param group   group number of the Entry 
930  * @param elem  element number of the Entry
931  */
932 void Document::LoadEntryBinArea(uint16_t group, uint16_t elem)
933 {
934    // Search the corresponding DocEntry
935    DocEntry *docElement = GetDocEntry(group, elem);
936    if ( !docElement )
937       return;
938
939    BinEntry *binElement = dynamic_cast<BinEntry *>(docElement);
940    if( !binElement )
941       return;
942
943    LoadEntryBinArea(binElement);
944 }
945
946 /**
947  * \brief         Loads (from disk) the element content 
948  *                when a string is not suitable
949  * @param element  Entry whose binArea is going to be loaded
950  */
951 void Document::LoadEntryBinArea(BinEntry *element) 
952 {
953    if(element->GetBinArea())
954       return;
955
956    bool openFile = !Fp;
957    if(openFile)
958       OpenFile();
959
960    size_t o =(size_t)element->GetOffset();
961    Fp->seekg(o, std::ios::beg);
962
963    size_t l = element->GetLength();
964    uint8_t *a = new uint8_t[l];
965    if( !a )
966    {
967       gdcmVerboseMacro( "Cannot allocate a");
968       return;
969    }
970
971    /// \todo check the result 
972    Fp->read((char*)a, l);
973    if( Fp->fail() || Fp->eof()) //Fp->gcount() == 1
974    {
975       delete[] a;
976       return;
977    }
978
979    element->SetBinArea(a);
980
981    if(openFile)
982       CloseFile();
983 }
984
985 /**
986  * \brief   Sets a 'non string' value to a given Dicom Element
987  * @param   area area containing the 'non string' value
988  * @param   group     Group number of the searched Dicom Element 
989  * @param   element Element number of the searched Dicom Element 
990  * @return  
991  */
992 /*bool Document::SetEntryBinArea(uint8_t *area,
993                                  uint16_t group, uint16_t element) 
994 {
995    DocEntry *currentEntry = GetDocEntry(group, element);
996    if ( !currentEntry )
997    {
998       return false;
999    }
1000
1001    if ( BinEntry *binEntry = dynamic_cast<BinEntry*>(currentEntry) )
1002    {
1003       binEntry->SetBinArea( area );
1004       return true;
1005    }
1006
1007    return false;
1008 }*/
1009
1010 /**
1011  * \brief  retrieves a Dicom Element (the first one) using (group, element)
1012  * \warning (group, element) IS NOT an identifier inside the Dicom Header
1013  *           if you think it's NOT UNIQUE, check the count number
1014  *           and use iterators to retrieve ALL the Dicoms Elements within
1015  *           a given couple (group, element)
1016  * @param   group Group number of the searched Dicom Element 
1017  * @param   element Element number of the searched Dicom Element 
1018  * @return  
1019  */
1020 DocEntry *Document::GetDocEntry(uint16_t group, uint16_t element) 
1021 {
1022    TagKey key = DictEntry::TranslateToKey(group, element);
1023    if ( !TagHT.count(key))
1024    {
1025       return NULL;
1026    }
1027    return TagHT.find(key)->second;
1028 }
1029
1030 /**
1031  * \brief  Same as \ref Document::GetDocEntry except it only
1032  *         returns a result when the corresponding entry is of type
1033  *         ValEntry.
1034  * @return When present, the corresponding ValEntry. 
1035  */
1036 ValEntry *Document::GetValEntry(uint16_t group, uint16_t element)
1037 {
1038    DocEntry *currentEntry = GetDocEntry(group, element);
1039    if ( !currentEntry )
1040    {
1041       return 0;
1042    }
1043    if ( ValEntry *entry = dynamic_cast<ValEntry*>(currentEntry) )
1044    {
1045       return entry;
1046    }
1047    gdcmVerboseMacro( "Unfound ValEntry.");
1048
1049    return 0;
1050 }
1051
1052 /**
1053  * \brief  Same as \ref Document::GetDocEntry except it only
1054  *         returns a result when the corresponding entry is of type
1055  *         BinEntry.
1056  * @return When present, the corresponding BinEntry. 
1057  */
1058 BinEntry *Document::GetBinEntry(uint16_t group, uint16_t element)
1059 {
1060    DocEntry *currentEntry = GetDocEntry(group, element);
1061    if ( !currentEntry )
1062    {
1063       return 0;
1064    }
1065    if ( BinEntry *entry = dynamic_cast<BinEntry*>(currentEntry) )
1066    {
1067       return entry;
1068    }
1069    gdcmVerboseMacro( "Unfound BinEntry.");
1070
1071    return 0;
1072 }
1073
1074 /**
1075  * \brief         Loads the element while preserving the current
1076  *               underlying file position indicator as opposed to
1077  *                to LoadDocEntry that modifies it.
1078  * @param entry   Header Entry whose value shall be loaded. 
1079  * @return  
1080  */
1081 void Document::LoadDocEntrySafe(DocEntry *entry)
1082 {
1083    if(Fp)
1084    {
1085       long PositionOnEntry = Fp->tellg();
1086       LoadDocEntry(entry);
1087       Fp->seekg(PositionOnEntry, std::ios::beg);
1088    }
1089 }
1090
1091 /**
1092  * \brief   Swaps back the bytes of 4-byte long integer accordingly to
1093  *          processor order.
1094  * @return  The properly swaped 32 bits integer.
1095  */
1096 uint32_t Document::SwapLong(uint32_t a)
1097 {
1098    switch (SwapCode)
1099    {
1100       case    0 :
1101          break;
1102       case 4321 :
1103          a=( ((a<<24) & 0xff000000) | ((a<<8)  & 0x00ff0000) | 
1104              ((a>>8)  & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1105          break;
1106    
1107       case 3412 :
1108          a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1109          break;
1110    
1111       case 2143 :
1112          a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff)  );
1113          break;
1114       default :
1115          //std::cout << "swapCode= " << SwapCode << std::endl;
1116          gdcmErrorMacro( "Unset swap code");
1117          a = 0;
1118    }
1119    return a;
1120
1121
1122 /**
1123  * \brief   Unswaps back the bytes of 4-byte long integer accordingly to
1124  *          processor order.
1125  * @return  The properly unswaped 32 bits integer.
1126  */
1127 uint32_t Document::UnswapLong(uint32_t a)
1128 {
1129    return SwapLong(a);
1130 }
1131
1132 /**
1133  * \brief   Swaps the bytes so they agree with the processor order
1134  * @return  The properly swaped 16 bits integer.
1135  */
1136 uint16_t Document::SwapShort(uint16_t a)
1137 {
1138    if ( SwapCode == 4321 || SwapCode == 2143 )
1139    {
1140       a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1141    }
1142    return a;
1143 }
1144
1145 /**
1146  * \brief   Unswaps the bytes so they agree with the processor order
1147  * @return  The properly unswaped 16 bits integer.
1148  */
1149 uint16_t Document::UnswapShort(uint16_t a)
1150 {
1151    return SwapShort(a);
1152 }
1153
1154 //-----------------------------------------------------------------------------
1155 // Private
1156
1157 /**
1158  * \brief   Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1159  * @return  length of the parsed set. 
1160  */ 
1161 void Document::ParseDES(DocEntrySet *set, long offset, 
1162                         long l_max, bool delim_mode)
1163 {
1164    DocEntry *newDocEntry = 0;
1165    ValEntry *newValEntry;
1166    BinEntry *newBinEntry;
1167    SeqEntry *newSeqEntry;
1168    VRKey vr;
1169    bool used=false;
1170
1171    while (true)
1172    {
1173       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1174       {
1175          break;
1176       }
1177
1178       used=true;
1179       newDocEntry = ReadNextDocEntry( );
1180       if ( !newDocEntry )
1181       {
1182          break;
1183       }
1184
1185       vr = newDocEntry->GetVR();
1186       newValEntry = dynamic_cast<ValEntry*>(newDocEntry);
1187       newBinEntry = dynamic_cast<BinEntry*>(newDocEntry);
1188       newSeqEntry = dynamic_cast<SeqEntry*>(newDocEntry);
1189
1190       if ( newValEntry || newBinEntry )
1191       {
1192          if ( newBinEntry )
1193          {
1194             if ( ! Global::GetVR()->IsVROfBinaryRepresentable(vr) )
1195             { 
1196                 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1197                 gdcmVerboseMacro( "Neither Valentry, nor BinEntry." 
1198                                   "Probably unknown VR.");
1199             }
1200
1201          //////////////////// BinEntry or UNKOWN VR:
1202             // When "this" is a Document the Key is simply of the
1203             // form ( group, elem )...
1204             if (Document *dummy = dynamic_cast< Document* > ( set ) )
1205             {
1206                (void)dummy;
1207                newBinEntry->SetKey( newBinEntry->GetKey() );
1208             }
1209             // but when "this" is a SQItem, we are inserting this new
1210             // valEntry in a sequence item, and the kay has the
1211             // generalized form (refer to \ref BaseTagKey):
1212             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1213             {
1214                newBinEntry->SetKey(  parentSQItem->GetBaseTagKey()
1215                                    + newBinEntry->GetKey() );
1216             }
1217
1218             LoadDocEntry( newBinEntry );
1219             if( !set->AddEntry( newBinEntry ) )
1220             {
1221               //Expect big troubles if here
1222               //delete newBinEntry;
1223               used=false;
1224             }
1225          }
1226          else
1227          {
1228          /////////////////////// ValEntry
1229             // When "set" is a Document, then we are at the top of the
1230             // hierarchy and the Key is simply of the form ( group, elem )...
1231             if (Document *dummy = dynamic_cast< Document* > ( set ) )
1232             {
1233                (void)dummy;
1234                newValEntry->SetKey( newValEntry->GetKey() );
1235             }
1236             // ...but when "set" is a SQItem, we are inserting this new
1237             // valEntry in a sequence item. Hence the key has the
1238             // generalized form (refer to \ref BaseTagKey):
1239             if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1240             {
1241                newValEntry->SetKey(  parentSQItem->GetBaseTagKey()
1242                                    + newValEntry->GetKey() );
1243             }
1244              
1245             LoadDocEntry( newValEntry );
1246             bool delimitor=newValEntry->IsItemDelimitor();
1247             if( !set->AddEntry( newValEntry ) )
1248             {
1249               // If here expect big troubles
1250               //delete newValEntry; //otherwise mem leak
1251               used=false;
1252             }
1253
1254             if (delimitor)
1255             {
1256                if(!used)
1257                   delete newDocEntry;
1258                break;
1259             }
1260             if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1261             {
1262                if(!used)
1263                   delete newDocEntry;
1264                break;
1265             }
1266          }
1267
1268          if (    ( newDocEntry->GetGroup()   == 0x7fe0 )
1269               && ( newDocEntry->GetElement() == 0x0010 ) )
1270          {
1271              TransferSyntaxType ts = GetTransferSyntax();
1272              if ( ts == RLELossless ) 
1273              {
1274                 long positionOnEntry = Fp->tellg();
1275                 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1276                 ComputeRLEInfo();
1277                 Fp->seekg( positionOnEntry, std::ios::beg );
1278              }
1279              else if ( IsJPEG() )
1280              {
1281                 long positionOnEntry = Fp->tellg();
1282                 Fp->seekg( newDocEntry->GetOffset(), std::ios::beg );
1283                 ComputeJPEGFragmentInfo();
1284                 Fp->seekg( positionOnEntry, std::ios::beg );
1285              }
1286          }
1287
1288          // Just to make sure we are at the beginning of next entry.
1289          SkipToNextDocEntry(newDocEntry);
1290       }
1291       else
1292       {
1293          // VR = "SQ"
1294          unsigned long l = newDocEntry->GetReadLength();            
1295          if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1296          {
1297             if ( l == 0xffffffff )
1298             {
1299               delim_mode = true;
1300             }
1301             else
1302             {
1303               delim_mode = false;
1304             }
1305          }
1306          // no other way to create it ...
1307          newSeqEntry->SetDelimitorMode( delim_mode );
1308
1309          // At the top of the hierarchy, stands a Document. When "set"
1310          // is a Document, then we are building the first depth level.
1311          // Hence the SeqEntry we are building simply has a depth
1312          // level of one:
1313          if (Document *dummy = dynamic_cast< Document* > ( set ) )
1314          {
1315             (void)dummy;
1316             newSeqEntry->SetDepthLevel( 1 );
1317             newSeqEntry->SetKey( newSeqEntry->GetKey() );
1318          }
1319          // But when "set" is allready a SQItem, we are building a nested
1320          // sequence, and hence the depth level of the new SeqEntry
1321          // we are building, is one level deeper:
1322          if (SQItem *parentSQItem = dynamic_cast< SQItem* > ( set ) )
1323          {
1324             newSeqEntry->SetDepthLevel( parentSQItem->GetDepthLevel() + 1 );
1325             newSeqEntry->SetKey(  parentSQItem->GetBaseTagKey()
1326                                 + newSeqEntry->GetKey() );
1327          }
1328
1329          if ( l != 0 )
1330          {  // Don't try to parse zero-length sequences
1331             ParseSQ( newSeqEntry, 
1332                      newDocEntry->GetOffset(),
1333                      l, delim_mode);
1334          }
1335          set->AddEntry( newSeqEntry );
1336          if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1337          {
1338             break;
1339          }
1340       }
1341
1342       if(!used)
1343          delete newDocEntry;
1344    }
1345 }
1346
1347 /**
1348  * \brief   Parses a Sequence ( SeqEntry after SeqEntry)
1349  * @return  parsed length for this level
1350  */ 
1351 void Document::ParseSQ( SeqEntry *seqEntry,
1352                         long offset, long l_max, bool delim_mode)
1353 {
1354    int SQItemNumber = 0;
1355    bool dlm_mod;
1356
1357    while (true)
1358    {
1359       DocEntry *newDocEntry = ReadNextDocEntry();   
1360       if ( !newDocEntry )
1361       {
1362          // FIXME Should warn user
1363          break;
1364       }
1365       if( delim_mode )
1366       {
1367          if ( newDocEntry->IsSequenceDelimitor() )
1368          {
1369             seqEntry->SetSequenceDelimitationItem( newDocEntry ); 
1370             break;
1371          }
1372       }
1373       if ( !delim_mode && ((long)(Fp->tellg())-offset) >= l_max)
1374       {
1375          delete newDocEntry;
1376          break;
1377       }
1378
1379       SQItem *itemSQ = new SQItem( seqEntry->GetDepthLevel() );
1380       std::ostringstream newBase;
1381       newBase << seqEntry->GetKey()
1382               << "/"
1383               << SQItemNumber
1384               << "#";
1385       itemSQ->SetBaseTagKey( newBase.str() );
1386       unsigned int l = newDocEntry->GetReadLength();
1387       
1388       if ( l == 0xffffffff )
1389       {
1390          dlm_mod = true;
1391       }
1392       else
1393       {
1394          dlm_mod = false;
1395       }
1396    
1397       ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1398       delete newDocEntry;
1399       
1400       seqEntry->AddEntry( itemSQ, SQItemNumber ); 
1401       SQItemNumber++;
1402       if ( !delim_mode && ((long)(Fp->tellg())-offset ) >= l_max )
1403       {
1404          break;
1405       }
1406    }
1407 }
1408
1409 /**
1410  * \brief         Loads the element content if its length doesn't exceed
1411  *                the value specified with Document::SetMaxSizeLoadEntry()
1412  * @param         entry Header Entry (Dicom Element) to be dealt with
1413  */
1414 void Document::LoadDocEntry(DocEntry *entry)
1415 {
1416    uint16_t group  = entry->GetGroup();
1417    std::string  vr = entry->GetVR();
1418    uint32_t length = entry->GetLength();
1419
1420    Fp->seekg((long)entry->GetOffset(), std::ios::beg);
1421
1422    // A SeQuence "contains" a set of Elements.  
1423    //          (fffe e000) tells us an Element is beginning
1424    //          (fffe e00d) tells us an Element just ended
1425    //          (fffe e0dd) tells us the current SeQuence just ended
1426    if( group == 0xfffe )
1427    {
1428       // NO more value field for SQ !
1429       return;
1430    }
1431
1432    // When the length is zero things are easy:
1433    if ( length == 0 )
1434    {
1435       ((ValEntry *)entry)->SetValue("");
1436       return;
1437    }
1438
1439    // The elements whose length is bigger than the specified upper bound
1440    // are not loaded. Instead we leave a short notice of the offset of
1441    // the element content and it's length.
1442
1443    std::ostringstream s;
1444    if (length > MaxSizeLoadEntry)
1445    {
1446       if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1447       {  
1448          //s << "gdcm::NotLoaded (BinEntry)";
1449          s << GDCM_NOTLOADED;
1450          s << " Address:" << (long)entry->GetOffset();
1451          s << " Length:"  << entry->GetLength();
1452          s << " x(" << std::hex << entry->GetLength() << ")";
1453          binEntryPtr->SetValue(s.str());
1454       }
1455       // Be carefull : a BinEntry IS_A ValEntry ... 
1456       else if (ValEntry *valEntryPtr = dynamic_cast< ValEntry* >(entry) )
1457       {
1458         // s << "gdcm::NotLoaded. (ValEntry)";
1459          s << GDCM_NOTLOADED;  
1460          s << " Address:" << (long)entry->GetOffset();
1461          s << " Length:"  << entry->GetLength();
1462          s << " x(" << std::hex << entry->GetLength() << ")";
1463          valEntryPtr->SetValue(s.str());
1464       }
1465       else
1466       {
1467          // fusible
1468          std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1469                   << "nor a ValEntry ?! Should never print that !" << std::endl;
1470       }
1471
1472       // to be sure we are at the end of the value ...
1473       Fp->seekg((long)entry->GetOffset()+(long)entry->GetLength(),
1474                 std::ios::beg);
1475       return;
1476    }
1477
1478    // When we find a BinEntry not very much can be done :
1479    if (BinEntry *binEntryPtr = dynamic_cast< BinEntry* >(entry) )
1480    {
1481       s << GDCM_BINLOADED;
1482       binEntryPtr->SetValue(s.str());
1483       LoadEntryBinArea(binEntryPtr); // last one, not to erase length !
1484       return;
1485    }
1486
1487    /// \todo Any compacter code suggested (?)
1488    if ( IsDocEntryAnInteger(entry) )
1489    {   
1490       uint32_t NewInt;
1491       int nbInt;
1492       // When short integer(s) are expected, read and convert the following 
1493       // n *two characters properly i.e. consider them as short integers as
1494       // opposed to strings.
1495       // Elements with Value Multiplicity > 1
1496       // contain a set of integers (not a single one)       
1497       if (vr == "US" || vr == "SS")
1498       {
1499          nbInt = length / 2;
1500          NewInt = ReadInt16();
1501          s << NewInt;
1502          if (nbInt > 1)
1503          {
1504             for (int i=1; i < nbInt; i++)
1505             {
1506                s << '\\';
1507                NewInt = ReadInt16();
1508                s << NewInt;
1509             }
1510          }
1511       }
1512       // See above comment on multiple integers (mutatis mutandis).
1513       else if (vr == "UL" || vr == "SL")
1514       {
1515          nbInt = length / 4;
1516          NewInt = ReadInt32();
1517          s << NewInt;
1518          if (nbInt > 1)
1519          {
1520             for (int i=1; i < nbInt; i++)
1521             {
1522                s << '\\';
1523                NewInt = ReadInt32();
1524                s << NewInt;
1525             }
1526          }
1527       }
1528 #ifdef GDCM_NO_ANSI_STRING_STREAM
1529       s << std::ends; // to avoid oddities on Solaris
1530 #endif //GDCM_NO_ANSI_STRING_STREAM
1531
1532       ((ValEntry *)entry)->SetValue(s.str());
1533       return;
1534    }
1535    
1536   // FIXME: We need an additional byte for storing \0 that is not on disk
1537    char *str = new char[length+1];
1538    Fp->read(str, (size_t)length);
1539    str[length] = '\0'; //this is only useful when length is odd
1540    // Special DicomString call to properly handle \0 and even length
1541    std::string newValue;
1542    if( length % 2 )
1543    {
1544       newValue = Util::DicomString(str, length+1);
1545       gdcmVerboseMacro("Warning: bad length: " << length );
1546       gdcmVerboseMacro("For string :" <<  newValue.c_str()); 
1547       // Since we change the length of string update it length
1548       //entry->SetReadLength(length+1);
1549    }
1550    else
1551    {
1552       newValue = Util::DicomString(str, length);
1553    }
1554    delete[] str;
1555
1556    if ( ValEntry *valEntry = dynamic_cast<ValEntry* >(entry) )
1557    {
1558       if ( Fp->fail() || Fp->eof())//Fp->gcount() == 1
1559       {
1560          gdcmVerboseMacro( "Unread element value");
1561          valEntry->SetValue(GDCM_UNREAD);
1562          return;
1563       }
1564
1565       if( vr == "UI" )
1566       {
1567          // Because of correspondance with the VR dic
1568          valEntry->SetValue(newValue);
1569       }
1570       else
1571       {
1572          valEntry->SetValue(newValue);
1573       }
1574    }
1575    else
1576    {
1577       gdcmErrorMacro( "Should have a ValEntry, here !");
1578    }
1579 }
1580
1581
1582 /**
1583  * \brief  Find the value Length of the passed Header Entry
1584  * @param  entry Header Entry whose length of the value shall be loaded. 
1585  */
1586 void Document::FindDocEntryLength( DocEntry *entry )
1587    throw ( FormatError )
1588 {
1589    uint16_t element = entry->GetElement();
1590    std::string  vr  = entry->GetVR();
1591    uint16_t length16;       
1592    
1593    if ( Filetype == ExplicitVR && !entry->IsImplicitVR() ) 
1594    {
1595       if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" ) 
1596       {
1597          // The following reserved two bytes (see PS 3.5-2003, section
1598          // "7.1.2 Data element structure with explicit vr", p 27) must be
1599          // skipped before proceeding on reading the length on 4 bytes.
1600          Fp->seekg( 2L, std::ios::cur);
1601          uint32_t length32 = ReadInt32();
1602
1603          if ( (vr == "OB" || vr == "OW") && length32 == 0xffffffff ) 
1604          {
1605             uint32_t lengthOB;
1606             try 
1607             {
1608                lengthOB = FindDocEntryLengthOBOrOW();
1609             }
1610             catch ( FormatUnexpected )
1611             {
1612                // Computing the length failed (this happens with broken
1613                // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1614                // chance to get the pixels by deciding the element goes
1615                // until the end of the file. Hence we artificially fix the
1616                // the length and proceed.
1617                long currentPosition = Fp->tellg();
1618                Fp->seekg(0L,std::ios::end);
1619
1620                long lengthUntilEOF = (long)(Fp->tellg())-currentPosition;
1621                Fp->seekg(currentPosition, std::ios::beg);
1622
1623                entry->SetReadLength(lengthUntilEOF);
1624                entry->SetLength(lengthUntilEOF);
1625                return;
1626             }
1627             entry->SetReadLength(lengthOB);
1628             entry->SetLength(lengthOB);
1629             return;
1630          }
1631          FixDocEntryFoundLength(entry, length32); 
1632          return;
1633       }
1634
1635       // Length is encoded on 2 bytes.
1636       length16 = ReadInt16();
1637       
1638       // We can tell the current file is encoded in big endian (like
1639       // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1640       // and it's value is the one of the encoding of a big endian file.
1641       // In order to deal with such big endian encoded files, we have
1642       // (at least) two strategies:
1643       // * when we load the "Transfer Syntax" tag with value of big endian
1644       //   encoding, we raise the proper flags. Then we wait for the end
1645       //   of the META group (0x0002) among which is "Transfer Syntax",
1646       //   before switching the swap code to big endian. We have to postpone
1647       //   the switching of the swap code since the META group is fully encoded
1648       //   in little endian, and big endian coding only starts at the next
1649       //   group. The corresponding code can be hard to analyse and adds
1650       //   many additional unnecessary tests for regular tags.
1651       // * the second strategy consists in waiting for trouble, that shall
1652       //   appear when we find the first group with big endian encoding. This
1653       //   is easy to detect since the length of a "Group Length" tag (the
1654       //   ones with zero as element number) has to be of 4 (0x0004). When we
1655       //   encounter 1024 (0x0400) chances are the encoding changed and we
1656       //   found a group with big endian encoding.
1657       // We shall use this second strategy. In order to make sure that we
1658       // can interpret the presence of an apparently big endian encoded
1659       // length of a "Group Length" without committing a big mistake, we
1660       // add an additional check: we look in the already parsed elements
1661       // for the presence of a "Transfer Syntax" whose value has to be "big
1662       // endian encoding". When this is the case, chances are we have got our
1663       // hands on a big endian encoded file: we switch the swap code to
1664       // big endian and proceed...
1665       if ( element  == 0x0000 && length16 == 0x0400 ) 
1666       {
1667          TransferSyntaxType ts = GetTransferSyntax();
1668          if ( ts != ExplicitVRBigEndian ) 
1669          {
1670             throw FormatError( "Document::FindDocEntryLength()",
1671                                " not explicit VR." );
1672             return;
1673          }
1674          length16 = 4;
1675          SwitchSwapToBigEndian();
1676
1677          // Restore the unproperly loaded values i.e. the group, the element
1678          // and the dictionary entry depending on them.
1679          uint16_t correctGroup = SwapShort( entry->GetGroup() );
1680          uint16_t correctElem  = SwapShort( entry->GetElement() );
1681          DictEntry *newTag = GetDictEntry( correctGroup,
1682                                                        correctElem );
1683          if ( !newTag )
1684          {
1685             // This correct tag is not in the dictionary. Create a new one.
1686             newTag = NewVirtualDictEntry(correctGroup, correctElem);
1687          }
1688          // FIXME this can create a memory leaks on the old entry that be
1689          // left unreferenced.
1690          entry->SetDictEntry( newTag );
1691       }
1692        
1693       // Heuristic: well, some files are really ill-formed.
1694       if ( length16 == 0xffff) 
1695       {
1696          // 0xffff means that we deal with 'Unknown Length' Sequence  
1697          length16 = 0;
1698       }
1699       FixDocEntryFoundLength( entry, (uint32_t)length16 );
1700       return;
1701    }
1702    else
1703    {
1704       // Either implicit VR or a non DICOM conformal (see note below) explicit
1705       // VR that ommited the VR of (at least) this element. Farts happen.
1706       // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1707       // on Data elements "Implicit and Explicit VR Data Elements shall
1708       // not coexist in a Data Set and Data Sets nested within it".]
1709       // Length is on 4 bytes.
1710       
1711       FixDocEntryFoundLength( entry, ReadInt32() );
1712       return;
1713    }
1714 }
1715
1716 /**
1717  * \brief     Find the Value Representation of the current Dicom Element.
1718  * @return    Value Representation of the current Entry
1719  */
1720 std::string Document::FindDocEntryVR()
1721 {
1722    if ( Filetype != ExplicitVR )
1723       return(GDCM_UNKNOWN);
1724
1725    long positionOnEntry = Fp->tellg();
1726    // Warning: we believe this is explicit VR (Value Representation) because
1727    // we used a heuristic that found "UL" in the first tag. Alas this
1728    // doesn't guarantee that all the tags will be in explicit VR. In some
1729    // cases (see e-film filtered files) one finds implicit VR tags mixed
1730    // within an explicit VR file. Hence we make sure the present tag
1731    // is in explicit VR and try to fix things if it happens not to be
1732    // the case.
1733
1734    char vr[3];
1735    Fp->read (vr, (size_t)2);
1736    vr[2] = 0;
1737
1738    if( !CheckDocEntryVR(vr) )
1739    {
1740       Fp->seekg(positionOnEntry, std::ios::beg);
1741       return(GDCM_UNKNOWN);
1742    }
1743    return(vr);
1744 }
1745
1746 /**
1747  * \brief     Check the correspondance between the VR of the header entry
1748  *            and the taken VR. If they are different, the header entry is 
1749  *            updated with the new VR.
1750  * @param     vr    Dicom Value Representation
1751  * @return    false if the VR is incorrect of if the VR isn't referenced
1752  *            otherwise, it returns true
1753 */
1754 bool Document::CheckDocEntryVR(VRKey vr)
1755 {
1756    // CLEANME searching the dicom_vr at each occurence is expensive.
1757    // PostPone this test in an optional integrity check at the end
1758    // of parsing or only in debug mode.
1759    if ( !Global::GetVR()->IsValidVR(vr) )
1760       return false;
1761
1762    return true; 
1763 }
1764
1765 /**
1766  * \brief   Get the transformed value of the header entry. The VR value 
1767  *          is used to define the transformation to operate on the value
1768  * \warning NOT end user intended method !
1769  * @param   entry entry to tranform
1770  * @return  Transformed entry value
1771  */
1772 std::string Document::GetDocEntryValue(DocEntry *entry)
1773 {
1774    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1775    {
1776       std::string val = ((ValEntry *)entry)->GetValue();
1777       std::string vr  = entry->GetVR();
1778       uint32_t length = entry->GetLength();
1779       std::ostringstream s;
1780       int nbInt;
1781
1782       // When short integer(s) are expected, read and convert the following 
1783       // n * 2 bytes properly i.e. as a multivaluated strings
1784       // (each single value is separated fromthe next one by '\'
1785       // as usual for standard multivaluated filels
1786       // Elements with Value Multiplicity > 1
1787       // contain a set of short integers (not a single one) 
1788    
1789       if( vr == "US" || vr == "SS" )
1790       {
1791          uint16_t newInt16;
1792
1793          nbInt = length / 2;
1794          for (int i=0; i < nbInt; i++) 
1795          {
1796             if( i != 0 )
1797             {
1798                s << '\\';
1799             }
1800             newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1801             newInt16 = SwapShort( newInt16 );
1802             s << newInt16;
1803          }
1804       }
1805
1806       // When integer(s) are expected, read and convert the following 
1807       // n * 4 bytes properly i.e. as a multivaluated strings
1808       // (each single value is separated fromthe next one by '\'
1809       // as usual for standard multivaluated filels
1810       // Elements with Value Multiplicity > 1
1811       // contain a set of integers (not a single one) 
1812       else if( vr == "UL" || vr == "SL" )
1813       {
1814          uint32_t newInt32;
1815
1816          nbInt = length / 4;
1817          for (int i=0; i < nbInt; i++) 
1818          {
1819             if( i != 0)
1820             {
1821                s << '\\';
1822             }
1823             newInt32 = ( val[4*i+0] & 0xFF )
1824                     + (( val[4*i+1] & 0xFF ) <<  8 )
1825                     + (( val[4*i+2] & 0xFF ) << 16 )
1826                     + (( val[4*i+3] & 0xFF ) << 24 );
1827             newInt32 = SwapLong( newInt32 );
1828             s << newInt32;
1829          }
1830       }
1831 #ifdef GDCM_NO_ANSI_STRING_STREAM
1832       s << std::ends; // to avoid oddities on Solaris
1833 #endif //GDCM_NO_ANSI_STRING_STREAM
1834       return s.str();
1835    }
1836
1837    return ((ValEntry *)entry)->GetValue();
1838 }
1839
1840 /**
1841  * \brief   Get the reverse transformed value of the header entry. The VR 
1842  *          value is used to define the reverse transformation to operate on
1843  *          the value
1844  * \warning NOT end user intended method !
1845  * @param   entry Entry to reverse transform
1846  * @return  Reverse transformed entry value
1847  */
1848 std::string Document::GetDocEntryUnvalue(DocEntry *entry)
1849 {
1850    if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1851    {
1852       std::string vr = entry->GetVR();
1853       std::vector<std::string> tokens;
1854       std::ostringstream s;
1855
1856       if ( vr == "US" || vr == "SS" ) 
1857       {
1858          uint16_t newInt16;
1859
1860          tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1861          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1862          for (unsigned int i=0; i<tokens.size(); i++) 
1863          {
1864             newInt16 = atoi(tokens[i].c_str());
1865             s << (  newInt16        & 0xFF ) 
1866               << (( newInt16 >> 8 ) & 0xFF );
1867          }
1868          tokens.clear();
1869       }
1870       if ( vr == "UL" || vr == "SL")
1871       {
1872          uint32_t newInt32;
1873
1874          tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1875          Util::Tokenize (((ValEntry *)entry)->GetValue(), tokens, "\\");
1876          for (unsigned int i=0; i<tokens.size();i++) 
1877          {
1878             newInt32 = atoi(tokens[i].c_str());
1879             s << (char)(  newInt32         & 0xFF ) 
1880               << (char)(( newInt32 >>  8 ) & 0xFF )
1881               << (char)(( newInt32 >> 16 ) & 0xFF )
1882               << (char)(( newInt32 >> 24 ) & 0xFF );
1883          }
1884          tokens.clear();
1885       }
1886
1887 #ifdef GDCM_NO_ANSI_STRING_STREAM
1888       s << std::ends; // to avoid oddities on Solaris
1889 #endif //GDCM_NO_ANSI_STRING_STREAM
1890       return s.str();
1891    }
1892
1893    return ((ValEntry *)entry)->GetValue();
1894 }
1895
1896 /**
1897  * \brief   Skip a given Header Entry 
1898  * \warning NOT end user intended method !
1899  * @param   entry entry to skip
1900  */
1901 void Document::SkipDocEntry(DocEntry *entry) 
1902 {
1903    SkipBytes(entry->GetLength());
1904 }
1905
1906 /**
1907  * \brief   Skips to the begining of the next Header Entry 
1908  * \warning NOT end user intended method !
1909  * @param   offset start of skipping
1910  * @param   readLgth length to skip
1911
1912  */
1913 void Document::SkipToNextDocEntry(DocEntry *newDocEntry) 
1914 {
1915    Fp->seekg((long)(newDocEntry->GetOffset()),     std::ios::beg);
1916    Fp->seekg( (long)(newDocEntry->GetReadLength()),std::ios::cur);
1917 }
1918
1919 /**
1920  * \brief   When the length of an element value is obviously wrong (because
1921  *          the parser went Jabberwocky) one can hope improving things by
1922  *          applying some heuristics.
1923  * @param   entry entry to check
1924  * @param   foundLength fist assumption about length    
1925  */
1926 void Document::FixDocEntryFoundLength(DocEntry *entry,
1927                                       uint32_t foundLength)
1928 {
1929    entry->SetReadLength( foundLength ); // will be updated only if a bug is found        
1930    if ( foundLength == 0xffffffff)
1931    {
1932       foundLength = 0;
1933    }
1934    
1935    uint16_t gr   = entry->GetGroup();
1936    uint16_t elem = entry->GetElement(); 
1937      
1938    if ( foundLength % 2)
1939    {
1940       gdcmVerboseMacro( "Warning : Tag with uneven length " << foundLength 
1941         <<  " in x(" << std::hex << gr << "," << elem <<")");
1942    }
1943       
1944    //////// Fix for some naughty General Electric images.
1945    // Allthough not recent many such GE corrupted images are still present
1946    // on Creatis hard disks. Hence this fix shall remain when such images
1947    // are no longer in use (we are talking a few years, here)...
1948    // Note: XMedCom probably uses such a trick since it is able to read
1949    //       those pesky GE images ...
1950    if ( foundLength == 13)
1951    {
1952       // Only happens for this length !
1953       if ( gr != 0x0008 || ( elem != 0x0070 && elem != 0x0080 ) )
1954       {
1955          foundLength = 10;
1956          entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1957       }
1958    }
1959
1960    //////// Fix for some brain-dead 'Leonardo' Siemens images.
1961    // Occurence of such images is quite low (unless one leaves close to a
1962    // 'Leonardo' source. Hence, one might consider commenting out the
1963    // following fix on efficiency reasons.
1964    else if ( gr   == 0x0009 && ( elem == 0x1113 || elem == 0x1114 ) )
1965    {
1966       foundLength = 4;
1967       entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1968    } 
1969  
1970    else if ( entry->GetVR() == "SQ" )
1971    {
1972       foundLength = 0;      // ReadLength is unchanged 
1973    } 
1974     
1975    //////// We encountered a 'delimiter' element i.e. a tag of the form 
1976    // "fffe|xxxx" which is just a marker. Delimiters length should not be
1977    // taken into account.
1978    else if( gr == 0xfffe )
1979    {    
1980      // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1981      // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1982      // causes extra troubles...
1983      if( entry->GetElement() != 0x0000 )
1984      {
1985         foundLength = 0;
1986      }
1987    } 
1988            
1989    entry->SetLength(foundLength);
1990 }
1991
1992 /**
1993  * \brief   Apply some heuristics to predict whether the considered 
1994  *          element value contains/represents an integer or not.
1995  * @param   entry The element value on which to apply the predicate.
1996  * @return  The result of the heuristical predicate.
1997  */
1998 bool Document::IsDocEntryAnInteger(DocEntry *entry)
1999 {
2000    uint16_t elem    = entry->GetElement();
2001    uint16_t group   = entry->GetGroup();
2002    const std::string &vr  = entry->GetVR();
2003    uint32_t length  = entry->GetLength();
2004
2005    // When we have some semantics on the element we just read, and if we
2006    // a priori know we are dealing with an integer, then we shall be
2007    // able to swap it's element value properly.
2008    if ( elem == 0 )  // This is the group length of the group
2009    {  
2010       if ( length == 4 )
2011       {
2012          return true;
2013       }
2014       else 
2015       {
2016          // Allthough this should never happen, still some images have a
2017          // corrupted group length [e.g. have a glance at offset x(8336) of
2018          // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2019          // Since for dicom compliant and well behaved headers, the present
2020          // test is useless (and might even look a bit paranoid), when we
2021          // encounter such an ill-formed image, we simply display a warning
2022          // message and proceed on parsing (while crossing fingers).
2023          long filePosition = Fp->tellg();
2024          gdcmVerboseMacro( "Erroneous Group Length element length  on : (" 
2025            << std::hex << group << " , " << elem
2026            << ") -before- position x(" << filePosition << ")"
2027            << "lgt : " << length );
2028       }
2029    }
2030
2031    if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2032    {
2033       return true;
2034    }   
2035    return false;
2036 }
2037
2038 /**
2039  * \brief  Find the Length till the next sequence delimiter
2040  * \warning NOT end user intended method !
2041  * @return 
2042  */
2043
2044 uint32_t Document::FindDocEntryLengthOBOrOW()
2045    throw( FormatUnexpected )
2046 {
2047    // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2048    long positionOnEntry = Fp->tellg();
2049    bool foundSequenceDelimiter = false;
2050    uint32_t totalLength = 0;
2051
2052    while ( !foundSequenceDelimiter )
2053    {
2054       uint16_t group;
2055       uint16_t elem;
2056       try
2057       {
2058          group = ReadInt16();
2059          elem  = ReadInt16();   
2060       }
2061       catch ( FormatError )
2062       {
2063          throw FormatError("Unexpected end of file encountered during ",
2064                            "Document::FindDocEntryLengthOBOrOW()");
2065       }
2066
2067       // We have to decount the group and element we just read
2068       totalLength += 4;
2069      
2070       if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2071       {
2072          long filePosition = Fp->tellg();
2073          gdcmVerboseMacro( "Neither an Item tag nor a Sequence delimiter tag on :" 
2074            << std::hex << group << " , " << elem 
2075            << ") -before- position x(" << filePosition << ")" );
2076   
2077          Fp->seekg(positionOnEntry, std::ios::beg);
2078          throw FormatUnexpected( "Neither an Item tag nor a Sequence delimiter tag.");
2079       }
2080
2081       if ( elem == 0xe0dd )
2082       {
2083          foundSequenceDelimiter = true;
2084       }
2085
2086       uint32_t itemLength = ReadInt32();
2087       // We add 4 bytes since we just read the ItemLength with ReadInt32
2088       totalLength += itemLength + 4;
2089       SkipBytes(itemLength);
2090       
2091       if ( foundSequenceDelimiter )
2092       {
2093          break;
2094       }
2095    }
2096    Fp->seekg( positionOnEntry, std::ios::beg);
2097    return totalLength;
2098 }
2099
2100 /**
2101  * \brief Reads a supposed to be 16 Bits integer
2102  *       (swaps it depending on processor endianity) 
2103  * @return read value
2104  */
2105 uint16_t Document::ReadInt16()
2106    throw( FormatError )
2107 {
2108    uint16_t g;
2109    Fp->read ((char*)&g, (size_t)2);
2110    if ( Fp->fail() )
2111    {
2112       throw FormatError( "Document::ReadInt16()", " file error." );
2113    }
2114    if( Fp->eof() )
2115    {
2116       throw FormatError( "Document::ReadInt16()", "EOF." );
2117    }
2118    g = SwapShort(g); 
2119    return g;
2120 }
2121
2122 /**
2123  * \brief  Reads a supposed to be 32 Bits integer
2124  *         (swaps it depending on processor endianity)  
2125  * @return read value
2126  */
2127 uint32_t Document::ReadInt32()
2128    throw( FormatError )
2129 {
2130    uint32_t g;
2131    Fp->read ((char*)&g, (size_t)4);
2132    if ( Fp->fail() )
2133    {
2134       throw FormatError( "Document::ReadInt32()", " file error." );
2135    }
2136    if( Fp->eof() )
2137    {
2138       throw FormatError( "Document::ReadInt32()", "EOF." );
2139    }
2140    g = SwapLong(g);
2141    return g;
2142 }
2143
2144 /**
2145  * \brief skips bytes inside the source file 
2146  * \warning NOT end user intended method !
2147  * @return 
2148  */
2149 void Document::SkipBytes(uint32_t nBytes)
2150 {
2151    //FIXME don't dump the returned value
2152    Fp->seekg((long)nBytes, std::ios::cur);
2153 }
2154
2155 /**
2156  * \brief Loads all the needed Dictionaries
2157  * \warning NOT end user intended method !   
2158  */
2159 void Document::Initialise() 
2160 {
2161    RefPubDict = Global::GetDicts()->GetDefaultPubDict();
2162    RefShaDict = NULL;
2163    RLEInfo  = new RLEFramesInfo;
2164    JPEGInfo = new JPEGFragmentsInfo;
2165    Filetype = Unknown;
2166 }
2167
2168 /**
2169  * \brief   Discover what the swap code is (among little endian, big endian,
2170  *          bad little endian, bad big endian).
2171  *          sw is set
2172  * @return false when we are absolutely sure 
2173  *               it's neither ACR-NEMA nor DICOM
2174  *         true  when we hope ours assuptions are OK
2175  */
2176 bool Document::CheckSwap()
2177 {
2178    // The only guaranted way of finding the swap code is to find a
2179    // group tag since we know it's length has to be of four bytes i.e.
2180    // 0x00000004. Finding the swap code in then straigthforward. Trouble
2181    // occurs when we can't find such group...
2182    
2183    uint32_t  x = 4;  // x : for ntohs
2184    bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2185    uint32_t  s32;
2186    uint16_t  s16;
2187        
2188    char deb[256];
2189     
2190    // First, compare HostByteOrder and NetworkByteOrder in order to
2191    // determine if we shall need to swap bytes (i.e. the Endian type).
2192    if ( x == ntohs(x) )
2193    {
2194       net2host = true;
2195    }
2196    else
2197    {
2198       net2host = false;
2199    }
2200          
2201    // The easiest case is the one of a DICOM header, since it possesses a
2202    // file preamble where it suffice to look for the string "DICM".
2203    Fp->read(deb, 256);
2204    
2205    char *entCur = deb + 128;
2206    if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2207    {
2208       gdcmVerboseMacro( "Looks like DICOM Version3" );
2209       
2210       // Next, determine the value representation (VR). Let's skip to the
2211       // first element (0002, 0000) and check there if we find "UL" 
2212       // - or "OB" if the 1st one is (0002,0001) -,
2213       // in which case we (almost) know it is explicit VR.
2214       // WARNING: if it happens to be implicit VR then what we will read
2215       // is the length of the group. If this ascii representation of this
2216       // length happens to be "UL" then we shall believe it is explicit VR.
2217       // FIXME: in order to fix the above warning, we could read the next
2218       // element value (or a couple of elements values) in order to make
2219       // sure we are not commiting a big mistake.
2220       // We need to skip :
2221       // * the 128 bytes of File Preamble (often padded with zeroes),
2222       // * the 4 bytes of "DICM" string,
2223       // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2224       // i.e. a total of  136 bytes.
2225       entCur = deb + 136;
2226      
2227       // FIXME : FIXME:
2228       // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2229       // but elem 0002,0010 (Transfert Syntax) tells us the file is
2230       // *Implicit* VR.  -and it is !- 
2231       
2232       if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2233           memcmp(entCur, "OB", (size_t)2) == 0 ||
2234           memcmp(entCur, "UI", (size_t)2) == 0 ||
2235           memcmp(entCur, "CS", (size_t)2) == 0 )  // CS, to remove later
2236                                                     // when Write DCM *adds*
2237       // FIXME
2238       // Use Document::dicom_vr to test all the possibilities
2239       // instead of just checking for UL, OB and UI !? group 0000 
2240       {
2241          Filetype = ExplicitVR;
2242          gdcmVerboseMacro( "Explicit Value Representation");
2243       } 
2244       else 
2245       {
2246          Filetype = ImplicitVR;
2247          gdcmVerboseMacro( "Not an explicit Value Representation");
2248       }
2249       
2250       if ( net2host )
2251       {
2252          SwapCode = 4321;
2253          gdcmVerboseMacro( "HostByteOrder != NetworkByteOrder");
2254       }
2255       else 
2256       {
2257          SwapCode = 0;
2258          gdcmVerboseMacro( "HostByteOrder = NetworkByteOrder");
2259       }
2260       
2261       // Position the file position indicator at first tag (i.e.
2262       // after the file preamble and the "DICM" string).
2263       Fp->seekg(0, std::ios::beg);
2264       Fp->seekg ( 132L, std::ios::beg);
2265       return true;
2266    } // End of DicomV3
2267
2268    // Alas, this is not a DicomV3 file and whatever happens there is no file
2269    // preamble. We can reset the file position indicator to where the data
2270    // is (i.e. the beginning of the file).
2271    gdcmVerboseMacro( "Not a DICOM Version3 file");
2272    Fp->seekg(0, std::ios::beg);
2273
2274    // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2275    // By clean we mean that the length of the first tag is written down.
2276    // If this is the case and since the length of the first group HAS to be
2277    // four (bytes), then determining the proper swap code is straightforward.
2278
2279    entCur = deb + 4;
2280    // We assume the array of char we are considering contains the binary
2281    // representation of a 32 bits integer. Hence the following dirty
2282    // trick :
2283    s32 = *((uint32_t *)(entCur));
2284
2285    switch( s32 )
2286    {
2287       case 0x00040000 :
2288          SwapCode = 3412;
2289          Filetype = ACR;
2290          return true;
2291       case 0x04000000 :
2292          SwapCode = 4321;
2293          Filetype = ACR;
2294          return true;
2295       case 0x00000400 :
2296          SwapCode = 2143;
2297          Filetype = ACR;
2298          return true;
2299       case 0x00000004 :
2300          SwapCode = 0;
2301          Filetype = ACR;
2302          return true;
2303       default :
2304          // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2305          // It is time for despaired wild guesses. 
2306          // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2307          //  i.e. the 'group length' element is not present :     
2308          
2309          //  check the supposed-to-be 'group number'
2310          //  in ( 0x0001 .. 0x0008 )
2311          //  to determine ' SwapCode' value .
2312          //  Only 0 or 4321 will be possible 
2313          //  (no oportunity to check for the formerly well known
2314          //  ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian' 
2315          //  if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -3, 4, ..., 8-) 
2316          //  the file IS NOT ACR-NEMA nor DICOM V3
2317          //  Find a trick to tell it the caller...
2318       
2319          s16 = *((uint16_t *)(deb));
2320       
2321          switch ( s16 )
2322          {
2323             case 0x0001 :
2324             case 0x0002 :
2325             case 0x0003 :
2326             case 0x0004 :
2327             case 0x0005 :
2328             case 0x0006 :
2329             case 0x0007 :
2330             case 0x0008 :
2331                SwapCode = 0;
2332                Filetype = ACR;
2333                return true;
2334             case 0x0100 :
2335             case 0x0200 :
2336             case 0x0300 :
2337             case 0x0400 :
2338             case 0x0500 :
2339             case 0x0600 :
2340             case 0x0700 :
2341             case 0x0800 :
2342                SwapCode = 4321;
2343                Filetype = ACR;
2344                return true;
2345             default :
2346                gdcmVerboseMacro( "ACR/NEMA unfound swap info (Really hopeless !)");
2347                Filetype = Unknown;
2348                return false;
2349          }
2350          // Then the only info we have is the net2host one.
2351          //if (! net2host )
2352          //   SwapCode = 0;
2353          //else
2354          //  SwapCode = 4321;
2355          //return;
2356    }
2357 }
2358
2359
2360
2361 /**
2362  * \brief Restore the unproperly loaded values i.e. the group, the element
2363  *        and the dictionary entry depending on them. 
2364  */
2365 void Document::SwitchSwapToBigEndian() 
2366 {
2367    gdcmVerboseMacro( "Switching to BigEndian mode.");
2368    if ( SwapCode == 0    ) 
2369    {
2370       SwapCode = 4321;
2371    }
2372    else if ( SwapCode == 4321 ) 
2373    {
2374       SwapCode = 0;
2375    }
2376    else if ( SwapCode == 3412 ) 
2377    {
2378       SwapCode = 2143;
2379    }
2380    else if ( SwapCode == 2143 )
2381    {
2382       SwapCode = 3412;
2383    }
2384 }
2385
2386 /**
2387  * \brief  during parsing, Header Elements too long are not loaded in memory 
2388  * @param newSize
2389  */
2390 void Document::SetMaxSizeLoadEntry(long newSize) 
2391 {
2392    if ( newSize < 0 )
2393    {
2394       return;
2395    }
2396    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2397    {
2398       MaxSizeLoadEntry = 0xffffffff;
2399       return;
2400    }
2401    MaxSizeLoadEntry = newSize;
2402 }
2403
2404
2405 /**
2406  * \brief Header Elements too long will not be printed
2407  * \todo  See comments of \ref Document::MAX_SIZE_PRINT_ELEMENT_VALUE 
2408  * @param newSize
2409  */
2410 void Document::SetMaxSizePrintEntry(long newSize) 
2411 {
2412    //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2413    if ( newSize < 0 )
2414    {
2415       return;
2416    }
2417    if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2418    {
2419       MaxSizePrintEntry = 0xffffffff;
2420       return;
2421    }
2422    MaxSizePrintEntry = newSize;
2423 }
2424
2425
2426
2427 /**
2428  * \brief   Handle broken private tag from Philips NTSCAN
2429  *          where the endianess is being switch to BigEndian for no
2430  *          apparent reason
2431  * @return  no return
2432  */
2433 void Document::HandleBrokenEndian(uint16_t group, uint16_t elem)
2434 {
2435    // Endian reversion. Some files contain groups of tags with reversed endianess.
2436    static int reversedEndian = 0;
2437    // try to fix endian switching in the middle of headers
2438    if ((group == 0xfeff) && (elem == 0x00e0))
2439    {
2440      // start endian swap mark for group found
2441      reversedEndian++;
2442      SwitchSwapToBigEndian();
2443      // fix the tag
2444      group = 0xfffe;
2445      elem = 0xe000;
2446    } 
2447    else if (group == 0xfffe && elem == 0xe00d && reversedEndian) 
2448    {
2449      // end of reversed endian group
2450      reversedEndian--;
2451      SwitchSwapToBigEndian();
2452    }
2453 }
2454
2455 /**
2456  * \brief   Read the next tag but WITHOUT loading it's value
2457  *          (read the 'Group Number', the 'Element Number',
2458  *           gets the Dict Entry
2459  *          gets the VR, gets the length, gets the offset value)
2460  * @return  On succes the newly created DocEntry, NULL on failure.      
2461  */
2462 DocEntry *Document::ReadNextDocEntry()
2463 {
2464    uint16_t group;
2465    uint16_t elem;
2466
2467    try
2468    {
2469       group = ReadInt16();
2470       elem  = ReadInt16();
2471    }
2472    catch ( FormatError e )
2473    {
2474       // We reached the EOF (or an error occured) therefore 
2475       // header parsing has to be considered as finished.
2476       //std::cout << e;
2477       return 0;
2478    }
2479
2480    HandleBrokenEndian(group, elem);
2481    std::string vr = FindDocEntryVR();
2482    std::string realVR = vr;
2483
2484    if( vr == GDCM_UNKNOWN)
2485    {
2486       DictEntry *dictEntry = GetDictEntry(group,elem);
2487       if( dictEntry )
2488          realVR = dictEntry->GetVR();
2489    }
2490
2491    DocEntry *newEntry;
2492    if( Global::GetVR()->IsVROfSequence(realVR) )
2493       newEntry = NewSeqEntry(group, elem);
2494    else if( Global::GetVR()->IsVROfStringRepresentable(realVR) )
2495       newEntry = NewValEntry(group, elem,vr);
2496    else
2497       newEntry = NewBinEntry(group, elem,vr);
2498
2499    if( vr == GDCM_UNKNOWN )
2500    {
2501       if( Filetype == ExplicitVR )
2502       {
2503          // We thought this was explicit VR, but we end up with an
2504          // implicit VR tag. Let's backtrack.   
2505          std::string msg;
2506          msg = Util::Format("Falsely explicit vr file (%04x,%04x)\n", 
2507                        newEntry->GetGroup(), newEntry->GetElement());
2508          gdcmVerboseMacro( msg.c_str() );
2509       }
2510       newEntry->SetImplicitVR();
2511    }
2512
2513    try
2514    {
2515       FindDocEntryLength(newEntry);
2516    }
2517    catch ( FormatError e )
2518    {
2519       // Call it quits
2520       //std::cout << e;
2521       delete newEntry;
2522       return 0;
2523    }
2524
2525    newEntry->SetOffset(Fp->tellg());  
2526
2527    return newEntry;
2528 }
2529
2530
2531 /**
2532  * \brief   Generate a free TagKey i.e. a TagKey that is not present
2533  *          in the TagHt dictionary.
2534  * @param   group The generated tag must belong to this group.  
2535  * @return  The element of tag with given group which is fee.
2536  */
2537 uint32_t Document::GenerateFreeTagKeyInGroup(uint16_t group) 
2538 {
2539    for (uint32_t elem = 0; elem < UINT32_MAX; elem++) 
2540    {
2541       TagKey key = DictEntry::TranslateToKey(group, elem);
2542       if (TagHT.count(key) == 0)
2543       {
2544          return elem;
2545       }
2546    }
2547    return UINT32_MAX;
2548 }
2549
2550 /**
2551  * \brief   Assuming the internal file pointer \ref Document::Fp 
2552  *          is placed at the beginning of a tag check whether this
2553  *          tag is (TestGroup, TestElement).
2554  * \warning On success the internal file pointer \ref Document::Fp
2555  *          is modified to point after the tag.
2556  *          On failure (i.e. when the tag wasn't the expected tag
2557  *          (TestGroup, TestElement) the internal file pointer
2558  *          \ref Document::Fp is restored to it's original position.
2559  * @param   testGroup   The expected group of the tag.
2560  * @param   testElement The expected Element of the tag.
2561  * @return  True on success, false otherwise.
2562  */
2563 bool Document::ReadTag(uint16_t testGroup, uint16_t testElement)
2564 {
2565    long positionOnEntry = Fp->tellg();
2566    long currentPosition = Fp->tellg();          // On debugging purposes
2567
2568    //// Read the Item Tag group and element, and make
2569    // sure they are what we expected:
2570    uint16_t itemTagGroup;
2571    uint16_t itemTagElement;
2572    try
2573    {
2574       itemTagGroup   = ReadInt16();
2575       itemTagElement = ReadInt16();
2576    }
2577    catch ( FormatError e )
2578    {
2579       //std::cerr << e << std::endl;
2580       return false;
2581    }
2582    if ( itemTagGroup != testGroup || itemTagElement != testElement )
2583    {
2584       gdcmVerboseMacro( "Wrong Item Tag found:"
2585        << "   We should have found tag ("
2586        << std::hex << testGroup << "," << testElement << ")" << std::endl
2587        << "   but instead we encountered tag ("
2588        << std::hex << itemTagGroup << "," << itemTagElement << ")"
2589        << std::dec
2590        << "  at address: " << (unsigned int)currentPosition );
2591       Fp->seekg(positionOnEntry, std::ios::beg);
2592
2593       return false;
2594    }
2595    return true;
2596 }
2597
2598 /**
2599  * \brief   Assuming the internal file pointer \ref Document::Fp 
2600  *          is placed at the beginning of a tag (TestGroup, TestElement),
2601  *          read the length associated to the Tag.
2602  * \warning On success the internal file pointer \ref Document::Fp
2603  *          is modified to point after the tag and it's length.
2604  *          On failure (i.e. when the tag wasn't the expected tag
2605  *          (TestGroup, TestElement) the internal file pointer
2606  *          \ref Document::Fp is restored to it's original position.
2607  * @param   testGroup   The expected group of the tag.
2608  * @param   testElement The expected Element of the tag.
2609  * @return  On success returns the length associated to the tag. On failure
2610  *          returns 0.
2611  */
2612 uint32_t Document::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2613 {
2614    long positionOnEntry = Fp->tellg();
2615    (void)positionOnEntry;
2616
2617    if ( !ReadTag(testGroup, testElement) )
2618    {
2619       return 0;
2620    }
2621                                                                                 
2622    //// Then read the associated Item Length
2623    long currentPosition = Fp->tellg();
2624    uint32_t itemLength  = ReadInt32();
2625    {
2626       gdcmVerboseMacro( "Basic Item Length is: "
2627         << itemLength << std::endl
2628         << "  at address: " << (unsigned int)currentPosition);
2629    }
2630    return itemLength;
2631 }
2632
2633 /**
2634  * \brief When parsing the Pixel Data of an encapsulated file, read
2635  *        the basic offset table (when present, and BTW dump it).
2636  */
2637 void Document::ReadAndSkipEncapsulatedBasicOffsetTable()
2638 {
2639    //// Read the Basic Offset Table Item Tag length...
2640    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2641
2642    // When present, read the basic offset table itself.
2643    // Notes: - since the presence of this basic offset table is optional
2644    //          we can't rely on it for the implementation, and we will simply
2645    //          trash it's content (when present).
2646    //        - still, when present, we could add some further checks on the
2647    //          lengths, but we won't bother with such fuses for the time being.
2648    if ( itemLength != 0 )
2649    {
2650       char *basicOffsetTableItemValue = new char[itemLength + 1];
2651       Fp->read(basicOffsetTableItemValue, itemLength);
2652
2653 #ifdef GDCM_DEBUG
2654       for (unsigned int i=0; i < itemLength; i += 4 )
2655       {
2656          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
2657                                               uint32_t);
2658          gdcmVerboseMacro( "Read one length: " << 
2659                           std::hex << individualLength );
2660       }
2661 #endif //GDCM_DEBUG
2662
2663       delete[] basicOffsetTableItemValue;
2664    }
2665 }
2666
2667 /**
2668  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
2669  *        Compute the RLE extra information and store it in \ref RLEInfo
2670  *        for later pixel retrieval usage.
2671  */
2672 void Document::ComputeRLEInfo()
2673 {
2674    TransferSyntaxType ts = GetTransferSyntax();
2675    if ( ts != RLELossless )
2676    {
2677       return;
2678    }
2679
2680    // Encoded pixel data: for the time being we are only concerned with
2681    // Jpeg or RLE Pixel data encodings.
2682    // As stated in PS 3.5-2003, section 8.2 p44:
2683    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
2684    //  value representation OB is used".
2685    // Hence we expect an OB value representation. Concerning OB VR,
2686    // the section PS 3.5-2003, section A.4.c p 58-59, states:
2687    // "For the Value Representations OB and OW, the encoding shall meet the
2688    //   following specifications depending on the Data element tag:"
2689    //   [...snip...]
2690    //    - the first item in the sequence of items before the encoded pixel
2691    //      data stream shall be basic offset table item. The basic offset table
2692    //      item value, however, is not required to be present"
2693
2694    ReadAndSkipEncapsulatedBasicOffsetTable();
2695
2696    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
2697    // Loop on the individual frame[s] and store the information
2698    // on the RLE fragments in a RLEFramesInfo.
2699    // Note: - when only a single frame is present, this is a
2700    //         classical image.
2701    //       - when more than one frame are present, then we are in 
2702    //         the case of a multi-frame image.
2703    long frameLength;
2704    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) )
2705    { 
2706       // Parse the RLE Header and store the corresponding RLE Segment
2707       // Offset Table information on fragments of this current Frame.
2708       // Note that the fragment pixels themselves are not loaded
2709       // (but just skipped).
2710       long frameOffset = Fp->tellg();
2711
2712       uint32_t nbRleSegments = ReadInt32();
2713       if ( nbRleSegments > 16 )
2714       {
2715          // There should be at most 15 segments (refer to RLEFrame class)
2716          gdcmVerboseMacro( "Too many segments.");
2717       }
2718  
2719       uint32_t rleSegmentOffsetTable[16];
2720       for( int k = 1; k <= 15; k++ )
2721       {
2722          rleSegmentOffsetTable[k] = ReadInt32();
2723       }
2724
2725       // Deduce from both the RLE Header and the frameLength the
2726       // fragment length, and again store this info in a
2727       // RLEFramesInfo.
2728       long rleSegmentLength[15];
2729       // skipping (not reading) RLE Segments
2730       if ( nbRleSegments > 1)
2731       {
2732          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2733          {
2734              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
2735                                   - rleSegmentOffsetTable[k];
2736              SkipBytes(rleSegmentLength[k]);
2737           }
2738        }
2739
2740        rleSegmentLength[nbRleSegments] = frameLength 
2741                                       - rleSegmentOffsetTable[nbRleSegments];
2742        SkipBytes(rleSegmentLength[nbRleSegments]);
2743
2744        // Store the collected info
2745        RLEFrame *newFrameInfo = new RLEFrame;
2746        newFrameInfo->NumberFragments = nbRleSegments;
2747        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
2748        {
2749           newFrameInfo->Offset[uk] = frameOffset + rleSegmentOffsetTable[uk];
2750           newFrameInfo->Length[uk] = rleSegmentLength[uk];
2751        }
2752        RLEInfo->Frames.push_back( newFrameInfo );
2753    }
2754
2755    // Make sure that at the end of the item we encounter a 'Sequence
2756    // Delimiter Item':
2757    if ( !ReadTag(0xfffe, 0xe0dd) )
2758    {
2759       gdcmVerboseMacro( "No sequence delimiter item at end of RLE item sequence");
2760    }
2761 }
2762
2763 /**
2764  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
2765  *        Compute the jpeg extra information (fragment[s] offset[s] and
2766  *        length) and store it[them] in \ref JPEGInfo for later pixel
2767  *        retrieval usage.
2768  */
2769 void Document::ComputeJPEGFragmentInfo()
2770 {
2771    // If you need to, look for comments of ComputeRLEInfo().
2772    if ( ! IsJPEG() )
2773    {
2774       return;
2775    }
2776
2777    ReadAndSkipEncapsulatedBasicOffsetTable();
2778
2779    // Loop on the fragments[s] and store the parsed information in a
2780    // JPEGInfo.
2781    long fragmentLength;
2782    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2783    { 
2784       long fragmentOffset = Fp->tellg();
2785
2786        // Store the collected info
2787        JPEGFragment *newFragment = new JPEGFragment;
2788        newFragment->Offset = fragmentOffset;
2789        newFragment->Length = fragmentLength;
2790        JPEGInfo->Fragments.push_back( newFragment );
2791
2792        SkipBytes( fragmentLength );
2793    }
2794
2795    // Make sure that at the end of the item we encounter a 'Sequence
2796    // Delimiter Item':
2797    if ( !ReadTag(0xfffe, 0xe0dd) )
2798    {
2799       gdcmVerboseMacro( "No sequence delimiter item at end of JPEG item sequence");
2800    }
2801 }
2802
2803 /**
2804  * \brief Walk recursively the given \ref DocEntrySet, and feed
2805  *        the given hash table (\ref TagDocEntryHT) with all the
2806  *        \ref DocEntry (Dicom entries) encountered.
2807  *        This method does the job for \ref BuildFlatHashTable.
2808  * @param builtHT Where to collect all the \ref DocEntry encountered
2809  *        when recursively walking the given set.
2810  * @param set The structure to be traversed (recursively).
2811  */
2812 void Document::BuildFlatHashTableRecurse( TagDocEntryHT &builtHT,
2813                                           DocEntrySet *set )
2814
2815    if (ElementSet *elementSet = dynamic_cast< ElementSet* > ( set ) )
2816    {
2817       TagDocEntryHT const &currentHT = elementSet->GetTagHT();
2818       for( TagDocEntryHT::const_iterator i  = currentHT.begin();
2819                                          i != currentHT.end();
2820                                        ++i)
2821       {
2822          DocEntry *entry = i->second;
2823          if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2824          {
2825             const ListSQItem& items = seqEntry->GetSQItems();
2826             for( ListSQItem::const_iterator item  = items.begin();
2827                                             item != items.end();
2828                                           ++item)
2829             {
2830                BuildFlatHashTableRecurse( builtHT, *item );
2831             }
2832             continue;
2833          }
2834          builtHT[entry->GetKey()] = entry;
2835       }
2836       return;
2837     }
2838
2839    if (SQItem *SQItemSet = dynamic_cast< SQItem* > ( set ) )
2840    {
2841       const ListDocEntry& currentList = SQItemSet->GetDocEntries();
2842       for (ListDocEntry::const_iterator i  = currentList.begin();
2843                                         i != currentList.end();
2844                                       ++i)
2845       {
2846          DocEntry *entry = *i;
2847          if ( SeqEntry *seqEntry = dynamic_cast<SeqEntry*>(entry) )
2848          {
2849             const ListSQItem& items = seqEntry->GetSQItems();
2850             for( ListSQItem::const_iterator item  = items.begin();
2851                                             item != items.end();
2852                                           ++item)
2853             {
2854                BuildFlatHashTableRecurse( builtHT, *item );
2855             }
2856             continue;
2857          }
2858          builtHT[entry->GetKey()] = entry;
2859       }
2860
2861    }
2862 }
2863
2864 /**
2865  * \brief Build a \ref TagDocEntryHT (i.e. a std::map<>) from the current
2866  *        Document.
2867  *
2868  *        The structure used by a Document (through \ref ElementSet),
2869  *        in order to hold the parsed entries of a Dicom header, is a recursive
2870  *        one. This is due to the fact that the sequences (when present)
2871  *        can be nested. Additionaly, the sequence items (represented in
2872  *        gdcm as \ref SQItem) add an extra complexity to the data
2873  *        structure. Hence, a gdcm user whishing to visit all the entries of
2874  *        a Dicom header will need to dig in the gdcm internals (which
2875  *        implies exposing all the internal data structures to the API).
2876  *        In order to avoid this burden to the user, \ref BuildFlatHashTable
2877  *        recursively builds a temporary hash table, which holds all the
2878  *        Dicom entries in a flat structure (a \ref TagDocEntryHT i.e. a
2879  *        std::map<>).
2880  * \warning Of course there is NO integrity constrain between the 
2881  *        returned \ref TagDocEntryHT and the \ref ElementSet used
2882  *        to build it. Hence if the underlying \ref ElementSet is
2883  *        altered, then it is the caller responsability to invoke 
2884  *        \ref BuildFlatHashTable again...
2885  * @return The flat std::map<> we juste build.
2886  */
2887 TagDocEntryHT *Document::BuildFlatHashTable()
2888 {
2889    TagDocEntryHT *FlatHT = new TagDocEntryHT;
2890    BuildFlatHashTableRecurse( *FlatHT, this );
2891    return FlatHT;
2892 }
2893
2894
2895
2896 /**
2897  * \brief   Compares two documents, according to \ref DicomDir rules
2898  * \warning Does NOT work with ACR-NEMA files
2899  * \todo    Find a trick to solve the pb (use RET fields ?)
2900  * @param   document
2901  * @return  true if 'smaller'
2902  */
2903 bool Document::operator<(Document &document)
2904 {
2905    // Patient Name
2906    std::string s1 = GetEntry(0x0010,0x0010);
2907    std::string s2 = document.GetEntry(0x0010,0x0010);
2908    if(s1 < s2)
2909    {
2910       return true;
2911    }
2912    else if( s1 > s2 )
2913    {
2914       return false;
2915    }
2916    else
2917    {
2918       // Patient ID
2919       s1 = GetEntry(0x0010,0x0020);
2920       s2 = document.GetEntry(0x0010,0x0020);
2921       if ( s1 < s2 )
2922       {
2923          return true;
2924       }
2925       else if ( s1 > s2 )
2926       {
2927          return false;
2928       }
2929       else
2930       {
2931          // Study Instance UID
2932          s1 = GetEntry(0x0020,0x000d);
2933          s2 = document.GetEntry(0x0020,0x000d);
2934          if ( s1 < s2 )
2935          {
2936             return true;
2937          }
2938          else if( s1 > s2 )
2939          {
2940             return false;
2941          }
2942          else
2943          {
2944             // Serie Instance UID
2945             s1 = GetEntry(0x0020,0x000e);
2946             s2 = document.GetEntry(0x0020,0x000e);    
2947             if ( s1 < s2 )
2948             {
2949                return true;
2950             }
2951             else if( s1 > s2 )
2952             {
2953                return false;
2954             }
2955          }
2956       }
2957    }
2958    return false;
2959 }
2960
2961
2962 /**
2963  * \brief   Re-computes the length of a ACR-NEMA/Dicom group from a DcmHeader
2964  * @param filetype Type of the File to be written 
2965  */
2966 int Document::ComputeGroup0002Length( FileType filetype ) 
2967 {
2968    uint16_t gr, el;
2969    std::string vr;
2970    
2971    int groupLength = 0;
2972    bool found0002 = false;   
2973   
2974    // for each zero-level Tag in the DCM Header
2975    DocEntry *entry;
2976
2977    Initialize();
2978    entry = GetNextEntry();
2979    while(entry)
2980    {
2981       gr = entry->GetGroup();
2982
2983       if (gr == 0x0002)
2984       {
2985          found0002 = true;
2986
2987          el = entry->GetElement();
2988          vr = entry->GetVR();            
2989  
2990          if (filetype == ExplicitVR) 
2991          {
2992             if ( (vr == "OB") || (vr == "OW") || (vr == "SQ") ) 
2993             {
2994                groupLength +=  4; // explicit VR AND OB, OW, SQ : 4 more bytes
2995             }
2996          }
2997          groupLength += 2 + 2 + 4 + entry->GetLength();   
2998       }
2999       else if (found0002 )
3000          break;
3001
3002       entry = GetNextEntry();
3003    }
3004    return groupLength; 
3005 }
3006
3007 } // end namespace gdcm
3008
3009 //-----------------------------------------------------------------------------