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