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