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