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