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