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