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