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