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