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