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