1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/09/13 07:49:36 $
7 Version: $Revision: 1.75 $
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.htm for details.
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.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
34 #include <netinet/in.h>
39 // Implicit VR Little Endian
40 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
41 // Explicit VR Little Endian
42 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
43 // Deflated Explicit VR Little Endian
44 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
45 // Explicit VR Big Endian
46 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
47 // JPEG Baseline (Process 1)
48 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
49 // JPEG Extended (Process 2 & 4)
50 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
51 // JPEG Extended (Process 3 & 5)
52 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
53 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
54 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
55 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
56 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
57 // JPEG Lossless, Non-Hierarchical (Process 14)
58 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
59 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
60 // [Selection Value 1])
61 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
63 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
65 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
67 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
68 // UI1_1_2_840_10008_1_2_5
69 #define str2num(str, typeNum) *((typeNum *)(str))
71 //-----------------------------------------------------------------------------
72 // Refer to gdcmDocument::CheckSwap()
73 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
75 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
76 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 0xfff; // 4096
77 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 0x7fffffff;
79 //-----------------------------------------------------------------------------
80 // Constructor / Destructor
84 * @param filename file to be opened for parsing
86 gdcmDocument::gdcmDocument( std::string const & filename )
89 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
98 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
102 fseek(Fp,0L,SEEK_END);
103 long lgt = ftell(Fp);
107 long beg = ftell(Fp);
112 long l = ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
113 (void)l; //is l used anywhere ?
117 // Load 'non string' values
119 std::string PhotometricInterpretation = GetEntryByNumber(0x0028,0x0004);
120 if( PhotometricInterpretation == "PALETTE COLOR " )
122 LoadEntryVoidArea(0x0028,0x1200); // gray LUT
123 LoadEntryVoidArea(0x0028,0x1201); // R LUT
124 LoadEntryVoidArea(0x0028,0x1202); // G LUT
125 LoadEntryVoidArea(0x0028,0x1203); // B LUT
127 LoadEntryVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
128 LoadEntryVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
129 LoadEntryVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
131 //FIXME later : how to use it?
132 LoadEntryVoidArea(0x0028,0x3006); //LUT Data (CTX dependent)
136 // --------------------------------------------------------------
137 // Specific code to allow gdcm to read ACR-LibIDO formated images
138 // Note: ACR-LibIDO is an extension of the ACR standard that was
139 // used at CREATIS. For the time being (say a couple years)
140 // we keep this kludge to allow a smooth move to gdcm for
141 // CREATIS developpers (sorry folks).
143 // if recognition code tells us we deal with a LibIDO image
144 // we switch lineNumber and columnNumber
147 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
148 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
149 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
150 // with "little-endian strings"
152 Filetype = gdcmACR_LIBIDO;
153 std::string rows = GetEntryByNumber(0x0028, 0x0010);
154 std::string columns = GetEntryByNumber(0x0028, 0x0011);
155 SetEntryByNumber(columns, 0x0028, 0x0010);
156 SetEntryByNumber(rows , 0x0028, 0x0011);
158 // ----------------- End of ACR-LibIDO kludge ------------------
160 PrintLevel = 1; // 'Medium' print level by default
164 * \brief This default constructor doesn't parse the file. You should
165 * then invoke \ref gdcmDocument::SetFileName and then the parsing.
167 gdcmDocument::gdcmDocument()
170 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
172 PrintLevel = 1; // 'Medium' print level by default
176 * \brief Canonical destructor.
178 gdcmDocument::~gdcmDocument ()
183 // Recursive clean up of sequences
184 for (TagDocEntryHT::const_iterator it = TagHT.begin();
185 it != TagHT.end(); ++it )
192 //-----------------------------------------------------------------------------
196 * \brief Prints The Dict Entries of THE public Dicom Dictionary
199 void gdcmDocument::PrintPubDict(std::ostream & os)
201 RefPubDict->Print(os);
205 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
208 void gdcmDocument::PrintShaDict(std::ostream & os)
210 RefShaDict->Print(os);
213 //-----------------------------------------------------------------------------
216 * \brief Get the public dictionary used
218 gdcmDict *gdcmDocument::GetPubDict()
224 * \brief Get the shadow dictionary used
226 gdcmDict *gdcmDocument::GetShaDict()
232 * \brief Set the shadow dictionary used
233 * \param dict dictionary to use in shadow
235 bool gdcmDocument::SetShaDict(gdcmDict *dict)
242 * \brief Set the shadow dictionary used
243 * \param dictName name of the dictionary to use in shadow
245 bool gdcmDocument::SetShaDict(DictKey const & dictName)
247 RefShaDict = gdcmGlobal::GetDicts()->GetDict(dictName);
252 * \brief This predicate, based on hopefully reasonable heuristics,
253 * decides whether or not the current gdcmDocument was properly parsed
254 * and contains the mandatory information for being considered as
255 * a well formed and usable Dicom/Acr File.
256 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
259 bool gdcmDocument::IsReadable()
261 if( Filetype == gdcmUnknown)
263 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
269 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
279 * \brief Internal function that checks whether the Transfer Syntax given
280 * as argument is the one present in the current document.
281 * @param syntaxToCheck The transfert syntax we need to check against.
282 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
283 * the current document. False either when the document contains
284 * no Transfer Syntax, or when the Tranfer Syntaxes doesn't match.
286 bool gdcmDocument::IsGivenTransferSyntax(std::string const & syntaxToCheck)
288 gdcmDocEntry *entry = GetDocEntryByNumber(0x0002, 0x0010);
294 // The entry might be present but not loaded (parsing and loading
295 // happen at different stages): try loading and proceed with check...
296 LoadDocEntrySafe(entry);
297 if (gdcmValEntry* valEntry = dynamic_cast< gdcmValEntry* >(entry) )
299 std::string transfer = valEntry->GetValue();
300 // The actual transfer (as read from disk) might be padded. We
301 // first need to remove the potential padding. We can make the
302 // weak assumption that padding was not executed with digits...
303 if ( transfer.length() == 0 ) { // for brain damaged headers
306 while ( ! isdigit(transfer[transfer.length()-1]) )
308 transfer.erase(transfer.length()-1, 1);
310 if ( transfer == syntaxToCheck )
319 * \brief Determines if the Transfer Syntax of the present document
320 * corresponds to a Implicit Value Representation of
322 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
323 * @return True when ImplicitVRLittleEndian found. False in all other cases.
325 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax()
327 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
331 * \brief Determines if the Transfer Syntax was already encountered
332 * and if it corresponds to a ExplicitVRLittleEndian one.
333 * @return True when ExplicitVRLittleEndian found. False in all other cases.
335 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax()
337 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
341 * \brief Determines if the Transfer Syntax was already encountered
342 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
343 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
345 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax()
347 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
351 * \brief Determines if the Transfer Syntax was already encountered
352 * and if it corresponds to a Explicit VR Big Endian one.
353 * @return True when big endian found. False in all other cases.
355 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax()
357 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
361 * \brief Determines if the Transfer Syntax was already encountered
362 * and if it corresponds to a JPEGBaseLineProcess1 one.
363 * @return True when JPEGBaseLineProcess1found. False in all other cases.
365 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax()
367 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
371 * \brief Determines if the Transfer Syntax was already encountered
372 * and if it corresponds to a JPEGExtendedProcess2-4 one.
373 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
375 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax()
377 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
381 * \brief Determines if the Transfer Syntax was already encountered
382 * and if it corresponds to a JPEGExtendeProcess3-5 one.
383 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
385 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax()
387 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
391 * \brief Determines if the Transfer Syntax was already encountered
392 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
393 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
396 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax()
398 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
402 * \brief Determines if the Transfer Syntax was already encountered
403 * and if it corresponds to a RLE Lossless one.
404 * @return True when RLE Lossless found. False in all
407 bool gdcmDocument::IsRLELossLessTransferSyntax()
409 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
413 * \brief Determines if Transfer Syntax was already encountered
414 * and if it corresponds to a JPEG Lossless one.
415 * @return True when RLE Lossless found. False in all
419 bool gdcmDocument::IsJPEGLossless()
421 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
422 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
423 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_70) );
427 * \brief Determines if the Transfer Syntax was already encountered
428 * and if it corresponds to a JPEG2000 one
429 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
432 bool gdcmDocument::IsJPEG2000()
434 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
435 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
439 * \brief Predicate for dicom version 3 file.
440 * @return True when the file is a dicom version 3.
442 bool gdcmDocument::IsDicomV3()
444 // Checking if Transfert Syntax exists is enough
445 // Anyway, it's to late check if the 'Preamble' was found ...
446 // And ... would it be a rich idea to check ?
447 // (some 'no Preamble' DICOM images exist !)
448 return GetDocEntryByNumber(0x0002, 0x0010) != NULL;
452 * \brief returns the File Type
453 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
454 * @return the FileType code
456 FileType gdcmDocument::GetFileType()
462 * \brief Tries to open the file \ref gdcmDocument::Filename and
463 * checks the preamble when existing.
464 * @return The FILE pointer on success.
466 FILE* gdcmDocument::OpenFile()
468 Fp = fopen(Filename.c_str(),"rb");
473 "gdcmDocument::OpenFile cannot open file: ",
479 fread(&zero, (size_t)2, (size_t)1, Fp);
481 //ACR -- or DICOM with no Preamble --
482 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200 )
488 fseek(Fp, 126L, SEEK_CUR);
490 fread(dicm, (size_t)4, (size_t)1, Fp);
491 if( memcmp(dicm, "DICM", 4) == 0 )
498 "gdcmDocument::OpenFile not DICOM/ACR (missing preamble)",
505 * \brief closes the file
506 * @return TRUE if the close was successfull
508 bool gdcmDocument::CloseFile()
510 int closed = fclose(Fp);
517 * \brief Writes in a file all the Header Entries (Dicom Elements)
518 * @param fp file pointer on an already open file
519 * @param filetype Type of the File to be written
520 * (ACR-NEMA, ExplicitVR, ImplicitVR)
521 * \return Always true.
523 void gdcmDocument::Write(FILE* fp,FileType filetype)
525 /// \todo move the following lines (and a lot of others, to be written)
526 /// to a future function CheckAndCorrectHeader
528 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
529 /// no way (check : FileType est un champ de gdcmDocument ...)
530 /// a moins de se livrer a un tres complique ajout des champs manquants.
531 /// faire un CheckAndCorrectHeader (?)
533 if (filetype == gdcmImplicitVR)
535 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
536 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
538 /// \todo Refer to standards on page 21, chapter 6.2
539 /// "Value representation": values with a VR of UI shall be
540 /// padded with a single trailing null
541 /// in the following case we have to padd manually with a 0
543 SetEntryLengthByNumber(18, 0x0002, 0x0010);
546 if (filetype == gdcmExplicitVR)
548 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
549 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
551 /// \todo Refer to standards on page 21, chapter 6.2
552 /// "Value representation": values with a VR of UI shall be
553 /// padded with a single trailing null
554 /// Dans le cas suivant on doit pader manuellement avec un 0
556 SetEntryLengthByNumber(20, 0x0002, 0x0010);
560 * \todo rewrite later, if really usefull
561 * - 'Group Length' element is optional in DICOM
562 * - but un-updated odd groups lengthes can causes pb
565 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
566 * UpdateGroupLength(false,filetype);
567 * if ( filetype == ACR)
568 * UpdateGroupLength(true,ACR);
571 gdcmElementSet::Write(fp, filetype); // This one is recursive
576 * \brief Modifies the value of a given Header Entry (Dicom Element)
577 * when it exists. Create it with the given value when unexistant.
578 * @param value (string) Value to be set
579 * @param group Group number of the Entry
580 * @param elem Element number of the Entry
581 * \return pointer to the modified/created Header Entry (NULL when creation
585 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
586 std::string const & value,
590 gdcmValEntry* valEntry = 0;
591 gdcmDocEntry* currentEntry = GetDocEntryByNumber( group, elem);
595 // The entry wasn't present and we simply create the required ValEntry:
596 currentEntry = NewDocEntryByNumber(group, elem);
599 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
600 " NewDocEntryByNumber failed.");
603 valEntry = new gdcmValEntry(currentEntry);
604 if ( !AddEntry(valEntry))
606 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
607 " failed allthough this is a creation.");
612 valEntry = dynamic_cast< gdcmValEntry* >(currentEntry);
613 if ( !valEntry ) // Euuuuh? It wasn't a ValEntry
614 // then we change it to a ValEntry ?
615 // Shouldn't it be considered as an error ?
617 // We need to promote the gdcmDocEntry to a gdcmValEntry:
618 valEntry = new gdcmValEntry(currentEntry);
619 if (!RemoveEntry(currentEntry))
621 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
622 " of previous DocEntry failed.");
625 if ( !AddEntry(valEntry))
627 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
628 " promoted ValEntry failed.");
634 SetEntryByNumber(value, group, elem);
640 * \brief Modifies the value of a given Header Entry (Dicom Element)
641 * when it exists. Create it with the given value when unexistant.
642 * @param voidArea (binary) value to be set
643 * @param Group Group number of the Entry
644 * @param Elem Element number of the Entry
645 * \return pointer to the modified/created Header Entry (NULL when creation
648 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
655 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
658 a = NewBinEntryByNumber(group, elem);
664 b = new gdcmBinEntry(a);
666 b->SetVoidArea(voidArea);
669 SetEntryByNumber(voidArea, lgth, group, elem);
670 //b->SetVoidArea(voidArea); //what if b == 0 !!
677 * \brief Modifies the value of a given Header Entry (Dicom Element)
678 * when it exists. Create it when unexistant.
679 * @param Group Group number of the Entry
680 * @param Elem Element number of the Entry
681 * \return pointer to the modified/created SeqEntry (NULL when creation
684 gdcmSeqEntry * gdcmDocument::ReplaceOrCreateByNumber(
689 gdcmDocEntry* a = GetDocEntryByNumber( group, elem);
692 a = NewSeqEntryByNumber(group, elem);
698 b = new gdcmSeqEntry(a, 1); // FIXME : 1 (Depth)
705 * \brief Set a new value if the invoked element exists
706 * Seems to be useless !!!
707 * @param value new element value
708 * @param group group number of the Entry
709 * @param elem element number of the Entry
712 bool gdcmDocument::ReplaceIfExistByNumber(std::string const & value,
713 uint16_t group, uint16_t elem )
715 SetEntryByNumber(value, group, elem);
720 //-----------------------------------------------------------------------------
724 * \brief Checks if a given Dicom Element exists within the H table
725 * @param group Group number of the searched Dicom Element
726 * @param element Element number of the searched Dicom Element
727 * @return true is found
729 bool gdcmDocument::CheckIfEntryExistByNumber(uint16_t group, uint16_t element )
731 const std::string &key = gdcmDictEntry::TranslateToKey(group, element );
732 return TagHT.count(key);
736 * \brief Searches within Header Entries (Dicom Elements) parsed with
737 * the public and private dictionaries
738 * for the element value of a given tag.
739 * \warning Don't use any longer : use GetPubEntryByName
740 * @param tagName name of the searched element.
741 * @return Corresponding element value when it exists,
742 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
744 std::string gdcmDocument::GetEntryByName(TagName const & tagName)
746 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
752 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
756 * \brief Searches within Header Entries (Dicom Elements) parsed with
757 * the public and private dictionaries
758 * for the element value representation of a given tag.
760 * Obtaining the VR (Value Representation) might be needed by caller
761 * to convert the string typed content to caller's native type
762 * (think of C++ vs Python). The VR is actually of a higher level
763 * of semantics than just the native C++ type.
764 * @param tagName name of the searched element.
765 * @return Corresponding element value representation when it exists,
766 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
768 std::string gdcmDocument::GetEntryVRByName(TagName const & tagName)
770 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
771 if( dictEntry == NULL)
776 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
777 dictEntry->GetElement());
778 return elem->GetVR();
783 * \brief Searches within Header Entries (Dicom Elements) parsed with
784 * the public and private dictionaries
785 * for the element value representation of a given tag.
786 * @param group Group number of the searched tag.
787 * @param element Element number of the searched tag.
788 * @return Corresponding element value representation when it exists,
789 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
791 std::string gdcmDocument::GetEntryByNumber(uint16_t group, uint16_t element)
793 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
794 /// \todo use map methods, instead of multimap JPR
795 if ( !TagHT.count(key))
800 return ((gdcmValEntry *)TagHT.find(key)->second)->GetValue();
804 * \brief Searches within Header Entries (Dicom Elements) parsed with
805 * the public and private dictionaries
806 * for the element value representation of a given tag..
808 * Obtaining the VR (Value Representation) might be needed by caller
809 * to convert the string typed content to caller's native type
810 * (think of C++ vs Python). The VR is actually of a higher level
811 * of semantics than just the native C++ type.
812 * @param group Group number of the searched tag.
813 * @param element Element number of the searched tag.
814 * @return Corresponding element value representation when it exists,
815 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
817 std::string gdcmDocument::GetEntryVRByNumber(uint16_t group, uint16_t element)
819 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
824 return elem->GetVR();
828 * \brief Searches within Header Entries (Dicom Elements) parsed with
829 * the public and private dictionaries
830 * for the value length of a given tag..
831 * @param group Group number of the searched tag.
832 * @param element Element number of the searched tag.
833 * @return Corresponding element length; -2 if not found
835 int gdcmDocument::GetEntryLengthByNumber(uint16_t group, uint16_t element)
837 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
840 return -2; //magic number
842 return elem->GetLength();
845 * \brief Sets the value (string) of the Header Entry (Dicom Element)
846 * @param content string value of the Dicom Element
847 * @param tagName name of the searched Dicom Element.
848 * @return true when found
850 bool gdcmDocument::SetEntryByName(std::string const & content,std::string const & tagName)
852 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
858 return SetEntryByNumber(content,dictEntry->GetGroup(),
859 dictEntry->GetElement());
863 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
864 * through it's (group, element) and modifies it's content with
866 * @param content new value (string) to substitute with
867 * @param group group number of the Dicom Element to modify
868 * @param element element number of the Dicom Element to modify
870 bool gdcmDocument::SetEntryByNumber(std::string const & content,
877 gdcmValEntry* valEntry = GetValEntryByNumber(group, element);
880 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
881 " ValEntry (try promotion first).");
884 // Non even content must be padded with a space (020H)...
885 std::string finalContent = content;
886 if( finalContent.length() % 2 )
888 finalContent += '\0'; // ... therefore we padd with (000H) .!?!
890 valEntry->SetValue(finalContent);
892 // Integers have a special treatement for their length:
894 l = finalContent.length();
895 if ( l != 0) // To avoid to be cheated by 'zero length' integers
897 gdcmVRKey vr = valEntry->GetVR();
898 if( vr == "US" || vr == "SS" )
900 c = CountSubstring(content, "\\") + 1; // for multivaluated items
903 else if( vr == "UL" || vr == "SL" )
905 c = CountSubstring(content, "\\") + 1; // for multivaluated items
909 valEntry->SetLength(l);
914 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
915 * through it's (group, element) and modifies it's content with
917 * @param content new value (void *) to substitute with
918 * @param lgth new value length
919 * @param group group number of the Dicom Element to modify
920 * @param element element number of the Dicom Element to modify
922 bool gdcmDocument::SetEntryByNumber(void *content,
927 (void)lgth; //not used
928 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
929 if ( !TagHT.count(key))
934 /* Hope Binary field length is *never* wrong
935 if(lgth%2) // Non even length are padded with a space (020H).
938 //content = content + '\0'; // fing a trick to enlarge a binary field?
941 gdcmBinEntry* a = (gdcmBinEntry *)TagHT[key];
942 a->SetVoidArea(content);
949 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
950 * in the PubDocEntrySet of this instance
951 * through it's (group, element) and modifies it's length with
953 * \warning Use with extreme caution.
954 * @param l new length to substitute with
955 * @param group group number of the Entry to modify
956 * @param element element number of the Entry to modify
957 * @return true on success, false otherwise.
959 bool gdcmDocument::SetEntryLengthByNumber(uint32_t l,
963 /// \todo use map methods, instead of multimap JPR
964 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
965 if ( !TagHT.count(key) )
971 l++; // length must be even
973 ( ((TagHT.equal_range(key)).first)->second )->SetLength(l);
979 * \brief Gets (from Header) the offset of a 'non string' element value
980 * (LoadElementValues has already be executed)
981 * @param group group number of the Entry
982 * @param elem element number of the Entry
983 * @return File Offset of the Element Value
985 size_t gdcmDocument::GetEntryOffsetByNumber(uint16_t group, uint16_t elem)
987 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
990 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
993 return entry->GetOffset();
997 * \brief Gets (from Header) a 'non string' element value
998 * (LoadElementValues has already be executed)
999 * @param group group number of the Entry
1000 * @param elem element number of the Entry
1001 * @return Pointer to the 'non string' area
1003 void * gdcmDocument::GetEntryVoidAreaByNumber(uint16_t group, uint16_t elem)
1005 gdcmDocEntry* entry = GetDocEntryByNumber(group, elem);
1008 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
1011 return ((gdcmBinEntry *)entry)->GetVoidArea();
1015 * \brief Loads (from disk) the element content
1016 * when a string is not suitable
1017 * @param group group number of the Entry
1018 * @param elem element number of the Entry
1020 void *gdcmDocument::LoadEntryVoidArea(uint16_t group, uint16_t elem)
1022 gdcmDocEntry *docElement = GetDocEntryByNumber(group, elem);
1027 size_t o =(size_t)docElement->GetOffset();
1028 fseek(Fp, o, SEEK_SET);
1029 size_t l = docElement->GetLength();
1030 char* a = new char[l];
1033 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1036 size_t l2 = fread(a, 1, l , Fp);
1042 /// \TODO Drop any already existing void area! JPR
1043 SetEntryVoidAreaByNumber(a, group, elem);
1048 * \brief Loads (from disk) the element content
1049 * when a string is not suitable
1050 * @param element Entry whose voidArea is going to be loaded
1052 void *gdcmDocument::LoadEntryVoidArea(gdcmBinEntry *element)
1054 size_t o =(size_t)element->GetOffset();
1055 fseek(Fp, o, SEEK_SET);
1056 size_t l = element->GetLength();
1057 char* a = new char[l];
1060 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
1063 element->SetVoidArea((void *)a);
1064 /// \todo check the result
1065 size_t l2 = fread(a, 1, l , Fp);
1076 * \brief Sets a 'non string' value to a given Dicom Element
1077 * @param area area containing the 'non string' value
1078 * @param group Group number of the searched Dicom Element
1079 * @param element Element number of the searched Dicom Element
1082 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
1086 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1087 if ( !TagHT.count(key))
1092 // This was for multimap ?
1093 (( gdcmBinEntry *)( ((TagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
1099 * \brief Update the entries with the shadow dictionary.
1100 * Only non even entries are analyzed
1102 void gdcmDocument::UpdateShaEntries()
1104 //gdcmDictEntry *entry;
1107 /// \todo TODO : still any use to explore recursively the whole structure?
1109 for(ListTag::iterator it=listEntries.begin();
1110 it!=listEntries.end();
1113 // Odd group => from public dictionary
1114 if((*it)->GetGroup()%2==0)
1117 // Peer group => search the corresponding dict entry
1119 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
1123 if((*it)->IsImplicitVR())
1128 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1130 // Set the new entry and the new value
1131 (*it)->SetDictEntry(entry);
1132 CheckDocEntryVR(*it,vr);
1134 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1139 // Remove precedent value transformation
1140 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1147 * \brief Searches within the Header Entries for a Dicom Element of
1149 * @param tagName name of the searched Dicom Element.
1150 * @return Corresponding Dicom Element when it exists, and NULL
1153 gdcmDocEntry* gdcmDocument::GetDocEntryByName(std::string const & tagName)
1155 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1161 return GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
1165 * \brief retrieves a Dicom Element (the first one) using (group, element)
1166 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1167 * if you think it's NOT UNIQUE, check the count number
1168 * and use iterators to retrieve ALL the Dicoms Elements within
1169 * a given couple (group, element)
1170 * @param group Group number of the searched Dicom Element
1171 * @param element Element number of the searched Dicom Element
1174 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(uint16_t group,
1177 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, element);
1178 if ( !TagHT.count(key))
1182 return TagHT.find(key)->second;
1186 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1187 * returns a result when the corresponding entry is of type
1189 * @return When present, the corresponding ValEntry.
1191 gdcmValEntry* gdcmDocument::GetValEntryByNumber(uint16_t group,
1194 gdcmDocEntry* currentEntry = GetDocEntryByNumber(group, element);
1195 if ( !currentEntry )
1199 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry*>(currentEntry) )
1203 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1209 * \brief Loads the element while preserving the current
1210 * underlying file position indicator as opposed to
1211 * to LoadDocEntry that modifies it.
1212 * @param entry Header Entry whose value shall be loaded.
1215 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry)
1217 long PositionOnEntry = ftell(Fp);
1218 LoadDocEntry(entry);
1219 fseek(Fp, PositionOnEntry, SEEK_SET);
1223 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1225 * @return The properly swaped 32 bits integer.
1227 uint32_t gdcmDocument::SwapLong(uint32_t a)
1234 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1235 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1239 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1243 a=( ((a<< 8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1246 //std::cout << "swapCode= " << SwapCode << std::endl;
1247 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1254 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1256 * @return The properly unswaped 32 bits integer.
1258 uint32_t gdcmDocument::UnswapLong(uint32_t a)
1264 * \brief Swaps the bytes so they agree with the processor order
1265 * @return The properly swaped 16 bits integer.
1267 uint16_t gdcmDocument::SwapShort(uint16_t a)
1269 if ( SwapCode == 4321 || SwapCode == 2143 )
1271 a = ((( a << 8 ) & 0x0ff00 ) | (( a >> 8 ) & 0x00ff ) );
1277 * \brief Unswaps the bytes so they agree with the processor order
1278 * @return The properly unswaped 16 bits integer.
1280 uint16_t gdcmDocument::UnswapShort(uint16_t a)
1282 return SwapShort(a);
1285 //-----------------------------------------------------------------------------
1289 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1290 * @return length of the parsed set.
1293 long gdcmDocument::ParseDES(gdcmDocEntrySet *set,
1298 gdcmDocEntry *newDocEntry = 0;
1299 gdcmValEntry *newValEntry = 0;
1300 unsigned long l = 0;
1302 int depth = set->GetDepthLevel();
1305 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1309 newDocEntry = ReadNextDocEntry( );
1315 gdcmVRKey vr = newDocEntry->GetVR();
1319 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1322 newValEntry = new gdcmValEntry(newDocEntry->GetDictEntry());
1323 newValEntry->Copy(newDocEntry);
1324 newValEntry->SetDepthLevel(depth);
1325 set->AddEntry(newValEntry);
1326 LoadDocEntry(newValEntry);
1327 if (newValEntry->IsItemDelimitor())
1331 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1338 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1340 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1341 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1342 "nor BinEntry. Probably unknown VR.");
1345 ////// BinEntry or UNKOWN VR:
1346 gdcmBinEntry *bn = new gdcmBinEntry(newDocEntry->GetDictEntry());
1347 bn->Copy(newDocEntry);
1352 if (newDocEntry->GetGroup() == 0x7fe0 &&
1353 newDocEntry->GetElement() == 0x0010 )
1355 if (newDocEntry->GetReadLength()==0xffffffff)
1357 // Broken US.3405.1.dcm
1358 Parse7FE0(); // to skip the pixels
1359 // (multipart JPEG/RLE are trouble makers)
1363 SkipToNextDocEntry(newDocEntry);
1364 l = newDocEntry->GetFullLength();
1369 // to be sure we are at the beginning
1370 SkipToNextDocEntry(newDocEntry);
1371 l = newDocEntry->GetFullLength();
1377 l = newDocEntry->GetReadLength();
1378 if ( l != 0 ) // don't mess the delim_mode for zero-length sequence
1380 if ( l == 0xffffffff )
1389 // no other way to create it ...
1390 gdcmSeqEntry *sq = new gdcmSeqEntry(newDocEntry->GetDictEntry(),
1391 set->GetDepthLevel());
1392 sq->Copy(newDocEntry);
1393 sq->SetDelimitorMode(delim_mode);
1394 sq->SetDepthLevel(depth);
1397 { // Don't try to parse zero-length sequences
1398 long lgt = ParseSQ( sq,
1399 newDocEntry->GetOffset(),
1401 (void)lgt; //not used...
1404 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1411 return l; // Probably useless
1415 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1416 * @return parsed length for this level
1418 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1419 long offset, long l_max, bool delim_mode)
1421 int SQItemNumber = 0;
1423 //int depth = set->GetDepthLevel();
1424 //(void)depth; //not used
1428 gdcmDocEntry *newDocEntry = ReadNextDocEntry();
1431 // FIXME Should warn user
1436 if ( newDocEntry->IsSequenceDelimitor() )
1438 set->SetSequenceDelimitationItem( newDocEntry );
1442 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1447 gdcmSQItem *itemSQ = new gdcmSQItem(set->GetDepthLevel());
1448 itemSQ->AddEntry(newDocEntry);
1449 unsigned int l = newDocEntry->GetReadLength();
1451 if ( l == 0xffffffff )
1460 int lgr = ParseDES(itemSQ, newDocEntry->GetOffset(), l, dlm_mod);
1461 (void)lgr; //FIXME not used
1463 set->AddEntry(itemSQ, SQItemNumber);
1465 if ( !delim_mode && (ftell(Fp)-offset) >= l_max)
1471 int lgth = ftell(Fp) - offset;
1476 * \brief Loads the element content if its length doesn't exceed
1477 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1478 * @param entry Header Entry (Dicom Element) to be dealt with
1480 void gdcmDocument::LoadDocEntry(gdcmDocEntry* entry)
1483 uint16_t group = entry->GetGroup();
1484 std::string vr = entry->GetVR();
1485 uint32_t length = entry->GetLength();
1487 fseek(Fp, (long)entry->GetOffset(), SEEK_SET);
1489 // A SeQuence "contains" a set of Elements.
1490 // (fffe e000) tells us an Element is beginning
1491 // (fffe e00d) tells us an Element just ended
1492 // (fffe e0dd) tells us the current SeQuence just ended
1493 if( group == 0xfffe )
1495 // NO more value field for SQ !
1499 // When the length is zero things are easy:
1502 ((gdcmValEntry *)entry)->SetValue("");
1506 // The elements whose length is bigger than the specified upper bound
1507 // are not loaded. Instead we leave a short notice of the offset of
1508 // the element content and it's length.
1510 std::ostringstream s;
1511 if (length > MaxSizeLoadEntry)
1513 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1515 //s << "gdcm::NotLoaded (BinEntry)";
1516 s << GDCM_NOTLOADED;
1517 s << " Address:" << (long)entry->GetOffset();
1518 s << " Length:" << entry->GetLength();
1519 s << " x(" << std::hex << entry->GetLength() << ")";
1520 binEntryPtr->SetValue(s.str());
1522 // Be carefull : a BinEntry IS_A ValEntry ...
1523 else if (gdcmValEntry* valEntryPtr = dynamic_cast< gdcmValEntry* >(entry) )
1525 // s << "gdcm::NotLoaded. (ValEntry)";
1526 s << GDCM_NOTLOADED;
1527 s << " Address:" << (long)entry->GetOffset();
1528 s << " Length:" << entry->GetLength();
1529 s << " x(" << std::hex << entry->GetLength() << ")";
1530 valEntryPtr->SetValue(s.str());
1535 std::cout<< "MaxSizeLoadEntry exceeded, neither a BinEntry "
1536 << "nor a ValEntry ?! Should never print that !" << std::endl;
1539 // to be sure we are at the end of the value ...
1540 fseek(Fp,(long)entry->GetOffset()+(long)entry->GetLength(),SEEK_SET);
1544 // When we find a BinEntry not very much can be done :
1545 if (gdcmBinEntry* binEntryPtr = dynamic_cast< gdcmBinEntry* >(entry) )
1547 s << "gdcm::Loaded (BinEntry)";
1548 binEntryPtr->SetValue(s.str());
1549 LoadEntryVoidArea(binEntryPtr); // last one, not to erase length !
1553 /// \todo Any compacter code suggested (?)
1554 if ( IsDocEntryAnInteger(entry) )
1557 //std::ostringstream s; //shadow previous declaration
1559 // When short integer(s) are expected, read and convert the following
1560 // n *two characters properly i.e. consider them as short integers as
1561 // opposed to strings.
1562 // Elements with Value Multiplicity > 1
1563 // contain a set of integers (not a single one)
1564 if (vr == "US" || vr == "SS")
1567 NewInt = ReadInt16();
1571 for (int i=1; i < nbInt; i++)
1574 NewInt = ReadInt16();
1579 // See above comment on multiple integers (mutatis mutandis).
1580 else if (vr == "UL" || vr == "SL")
1583 NewInt = ReadInt32();
1587 for (int i=1; i < nbInt; i++)
1590 NewInt = ReadInt32();
1595 #ifdef GDCM_NO_ANSI_STRING_STREAM
1596 s << std::ends; // to avoid oddities on Solaris
1597 #endif //GDCM_NO_ANSI_STRING_STREAM
1599 ((gdcmValEntry *)entry)->SetValue(s.str());
1603 // We need an additional byte for storing \0 that is not on disk
1604 //std::string newValue(length,0);
1605 //item_read = fread(&(newValue[0]), (size_t)length, (size_t)1, Fp);
1606 //rah !! I can't believe it could work, normally this is a const char* !!!
1607 char *str = new char[length+1];
1608 item_read = fread(str, (size_t)length, (size_t)1, Fp);
1610 std::string newValue = str;
1612 if ( gdcmValEntry* valEntry = dynamic_cast<gdcmValEntry* >(entry) )
1614 if ( item_read != 1 )
1616 dbg.Verbose(1, "gdcmDocument::LoadDocEntry",
1617 "unread element value");
1618 valEntry->SetValue(GDCM_UNREAD);
1624 // Because of correspondance with the VR dic
1625 valEntry->SetValue(newValue);
1629 valEntry->SetValue(newValue);
1634 dbg.Error(true, "gdcmDocument::LoadDocEntry"
1635 "Should have a ValEntry, here !");
1641 * \brief Find the value Length of the passed Header Entry
1642 * @param entry Header Entry whose length of the value shall be loaded.
1644 void gdcmDocument::FindDocEntryLength( gdcmDocEntry *entry )
1645 throw ( gdcmFormatError )
1647 uint16_t element = entry->GetElement();
1648 std::string vr = entry->GetVR();
1651 if ( Filetype == gdcmExplicitVR && !entry->IsImplicitVR() )
1653 if ( vr == "OB" || vr == "OW" || vr == "SQ" || vr == "UN" )
1655 // The following reserved two bytes (see PS 3.5-2001, section
1656 // 7.1.2 Data element structure with explicit vr p27) must be
1657 // skipped before proceeding on reading the length on 4 bytes.
1658 fseek(Fp, 2L, SEEK_CUR);
1659 uint32_t length32 = ReadInt32();
1661 if ( vr == "OB" && length32 == 0xffffffff )
1666 lengthOB = FindDocEntryLengthOB();
1668 catch ( gdcmFormatUnexpected )
1670 // Computing the length failed (this happens with broken
1671 // files like gdcm-JPEG-LossLess3a.dcm). We still have a
1672 // chance to get the pixels by deciding the element goes
1673 // until the end of the file. Hence we artificially fix the
1674 // the length and proceed.
1675 long currentPosition = ftell(Fp);
1676 fseek(Fp,0L,SEEK_END);
1677 long lengthUntilEOF = ftell(Fp) - currentPosition;
1678 fseek(Fp, currentPosition, SEEK_SET);
1679 entry->SetLength(lengthUntilEOF);
1682 entry->SetLength(lengthOB);
1685 FixDocEntryFoundLength(entry, length32);
1689 // Length is encoded on 2 bytes.
1690 length16 = ReadInt16();
1692 // We can tell the current file is encoded in big endian (like
1693 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1694 // and it's value is the one of the encoding of a big endian file.
1695 // In order to deal with such big endian encoded files, we have
1696 // (at least) two strategies:
1697 // * when we load the "Transfer Syntax" tag with value of big endian
1698 // encoding, we raise the proper flags. Then we wait for the end
1699 // of the META group (0x0002) among which is "Transfer Syntax",
1700 // before switching the swap code to big endian. We have to postpone
1701 // the switching of the swap code since the META group is fully encoded
1702 // in little endian, and big endian coding only starts at the next
1703 // group. The corresponding code can be hard to analyse and adds
1704 // many additional unnecessary tests for regular tags.
1705 // * the second strategy consists in waiting for trouble, that shall
1706 // appear when we find the first group with big endian encoding. This
1707 // is easy to detect since the length of a "Group Length" tag (the
1708 // ones with zero as element number) has to be of 4 (0x0004). When we
1709 // encounter 1024 (0x0400) chances are the encoding changed and we
1710 // found a group with big endian encoding.
1711 // We shall use this second strategy. In order to make sure that we
1712 // can interpret the presence of an apparently big endian encoded
1713 // length of a "Group Length" without committing a big mistake, we
1714 // add an additional check: we look in the already parsed elements
1715 // for the presence of a "Transfer Syntax" whose value has to be "big
1716 // endian encoding". When this is the case, chances are we have got our
1717 // hands on a big endian encoded file: we switch the swap code to
1718 // big endian and proceed...
1719 if ( element == 0x0000 && length16 == 0x0400 )
1721 if ( !IsExplicitVRBigEndianTransferSyntax() )
1723 throw gdcmFormatError( "gdcmDocument::FindDocEntryLength()",
1724 " not explicit VR." );
1728 SwitchSwapToBigEndian();
1729 // Restore the unproperly loaded values i.e. the group, the element
1730 // and the dictionary entry depending on them.
1731 uint16_t correctGroup = SwapShort( entry->GetGroup() );
1732 uint16_t correctElem = SwapShort( entry->GetElement() );
1733 gdcmDictEntry* newTag = GetDictEntryByNumber( correctGroup,
1737 // This correct tag is not in the dictionary. Create a new one.
1738 newTag = NewVirtualDictEntry(correctGroup, correctElem);
1740 // FIXME this can create a memory leaks on the old entry that be
1741 // left unreferenced.
1742 entry->SetDictEntry( newTag );
1745 // Heuristic: well, some files are really ill-formed.
1746 if ( length16 == 0xffff)
1748 // 0xffff means that we deal with 'Unknown Length' Sequence
1751 FixDocEntryFoundLength( entry, (uint32_t)length16 );
1756 // Either implicit VR or a non DICOM conformal (see note below) explicit
1757 // VR that ommited the VR of (at least) this element. Farts happen.
1758 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1759 // on Data elements "Implicit and Explicit VR Data Elements shall
1760 // not coexist in a Data Set and Data Sets nested within it".]
1761 // Length is on 4 bytes.
1763 FixDocEntryFoundLength( entry, ReadInt32() );
1769 * \brief Find the Value Representation of the current Dicom Element.
1772 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *entry )
1774 if ( Filetype != gdcmExplicitVR )
1781 long positionOnEntry = ftell(Fp);
1782 // Warning: we believe this is explicit VR (Value Representation) because
1783 // we used a heuristic that found "UL" in the first tag. Alas this
1784 // doesn't guarantee that all the tags will be in explicit VR. In some
1785 // cases (see e-film filtered files) one finds implicit VR tags mixed
1786 // within an explicit VR file. Hence we make sure the present tag
1787 // is in explicit VR and try to fix things if it happens not to be
1790 fread (vr, (size_t)2,(size_t)1, Fp);
1793 if( !CheckDocEntryVR(entry, vr) )
1795 fseek(Fp, positionOnEntry, SEEK_SET);
1796 // When this element is known in the dictionary we shall use, e.g. for
1797 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1798 // dictionary entry. Still we have to flag the element as implicit since
1799 // we know now our assumption on expliciteness is not furfilled.
1801 if ( entry->IsVRUnknown() )
1803 entry->SetVR("Implicit");
1805 entry->SetImplicitVR();
1810 * \brief Check the correspondance between the VR of the header entry
1811 * and the taken VR. If they are different, the header entry is
1812 * updated with the new VR.
1813 * @param entry Header Entry to check
1814 * @param vr Dicom Value Representation
1815 * @return false if the VR is incorrect of if the VR isn't referenced
1816 * otherwise, it returns true
1818 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *entry, gdcmVRKey vr)
1820 char msg[100]; // for sprintf
1821 bool realExplicit = true;
1823 // Assume we are reading a falsely explicit VR file i.e. we reached
1824 // a tag where we expect reading a VR but are in fact we read the
1825 // first to bytes of the length. Then we will interogate (through find)
1826 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1827 // both GCC and VC++ implementations of the STL map. Hence when the
1828 // expected VR read happens to be non-ascii characters we consider
1829 // we hit falsely explicit VR tag.
1831 if ( !isalpha(vr[0]) && !isalpha(vr[1]) )
1833 realExplicit = false;
1836 // CLEANME searching the dicom_vr at each occurence is expensive.
1837 // PostPone this test in an optional integrity check at the end
1838 // of parsing or only in debug mode.
1839 if ( realExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1841 realExplicit = false;
1844 if ( !realExplicit )
1846 // We thought this was explicit VR, but we end up with an
1847 // implicit VR tag. Let's backtrack.
1848 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1849 entry->GetGroup(), entry->GetElement());
1850 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1852 if( entry->GetGroup() % 2 && entry->GetElement() == 0x0000)
1854 // Group length is UL !
1855 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1856 entry->GetGroup(), entry->GetElement(),
1857 "UL", "FIXME", "Group Length");
1858 entry->SetDictEntry( newEntry );
1863 if ( entry->IsVRUnknown() )
1865 // When not a dictionary entry, we can safely overwrite the VR.
1866 if( entry->GetElement() == 0x0000 )
1868 // Group length is UL !
1876 else if ( entry->GetVR() != vr )
1878 // The VR present in the file and the dictionary disagree. We assume
1879 // the file writer knew best and use the VR of the file. Since it would
1880 // be unwise to overwrite the VR of a dictionary (since it would
1881 // compromise it's next user), we need to clone the actual DictEntry
1882 // and change the VR for the read one.
1883 gdcmDictEntry* newEntry = NewVirtualDictEntry(
1884 entry->GetGroup(), entry->GetElement(),
1885 vr, "FIXME", entry->GetName());
1886 entry->SetDictEntry(newEntry);
1893 * \brief Get the transformed value of the header entry. The VR value
1894 * is used to define the transformation to operate on the value
1895 * \warning NOT end user intended method !
1896 * @param entry entry to tranform
1897 * @return Transformed entry value
1899 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *entry)
1901 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1903 std::string val = ((gdcmValEntry *)entry)->GetValue();
1904 std::string vr = entry->GetVR();
1905 uint32_t length = entry->GetLength();
1906 std::ostringstream s;
1909 // When short integer(s) are expected, read and convert the following
1910 // n * 2 bytes properly i.e. as a multivaluated strings
1911 // (each single value is separated fromthe next one by '\'
1912 // as usual for standard multivaluated filels
1913 // Elements with Value Multiplicity > 1
1914 // contain a set of short integers (not a single one)
1916 if( vr == "US" || vr == "SS" )
1921 for (int i=0; i < nbInt; i++)
1927 newInt16 = ( val[2*i+0] & 0xFF ) + ( ( val[2*i+1] & 0xFF ) << 8);
1928 newInt16 = SwapShort( newInt16 );
1933 // When integer(s) are expected, read and convert the following
1934 // n * 4 bytes properly i.e. as a multivaluated strings
1935 // (each single value is separated fromthe next one by '\'
1936 // as usual for standard multivaluated filels
1937 // Elements with Value Multiplicity > 1
1938 // contain a set of integers (not a single one)
1939 else if( vr == "UL" || vr == "SL" )
1944 for (int i=0; i < nbInt; i++)
1950 newInt32 = ( val[4*i+0] & 0xFF )
1951 + (( val[4*i+1] & 0xFF ) << 8 )
1952 + (( val[4*i+2] & 0xFF ) << 16 )
1953 + (( val[4*i+3] & 0xFF ) << 24 );
1954 newInt32 = SwapLong( newInt32 );
1958 #ifdef GDCM_NO_ANSI_STRING_STREAM
1959 s << std::ends; // to avoid oddities on Solaris
1960 #endif //GDCM_NO_ANSI_STRING_STREAM
1964 return ((gdcmValEntry *)entry)->GetValue();
1968 * \brief Get the reverse transformed value of the header entry. The VR
1969 * value is used to define the reverse transformation to operate on
1971 * \warning NOT end user intended method !
1972 * @param entry Entry to reverse transform
1973 * @return Reverse transformed entry value
1975 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry* entry)
1977 if ( IsDocEntryAnInteger(entry) && entry->IsImplicitVR() )
1979 std::string vr = entry->GetVR();
1980 std::vector<std::string> tokens;
1981 std::ostringstream s;
1983 if ( vr == "US" || vr == "SS" )
1987 tokens.erase( tokens.begin(), tokens.end()); // clean any previous value
1988 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
1989 for (unsigned int i=0; i<tokens.size(); i++)
1991 newInt16 = atoi(tokens[i].c_str());
1992 s << ( newInt16 & 0xFF )
1993 << (( newInt16 >> 8 ) & 0xFF );
1997 if ( vr == "UL" || vr == "SL")
2001 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2002 Tokenize (((gdcmValEntry *)entry)->GetValue(), tokens, "\\");
2003 for (unsigned int i=0; i<tokens.size();i++)
2005 newInt32 = atoi(tokens[i].c_str());
2006 s << (char)( newInt32 & 0xFF )
2007 << (char)(( newInt32 >> 8 ) & 0xFF )
2008 << (char)(( newInt32 >> 16 ) & 0xFF )
2009 << (char)(( newInt32 >> 24 ) & 0xFF );
2014 #ifdef GDCM_NO_ANSI_STRING_STREAM
2015 s << std::ends; // to avoid oddities on Solaris
2016 #endif //GDCM_NO_ANSI_STRING_STREAM
2020 return ((gdcmValEntry *)entry)->GetValue();
2024 * \brief Skip a given Header Entry
2025 * \warning NOT end user intended method !
2026 * @param entry entry to skip
2028 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
2030 SkipBytes(entry->GetLength());
2034 * \brief Skips to the begining of the next Header Entry
2035 * \warning NOT end user intended method !
2036 * @param entry entry to skip
2038 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
2040 fseek(Fp, (long)(entry->GetOffset()), SEEK_SET);
2041 fseek(Fp, (long)(entry->GetReadLength()), SEEK_CUR);
2045 * \brief When the length of an element value is obviously wrong (because
2046 * the parser went Jabberwocky) one can hope improving things by
2047 * applying some heuristics.
2048 * @param entry entry to check
2049 * @param foundLength fist assumption about length
2051 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *entry,
2052 uint32_t foundLength)
2054 entry->SetReadLength( foundLength ); // will be updated only if a bug is found
2055 if ( foundLength == 0xffffffff)
2060 uint16_t gr = entry->GetGroup();
2061 uint16_t el = entry->GetElement();
2063 if ( foundLength % 2)
2065 std::ostringstream s;
2066 s << "Warning : Tag with uneven length "
2068 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
2069 dbg.Verbose(0, s.str().c_str());
2072 //////// Fix for some naughty General Electric images.
2073 // Allthough not recent many such GE corrupted images are still present
2074 // on Creatis hard disks. Hence this fix shall remain when such images
2075 // are no longer in user (we are talking a few years, here)...
2076 // Note: XMedCom probably uses such a trick since it is able to read
2077 // those pesky GE images ...
2078 if ( foundLength == 13)
2080 // Only happens for this length !
2081 if ( entry->GetGroup() != 0x0008
2082 || ( entry->GetElement() != 0x0070
2083 && entry->GetElement() != 0x0080 ) )
2086 entry->SetReadLength(10); /// \todo a bug is to be fixed !?
2090 //////// Fix for some brain-dead 'Leonardo' Siemens images.
2091 // Occurence of such images is quite low (unless one leaves close to a
2092 // 'Leonardo' source. Hence, one might consider commenting out the
2093 // following fix on efficiency reasons.
2094 else if ( entry->GetGroup() == 0x0009
2095 && ( entry->GetElement() == 0x1113
2096 || entry->GetElement() == 0x1114 ) )
2099 entry->SetReadLength(4); /// \todo a bug is to be fixed !?
2102 else if ( entry->GetVR() == "SQ" )
2104 foundLength = 0; // ReadLength is unchanged
2107 //////// We encountered a 'delimiter' element i.e. a tag of the form
2108 // "fffe|xxxx" which is just a marker. Delimiters length should not be
2109 // taken into account.
2110 else if( entry->GetGroup() == 0xfffe )
2112 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
2113 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
2114 // causes extra troubles...
2115 if( entry->GetElement() != 0x0000 )
2121 entry->SetUsableLength(foundLength);
2125 * \brief Apply some heuristics to predict whether the considered
2126 * element value contains/represents an integer or not.
2127 * @param entry The element value on which to apply the predicate.
2128 * @return The result of the heuristical predicate.
2130 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *entry)
2132 uint16_t element = entry->GetElement();
2133 uint16_t group = entry->GetGroup();
2134 std::string vr = entry->GetVR();
2135 uint32_t length = entry->GetLength();
2137 // When we have some semantics on the element we just read, and if we
2138 // a priori know we are dealing with an integer, then we shall be
2139 // able to swap it's element value properly.
2140 if ( element == 0 ) // This is the group length of the group
2148 // Allthough this should never happen, still some images have a
2149 // corrupted group length [e.g. have a glance at offset x(8336) of
2150 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
2151 // Since for dicom compliant and well behaved headers, the present
2152 // test is useless (and might even look a bit paranoid), when we
2153 // encounter such an ill-formed image, we simply display a warning
2154 // message and proceed on parsing (while crossing fingers).
2155 std::ostringstream s;
2156 int filePosition = ftell(Fp);
2157 s << "Erroneous Group Length element length on : (" \
2158 << std::hex << group << " , " << element
2159 << ") -before- position x(" << filePosition << ")"
2160 << "lgt : " << length;
2161 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
2165 if ( vr == "UL" || vr == "US" || vr == "SL" || vr == "SS" )
2174 * \brief Find the Length till the next sequence delimiter
2175 * \warning NOT end user intended method !
2179 uint32_t gdcmDocument::FindDocEntryLengthOB()
2180 throw( gdcmFormatUnexpected )
2182 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
2183 long positionOnEntry = ftell(Fp);
2184 bool foundSequenceDelimiter = false;
2185 uint32_t totalLength = 0;
2187 while ( !foundSequenceDelimiter )
2193 group = ReadInt16();
2196 catch ( gdcmFormatError )
2198 throw gdcmFormatError("gdcmDocument::FindDocEntryLengthOB()",
2199 " group or element not present.");
2202 // We have to decount the group and element we just read
2205 if ( group != 0xfffe || ( ( elem != 0xe0dd ) && ( elem != 0xe000 ) ) )
2207 dbg.Verbose(1, "gdcmDocument::FindDocEntryLengthOB: neither an Item "
2208 "tag nor a Sequence delimiter tag.");
2209 fseek(Fp, positionOnEntry, SEEK_SET);
2210 throw gdcmFormatUnexpected("gdcmDocument::FindDocEntryLengthOB()",
2211 "Neither an Item tag nor a Sequence "
2215 if ( elem == 0xe0dd )
2217 foundSequenceDelimiter = true;
2220 uint32_t itemLength = ReadInt32();
2221 // We add 4 bytes since we just read the ItemLength with ReadInt32
2222 totalLength += itemLength + 4;
2223 SkipBytes(itemLength);
2225 if ( foundSequenceDelimiter )
2230 fseek(Fp, positionOnEntry, SEEK_SET);
2235 * \brief Reads a supposed to be 16 Bits integer
2236 * (swaps it depending on processor endianity)
2237 * @return read value
2239 uint16_t gdcmDocument::ReadInt16()
2240 throw( gdcmFormatError )
2243 size_t item_read = fread (&g, (size_t)2,(size_t)1, Fp);
2244 if ( item_read != 1 )
2248 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2250 throw gdcmFormatError( "gdcmDocument::ReadInt16()", "EOF." );
2257 * \brief Reads a supposed to be 32 Bits integer
2258 * (swaps it depending on processor endianity)
2259 * @return read value
2261 uint32_t gdcmDocument::ReadInt32()
2262 throw( gdcmFormatError )
2265 size_t item_read = fread (&g, (size_t)4,(size_t)1, Fp);
2266 if ( item_read != 1 )
2270 throw gdcmFormatError( "gdcmDocument::ReadInt16()", " file error." );
2272 throw gdcmFormatError( "gdcmDocument::ReadInt32()", "EOF." );
2279 * \brief skips bytes inside the source file
2280 * \warning NOT end user intended method !
2283 void gdcmDocument::SkipBytes(uint32_t nBytes)
2285 //FIXME don't dump the returned value
2286 (void)fseek(Fp, (long)nBytes, SEEK_CUR);
2290 * \brief Loads all the needed Dictionaries
2291 * \warning NOT end user intended method !
2293 void gdcmDocument::Initialise()
2295 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2300 * \brief Discover what the swap code is (among little endian, big endian,
2301 * bad little endian, bad big endian).
2303 * @return false when we are absolutely sure
2304 * it's neither ACR-NEMA nor DICOM
2305 * true when we hope ours assuptions are OK
2307 bool gdcmDocument::CheckSwap()
2309 // The only guaranted way of finding the swap code is to find a
2310 // group tag since we know it's length has to be of four bytes i.e.
2311 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2312 // occurs when we can't find such group...
2314 uint32_t x = 4; // x : for ntohs
2315 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2319 char deb[HEADER_LENGTH_TO_READ];
2321 // First, compare HostByteOrder and NetworkByteOrder in order to
2322 // determine if we shall need to swap bytes (i.e. the Endian type).
2323 if ( x == ntohs(x) )
2332 // The easiest case is the one of a DICOM header, since it possesses a
2333 // file preamble where it suffice to look for the string "DICM".
2334 int lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, Fp);
2335 (void)lgrLue; //FIXME not used
2337 char *entCur = deb + 128;
2338 if( memcmp(entCur, "DICM", (size_t)4) == 0 )
2340 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2342 // Next, determine the value representation (VR). Let's skip to the
2343 // first element (0002, 0000) and check there if we find "UL"
2344 // - or "OB" if the 1st one is (0002,0001) -,
2345 // in which case we (almost) know it is explicit VR.
2346 // WARNING: if it happens to be implicit VR then what we will read
2347 // is the length of the group. If this ascii representation of this
2348 // length happens to be "UL" then we shall believe it is explicit VR.
2349 // FIXME: in order to fix the above warning, we could read the next
2350 // element value (or a couple of elements values) in order to make
2351 // sure we are not commiting a big mistake.
2352 // We need to skip :
2353 // * the 128 bytes of File Preamble (often padded with zeroes),
2354 // * the 4 bytes of "DICM" string,
2355 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2356 // i.e. a total of 136 bytes.
2360 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2361 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2362 // *Implicit* VR. -and it is !-
2364 if( memcmp(entCur, "UL", (size_t)2) == 0 ||
2365 memcmp(entCur, "OB", (size_t)2) == 0 ||
2366 memcmp(entCur, "UI", (size_t)2) == 0 ||
2367 memcmp(entCur, "CS", (size_t)2) == 0 ) // CS, to remove later
2368 // when Write DCM *adds*
2370 // Use gdcmDocument::dicom_vr to test all the possibilities
2371 // instead of just checking for UL, OB and UI !? group 0000
2373 Filetype = gdcmExplicitVR;
2374 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2375 "explicit Value Representation");
2379 Filetype = gdcmImplicitVR;
2380 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2381 "not an explicit Value Representation");
2387 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2388 "HostByteOrder != NetworkByteOrder");
2393 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2394 "HostByteOrder = NetworkByteOrder");
2397 // Position the file position indicator at first tag (i.e.
2398 // after the file preamble and the "DICM" string).
2400 fseek (Fp, 132L, SEEK_SET);
2404 // Alas, this is not a DicomV3 file and whatever happens there is no file
2405 // preamble. We can reset the file position indicator to where the data
2406 // is (i.e. the beginning of the file).
2407 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2410 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2411 // By clean we mean that the length of the first tag is written down.
2412 // If this is the case and since the length of the first group HAS to be
2413 // four (bytes), then determining the proper swap code is straightforward.
2416 // We assume the array of char we are considering contains the binary
2417 // representation of a 32 bits integer. Hence the following dirty
2419 s32 = *((uint32_t *)(entCur));
2440 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2441 // It is time for despaired wild guesses.
2442 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2443 // i.e. the 'group length' element is not present :
2445 // check the supposed to be 'group number'
2446 // 0x0002 or 0x0004 or 0x0008
2447 // to determine ' SwapCode' value .
2448 // Only 0 or 4321 will be possible
2449 // (no oportunity to check for the formerly well known
2450 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2451 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2452 // the file IS NOT ACR-NEMA nor DICOM V3
2453 // Find a trick to tell it the caller...
2455 s16 = *((uint16_t *)(deb));
2472 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2473 "ACR/NEMA unfound swap info (Really hopeless !)");
2474 Filetype = gdcmUnknown;
2477 // Then the only info we have is the net2host one.
2487 * \brief Restore the unproperly loaded values i.e. the group, the element
2488 * and the dictionary entry depending on them.
2490 void gdcmDocument::SwitchSwapToBigEndian()
2492 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2493 "Switching to BigEndian mode.");
2494 if ( SwapCode == 0 )
2498 else if ( SwapCode == 4321 )
2502 else if ( SwapCode == 3412 )
2506 else if ( SwapCode == 2143 )
2513 * \brief during parsing, Header Elements too long are not loaded in memory
2516 void gdcmDocument::SetMaxSizeLoadEntry(long newSize)
2522 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2524 MaxSizeLoadEntry = 0xffffffff;
2527 MaxSizeLoadEntry = newSize;
2532 * \brief Header Elements too long will not be printed
2533 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2536 void gdcmDocument::SetMaxSizePrintEntry(long newSize)
2538 //DOH !! This is exactly SetMaxSizeLoadEntry FIXME FIXME
2543 if ((uint32_t)newSize >= (uint32_t)0xffffffff )
2545 MaxSizePrintEntry = 0xffffffff;
2548 MaxSizePrintEntry = newSize;
2554 * \brief Read the next tag but WITHOUT loading it's value
2555 * (read the 'Group Number', the 'Element Number',
2556 * gets the Dict Entry
2557 * gets the VR, gets the length, gets the offset value)
2558 * @return On succes the newly created DocEntry, NULL on failure.
2560 gdcmDocEntry* gdcmDocument::ReadNextDocEntry()
2567 group = ReadInt16();
2570 catch ( gdcmFormatError e )
2572 // We reached the EOF (or an error occured) therefore
2573 // header parsing has to be considered as finished.
2578 gdcmDocEntry *newEntry = NewDocEntryByNumber(group, elem);
2579 FindDocEntryVR(newEntry);
2583 FindDocEntryLength(newEntry);
2585 catch ( gdcmFormatError e )
2593 newEntry->SetOffset(ftell(Fp));
2600 * \brief Generate a free gdcmTagKey i.e. a gdcmTagKey that is not present
2601 * in the TagHt dictionary.
2602 * @param group The generated tag must belong to this group.
2603 * @return The element of tag with given group which is fee.
2605 uint32_t gdcmDocument::GenerateFreeTagKeyInGroup(uint16_t group)
2607 for (uint32_t elem = 0; elem < UINT32_MAX; elem++)
2609 gdcmTagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2610 if (TagHT.count(key) == 0)
2619 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2620 * is placed at the beginning of a tag check whether this
2621 * tag is (TestGroup, TestElement).
2622 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2623 * is modified to point after the tag.
2624 * On failure (i.e. when the tag wasn't the expected tag
2625 * (TestGroup, TestElement) the internal file pointer
2626 * \ref gdcmDocument::Fp is restored to it's original position.
2627 * @param testGroup The expected group of the tag.
2628 * @param testElement The expected Element of the tag.
2629 * @return True on success, false otherwise.
2631 bool gdcmDocument::ReadTag(uint16_t testGroup, uint16_t testElement)
2633 long positionOnEntry = ftell(Fp);
2634 long currentPosition = ftell(Fp); // On debugging purposes
2636 //// Read the Item Tag group and element, and make
2637 // sure they are what we expected:
2638 uint16_t itemTagGroup = ReadInt16();
2639 uint16_t itemTagElement = ReadInt16();
2640 if ( itemTagGroup != testGroup || itemTagElement != testElement )
2642 std::ostringstream s;
2643 s << " We should have found tag (";
2644 s << std::hex << testGroup << "," << testElement << ")" << std::endl;
2645 s << " but instead we encountered tag (";
2646 s << std::hex << itemTagGroup << "," << itemTagElement << ")"
2648 s << " at address: " << (unsigned)currentPosition << std::endl;
2649 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2650 dbg.Verbose(0, s.str().c_str());
2651 fseek(Fp, positionOnEntry, SEEK_SET);
2659 * \brief Assuming the internal file pointer \ref gdcmDocument::Fp
2660 * is placed at the beginning of a tag (TestGroup, TestElement),
2661 * read the length associated to the Tag.
2662 * \warning On success the internal file pointer \ref gdcmDocument::Fp
2663 * is modified to point after the tag and it's length.
2664 * On failure (i.e. when the tag wasn't the expected tag
2665 * (TestGroup, TestElement) the internal file pointer
2666 * \ref gdcmDocument::Fp is restored to it's original position.
2667 * @param testGroup The expected group of the tag.
2668 * @param testElement The expected Element of the tag.
2669 * @return On success returns the length associated to the tag. On failure
2672 uint32_t gdcmDocument::ReadTagLength(uint16_t testGroup, uint16_t testElement)
2674 long positionOnEntry = ftell(Fp);
2675 (void)positionOnEntry;
2677 if ( !ReadTag(testGroup, testElement) )
2682 //// Then read the associated Item Length
2683 long currentPosition = ftell(Fp);
2684 uint32_t itemLength = ReadInt32();
2686 std::ostringstream s;
2687 s << "Basic Item Length is: "
2688 << itemLength << std::endl;
2689 s << " at address: " << (unsigned)currentPosition << std::endl;
2690 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2696 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2697 * No other way so 'skip' the Data
2700 void gdcmDocument::Parse7FE0 ()
2702 gdcmDocEntry* element = GetDocEntryByNumber(0x0002, 0x0010);
2705 // Should warn user FIXME
2709 if ( IsImplicitVRLittleEndianTransferSyntax()
2710 || IsExplicitVRLittleEndianTransferSyntax()
2711 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2712 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2717 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2719 //// Read the Basic Offset Table Item Tag length...
2720 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2722 //// ... and then read length[s] itself[themselves]. We don't use
2723 // the values read (BTW what is the purpous of those lengths ?)
2724 if ( itemLength != 0 )
2726 // BTW, what is the purpous of those length anyhow !?
2727 char* basicOffsetTableItemValue = new char[itemLength + 1];
2728 fread(basicOffsetTableItemValue, itemLength, 1, Fp);
2730 for (unsigned int i=0; i < itemLength; i += 4 )
2732 uint32_t individualLength = str2num(&basicOffsetTableItemValue[i],uint32_t);
2733 std::ostringstream s;
2734 s << " Read one length: ";
2735 s << std::hex << individualLength << std::endl;
2736 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2738 delete[] basicOffsetTableItemValue;
2741 if ( ! IsRLELossLessTransferSyntax() )
2745 //// We then skip (not reading them) all the fragments of images:
2746 while ( (itemLength = ReadTagLength(0xfffe, 0xe000)) )
2748 SkipBytes(itemLength);
2755 long rleSegmentLength[15], fragmentLength;
2757 // While we find some items:
2758 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) )
2760 // Parse fragments of the current Fragment (Frame)
2761 //------------------ scanning (not reading) fragment pixels
2762 uint32_t nbRleSegments = ReadInt32();
2764 //// Reading RLE Segments Offset Table
2765 uint32_t rleSegmentOffsetTable[15];
2766 for(int k=1; k<=15; k++)
2768 ftellRes = ftell(Fp);
2769 rleSegmentOffsetTable[k] = ReadInt32();
2772 // skipping (not reading) RLE Segments
2773 if ( nbRleSegments > 1)
2775 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
2777 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
2778 - rleSegmentOffsetTable[k];
2779 ftellRes = ftell(Fp);
2780 SkipBytes(rleSegmentLength[k]);
2784 rleSegmentLength[nbRleSegments] = fragmentLength
2785 - rleSegmentOffsetTable[nbRleSegments];
2786 ftellRes = ftell(Fp);
2787 SkipBytes(rleSegmentLength[nbRleSegments]);
2790 // Make sure that at the end of the item we encounter a 'Sequence
2792 if ( !ReadTag(0xfffe, 0xe0dd) )
2794 dbg.Verbose(0, "gdcmDocument::Parse7FE0: no sequence delimiter item");
2795 dbg.Verbose(0, " at end of RLE item sequence");
2803 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2804 * \warning Does NOT work with ACR-NEMA files
2805 * \todo Find a trick to solve the pb (use RET fields ?)
2807 * @return true if 'smaller'
2809 bool gdcmDocument::operator<(gdcmDocument &document)
2812 std::string s1 = GetEntryByNumber(0x0010,0x0010);
2813 std::string s2 = document.GetEntryByNumber(0x0010,0x0010);
2825 s1 = GetEntryByNumber(0x0010,0x0020);
2826 s2 = document.GetEntryByNumber(0x0010,0x0020);
2837 // Study Instance UID
2838 s1 = GetEntryByNumber(0x0020,0x000d);
2839 s2 = document.GetEntryByNumber(0x0020,0x000d);
2850 // Serie Instance UID
2851 s1 = GetEntryByNumber(0x0020,0x000e);
2852 s2 = document.GetEntryByNumber(0x0020,0x000e);
2868 //-----------------------------------------------------------------------------