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