]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
Add some accessors for debugging purpose
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6
7   Date:      $Date: 2005/06/17 12:35:00 $
8   Version:   $Revision: 1.43 $
9                                                                                 
10   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
11   l'Image). All rights reserved. See Doc/License.txt or
12   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13                                                                                 
14      This software is distributed WITHOUT ANY WARRANTY; without even
15      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
16      PURPOSE.  See the above copyright notices for more information.
17                                                                                 
18 =========================================================================*/
19
20 #include "gdcmFileHelper.h"
21 #include "gdcmGlobal.h"
22 #include "gdcmTS.h"
23 #include "gdcmDocument.h"
24 #include "gdcmDebug.h"
25 #include "gdcmUtil.h"
26 #include "gdcmBinEntry.h"
27 #include "gdcmValEntry.h"
28 #include "gdcmSeqEntry.h"
29 #include "gdcmSQItem.h"
30 #include "gdcmContentEntry.h"
31 #include "gdcmFile.h"
32 #include "gdcmPixelReadConvert.h"
33 #include "gdcmPixelWriteConvert.h"
34 #include "gdcmDocEntryArchive.h"
35 #include "gdcmDictSet.h"
36
37 #include <fstream>
38
39 /*
40 // ----------------------------- WARNING -------------------------
41
42 These lines will be moved to the document-to-be 'User's Guide'
43
44 // To read an image, user needs a gdcm::File
45 gdcm::File *f1 = new gdcm::File(fileName);
46 // user can now check some values
47 std::string v = f1->GetEntryValue(groupNb,ElementNb);
48 // to get the pixels, user needs a gdcm::FileHelper
49 gdcm::FileHelper *fh1 = new gdcm::FileHelper(f1);
50 // user may ask not to convert Palette to RGB
51 uint8_t *pixels = fh1->GetImageDataRaw();
52 int imageLength = fh1->GetImageDataRawSize();
53 // He can now use the pixels, create a new image, ...
54 uint8_t *userPixels = ...
55
56 To re-write the image, user re-uses the gdcm::FileHelper
57
58 fh1->SetImageData( userPixels, userPixelsLength);
59 fh1->SetTypeToRaw(); // Even if it was possible to convert Palette to RGB
60                      // (WriteMode is set)
61  
62 fh1->SetWriteTypeToDcmExpl(); // he wants Explicit Value Representation
63                               // Little Endian is the default
64                               // no other value is allowed
65                                 (-->SetWriteType(ExplicitVR);)
66                                    -->WriteType = ExplicitVR;
67 fh1->Write(newFileName);      // overwrites the file, if any
68
69 // or :
70 fh1->WriteDcmExplVR(newFileName);
71
72
73 // ----------------------------- WARNING -------------------------
74
75 These lines will be moved to the document-to-be 'Developer's Guide'
76
77 WriteMode : WMODE_RAW / WMODE_RGB
78 WriteType : ImplicitVR, ExplicitVR, ACR, ACR_LIBIDO
79
80 fh1->Write(newFileName);
81    SetWriteFileTypeToImplicitVR() / SetWriteFileTypeToExplicitVR();
82    (modifies TransferSyntax)
83    SetWriteToRaw(); / SetWriteToRGB();
84       (modifies, when necessary : photochromatic interpretation, 
85          samples per pixel, Planar configuration, 
86          bits allocated, bits stored, high bit -ACR 24 bits-
87          Pixels element VR, pushes out the LUT )
88    CheckWriteIntegrity();
89       (checks user given pixels length)
90    FileInternal->Write(fileName,WriteType)
91    fp = opens file(fileName);
92    ComputeGroup0002Length(writetype);
93    BitsAllocated 12->16
94       RemoveEntryNoDestroy(palettes, etc)
95       Document::WriteContent(fp, writetype);
96    RestoreWrite();
97       (moves back to the File all the archived elements)
98    RestoreWriteFileType();
99       (pushes back group 0002, with TransferSyntax)
100 */
101
102
103
104
105 namespace gdcm 
106 {
107 //-------------------------------------------------------------------------
108 // Constructor / Destructor
109 /**
110  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
111  *        file (gdcm::File only deals with the ... header)
112  *        Opens (in read only and when possible) an existing file and checks
113  *        for DICOM compliance. Returns NULL on failure.
114  *        It will be up to the user to load the pixels into memory
115  * \note  the in-memory representation of all available tags found in
116  *        the DICOM header is post-poned to first header information access.
117  *        This avoid a double parsing of public part of the header when
118  *        one sets an a posteriori shadow dictionary (efficiency can be
119  *        seen as a side effect).   
120  */
121 FileHelper::FileHelper( )
122 {
123    FileInternal = new File( );
124    SelfHeader = true;
125    Initialize();
126 }
127
128 /**
129  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
130  *        file (File only deals with the ... header)
131  *        Opens (in read only and when possible) an existing file and checks
132  *        for DICOM compliance. Returns NULL on failure.
133  *        It will be up to the user to load the pixels into memory
134  * \note  the in-memory representation of all available tags found in
135  *        the DICOM header is post-poned to first header information access.
136  *        This avoid a double parsing of public part of the header when
137  *        user sets an a posteriori shadow dictionary (efficiency can be
138  *        seen as a side effect).   
139  * @param header already built Header
140  */
141 FileHelper::FileHelper(File *header)
142 {
143    FileInternal = header;
144    SelfHeader = false;
145    Initialize();
146 }
147
148 /**
149  * \brief Constructor dedicated to deal with the *pixels* area of a ACR/DICOMV3
150  *        file (gdcm::File only deals with the ... header)
151  *        Opens (in read only and when possible) an existing file and checks
152  *        for DICOM compliance. Returns NULL on failure.
153  *        It will be up to the user to load the pixels into memory
154  * \note  the in-memory representation of all available tags found in
155  *        the DICOM header is post-poned to first header information access.
156  *        This avoid a double parsing of public part of the header when
157  *        one sets an a posteriori shadow dictionary (efficiency can be
158  *        seen as a side effect).   
159  * @param filename file to be opened for parsing
160  */
161 FileHelper::FileHelper(std::string const &filename )
162 {
163    FileInternal = new File( filename );
164    SelfHeader = true;
165    Initialize();
166 }
167
168 /**
169  * \brief canonical destructor
170  * \note  If the header (gdcm::File) was created by the FileHelper constructor,
171  *        it is destroyed by the FileHelper
172  */
173 FileHelper::~FileHelper()
174
175    if( PixelReadConverter )
176    {
177       delete PixelReadConverter;
178    }
179    if( PixelWriteConverter )
180    {
181       delete PixelWriteConverter;
182    }
183    if( Archive )
184    {
185       delete Archive;
186    }
187
188    if( SelfHeader )
189    {
190       delete FileInternal;
191    }
192    FileInternal = 0;
193 }
194
195 //-----------------------------------------------------------------------------
196 // Public
197 /**
198  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
199  *          through it's (group, element) and modifies it's content with
200  *          the given value.
201  * @param   content new value (string) to substitute with
202  * @param   group  group number of the Dicom Element to modify
203  * @param   elem element number of the Dicom Element to modify
204  * \return  false if DocEntry not found
205  */
206 bool FileHelper::SetValEntry(std::string const &content,
207                              uint16_t group, uint16_t elem)
208
209    return FileInternal->SetValEntry(content, group, elem);
210 }
211
212
213 /**
214  * \brief   Accesses an existing DocEntry (i.e. a Dicom Element)
215  *          through it's (group, element) and modifies it's content with
216  *          the given value.
217  * @param   content new value (void*  -> uint8_t*) to substitute with
218  * @param   lgth new value length
219  * @param   group  group number of the Dicom Element to modify
220  * @param   elem element number of the Dicom Element to modify
221  * \return  false if DocEntry not found
222  */
223 bool FileHelper::SetBinEntry(uint8_t *content, int lgth,
224                              uint16_t group, uint16_t elem)
225 {
226    return FileInternal->SetBinEntry(content, lgth, group, elem);
227 }
228
229 /**
230  * \brief   Modifies the value of a given DocEntry (Dicom entry)
231  *          when it exists. Creates it with the given value when unexistant.
232  * @param   content (string)value to be set
233  * @param   group   Group number of the Entry 
234  * @param   elem  Element number of the Entry
235  * \return  pointer to the modified/created Dicom entry (NULL when creation
236  *          failed).
237  */ 
238 ValEntry *FileHelper::InsertValEntry(std::string const &content,
239                                      uint16_t group, uint16_t elem)
240 {
241    return FileInternal->InsertValEntry(content, group, elem);
242 }
243
244 /**
245  * \brief   Modifies the value of a given DocEntry (Dicom entry)
246  *          when it exists. Creates it with the given value when unexistant.
247  *          A copy of the binArea is made to be kept in the Document.
248  * @param   binArea (binary)value to be set
249  * @param   lgth new value length
250  * @param   group   Group number of the Entry 
251  * @param   elem  Element number of the Entry
252  * \return  pointer to the modified/created Dicom entry (NULL when creation
253  *          failed).
254  */
255 BinEntry *FileHelper::InsertBinEntry(uint8_t *binArea, int lgth,
256                                      uint16_t group, uint16_t elem)
257 {
258    return FileInternal->InsertBinEntry(binArea, lgth, group, elem);
259 }
260
261 /**
262  * \brief   Modifies the value of a given DocEntry (Dicom entry)
263  *          when it exists. Creates it, empty (?!) when unexistant.
264  * @param   group   Group number of the Entry 
265  * @param   elem  Element number of the Entry
266  * \return  pointer to the modified/created Dicom entry (NULL when creation
267  *          failed).
268  */
269 SeqEntry *FileHelper::InsertSeqEntry(uint16_t group, uint16_t elem)
270 {
271    return FileInternal->InsertSeqEntry(group, elem);
272 }
273
274 /**
275  * \brief   Get the size of the image data
276  *          If the image can be RGB (with a lut or by default), the size 
277  *          corresponds to the RGB image
278  *         (use GetImageDataRawSize if you want to be sure to get *only*
279  *          the size of the pixels)
280  * @return  The image size
281  */
282 size_t FileHelper::GetImageDataSize()
283 {
284    if ( PixelWriteConverter->GetUserData() )
285    {
286       return PixelWriteConverter->GetUserDataSize();
287    }
288    return PixelReadConverter->GetRGBSize();
289 }
290
291 /**
292  * \brief   Get the size of the image data
293  *          If the image could be converted to RGB using a LUT, 
294  *          this transformation is not taken into account by GetImageDataRawSize
295  *          (use GetImageDataSize if you wish)
296  * @return  The raw image size
297  */
298 size_t FileHelper::GetImageDataRawSize()
299 {
300    if ( PixelWriteConverter->GetUserData() )
301    {
302       return PixelWriteConverter->GetUserDataSize();
303    }
304    return PixelReadConverter->GetRawSize();
305 }
306
307 /**
308  * \brief   - Allocates necessary memory,
309  *          - Reads the pixels from disk (uncompress if necessary),
310  *          - Transforms YBR pixels, if any, into RGB pixels,
311  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
312  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
313  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
314  * @return  Pointer to newly allocated pixel data.
315  *          NULL if alloc fails 
316  */
317 uint8_t *FileHelper::GetImageData()
318 {
319    if ( PixelWriteConverter->GetUserData() )
320    {
321       return PixelWriteConverter->GetUserData();
322    }
323
324    if ( ! GetRaw() )
325    {
326       // If the decompression failed nothing can be done.
327       return 0;
328    }
329
330    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
331    {
332       return PixelReadConverter->GetRGB();
333    }
334    else
335    {
336       // When no LUT or LUT conversion fails, return the Raw
337       return PixelReadConverter->GetRaw();
338    }
339 }
340
341 /**
342  * \brief   Allocates necessary memory, 
343  *          Transforms YBR pixels (if any) into RGB pixels
344  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
345  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
346  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
347  * @return  Pointer to newly allocated pixel data.
348  *          NULL if alloc fails 
349  */
350 uint8_t *FileHelper::GetImageDataRaw ()
351 {
352    return GetRaw();
353 }
354
355 /**
356  * \brief
357  *          Read the pixels from disk (uncompress if necessary),
358  *          Transforms YBR pixels, if any, into RGB pixels
359  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
360  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
361  *          Copies at most MaxSize bytes of pixel data to caller allocated
362  *          memory space.
363  * \warning This function allows people that want to build a volume
364  *          from an image stack *not to* have, first to get the image pixels, 
365  *          and then move them to the volume area.
366  *          It's absolutely useless for any VTK user since vtk chooses 
367  *          to invert the lines of an image, that is the last line comes first
368  *          (for some axis related reasons?). Hence he will have 
369  *          to load the image line by line, starting from the end.
370  *          VTK users have to call GetImageData
371  *     
372  * @param   destination Address (in caller's memory space) at which the
373  *          pixel data should be copied
374  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
375  *          is not sufficient to hold the pixel data the copy is not
376  *          executed (i.e. no partial copy).
377  * @return  On success, the number of bytes actually copied. Zero on
378  *          failure e.g. MaxSize is lower than necessary.
379  */
380 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
381 {
382    if ( ! GetRaw() )
383    {
384       // If the decompression failed nothing can be done.
385       return 0;
386    }
387
388    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
389    {
390       if ( PixelReadConverter->GetRGBSize() > maxSize )
391       {
392          gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
393          return 0;
394       }
395       memcpy( destination,
396               (void*)PixelReadConverter->GetRGB(),
397               PixelReadConverter->GetRGBSize() );
398       return PixelReadConverter->GetRGBSize();
399    }
400
401    // Either no LUT conversion necessary or LUT conversion failed
402    if ( PixelReadConverter->GetRawSize() > maxSize )
403    {
404       gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
405       return 0;
406    }
407    memcpy( destination,
408            (void *)PixelReadConverter->GetRaw(),
409            PixelReadConverter->GetRawSize() );
410    return PixelReadConverter->GetRawSize();
411 }
412
413 /**
414  * \brief   Points the internal pointer to the callers inData
415  *          image representation, BUT WITHOUT COPYING THE DATA.
416  *          'image' Pixels are presented as C-like 2D arrays : line per line.
417  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
418  * \warning Since the pixels are not copied, it is the caller's responsability
419  *          not to deallocate its data before gdcm uses them (e.g. with
420  *          the Write() method )
421  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
422  *               user is allowed to pass any kind of pixelsn since the size is
423  *               given in bytes) 
424  * @param expectedSize total image size, *in Bytes*
425  */
426 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
427 {
428    SetUserData(inData, expectedSize);
429 }
430
431 /**
432  * \brief   Set the image data defined by the user
433  * \warning When writting the file, this data are get as default data to write
434  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
435  *               user is allowed to pass any kind of pixels since the size is
436  *               given in bytes) 
437  * @param expectedSize total image size, *in Bytes* 
438  */
439 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
440 {
441    PixelWriteConverter->SetUserData(inData, expectedSize);
442 }
443
444 /**
445  * \brief   Get the image data defined by the user
446  * \warning When writting the file, this data are get as default data to write
447  */
448 uint8_t *FileHelper::GetUserData()
449 {
450    return PixelWriteConverter->GetUserData();
451 }
452
453 /**
454  * \brief   Get the image data size defined by the user
455  * \warning When writting the file, this data are get as default data to write
456  */
457 size_t FileHelper::GetUserDataSize()
458 {
459    return PixelWriteConverter->GetUserDataSize();
460 }
461
462 /**
463  * \brief   Get the image data from the file.
464  *          If a LUT is found, the data are expanded to be RGB
465  */
466 uint8_t *FileHelper::GetRGBData()
467 {
468    return PixelReadConverter->GetRGB();
469 }
470
471 /**
472  * \brief   Get the image data size from the file.
473  *          If a LUT is found, the data are expanded to be RGB
474  */
475 size_t FileHelper::GetRGBDataSize()
476 {
477    return PixelReadConverter->GetRGBSize();
478 }
479
480 /**
481  * \brief   Get the image data from the file.
482  *          Even when a LUT is found, the data are not expanded to RGB!
483  */
484 uint8_t *FileHelper::GetRawData()
485 {
486    return PixelReadConverter->GetRaw();
487 }
488
489 /**
490  * \brief   Get the image data size from the file.
491  *          Even when a LUT is found, the data are not expanded to RGB!
492  */
493 size_t FileHelper::GetRawDataSize()
494 {
495    return PixelReadConverter->GetRawSize();
496 }
497
498 /**
499  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
500  */
501 uint8_t* FileHelper::GetLutRGBA()
502 {
503    if ( PixelReadConverter->GetLutRGBA() ==0 )
504       PixelReadConverter->BuildLUTRGBA();
505    return PixelReadConverter->GetLutRGBA();
506 }
507
508 /**
509  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Number
510  */
511 int FileHelper::GetLutItemNumber()
512 {
513    return PixelReadConverter->GetLutItemNumber();
514 }
515
516 /**
517  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT Item Size
518  */
519 int FileHelper::GetLutItemSize()
520 {
521    return PixelReadConverter->GetLutItemSize();
522 }
523
524 /**
525  * \brief Writes on disk A SINGLE Dicom file
526  *        NO test is performed on  processor "Endiannity".
527  *        It's up to the user to call his Reader properly
528  * @param fileName name of the file to be created
529  *                 (any already existing file is over written)
530  * @return false if write fails
531  */
532 bool FileHelper::WriteRawData(std::string const &fileName)
533 {
534    std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
535    if (!fp1)
536    {
537       gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
538       return false;
539    }
540
541    if( PixelWriteConverter->GetUserData() )
542    {
543       fp1.write( (char *)PixelWriteConverter->GetUserData(), 
544                  PixelWriteConverter->GetUserDataSize() );
545    }
546    else if ( PixelReadConverter->GetRGB() )
547    {
548       fp1.write( (char *)PixelReadConverter->GetRGB(), 
549                  PixelReadConverter->GetRGBSize());
550    }
551    else if ( PixelReadConverter->GetRaw() )
552    {
553       fp1.write( (char *)PixelReadConverter->GetRaw(), 
554                  PixelReadConverter->GetRawSize());
555    }
556    else
557    {
558       gdcmErrorMacro( "Nothing written." );
559    }
560
561    fp1.close();
562
563    return true;
564 }
565
566 /**
567  * \brief Writes on disk A SINGLE Dicom file, 
568  *        using the Implicit Value Representation convention
569  *        NO test is performed on  processor "Endianity".
570  * @param fileName name of the file to be created
571  *                 (any already existing file is overwritten)
572  * @return false if write fails
573  */
574
575 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
576 {
577    SetWriteTypeToDcmImplVR();
578    return Write(fileName);
579 }
580
581 /**
582 * \brief Writes on disk A SINGLE Dicom file, 
583  *        using the Explicit Value Representation convention
584  *        NO test is performed on  processor "Endiannity". 
585  * @param fileName name of the file to be created
586  *                 (any already existing file is overwritten)
587  * @return false if write fails
588  */
589
590 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
591 {
592    SetWriteTypeToDcmExplVR();
593    return Write(fileName);
594 }
595
596 /**
597  * \brief Writes on disk A SINGLE Dicom file, 
598  *        using the ACR-NEMA convention
599  *        NO test is performed on  processor "Endiannity".
600  *        (a l'attention des logiciels cliniques 
601  *        qui ne prennent en entrée QUE des images ACR ...
602  * \warning if a DICOM_V3 header is supplied,
603  *         groups < 0x0008 and shadow groups are ignored
604  * \warning NO TEST is performed on processor "Endiannity".
605  * @param fileName name of the file to be created
606  *                 (any already existing file is overwritten)
607  * @return false if write fails
608  */
609
610 bool FileHelper::WriteAcr (std::string const &fileName)
611 {
612    SetWriteTypeToAcr();
613    return Write(fileName);
614 }
615
616 /**
617  * \brief Writes on disk A SINGLE Dicom file, 
618  * @param fileName name of the file to be created
619  *                 (any already existing file is overwritten)
620  * @return false if write fails
621  */
622 bool FileHelper::Write(std::string const &fileName)
623 {
624    switch(WriteType)
625    {
626       case ImplicitVR:
627          SetWriteFileTypeToImplicitVR();
628          break;
629       case Unknown:  // should never happen; ExplicitVR is the default value
630       case ExplicitVR:
631          SetWriteFileTypeToExplicitVR();
632          break;
633       case ACR:
634       case ACR_LIBIDO:
635       // NOTHING is done here just for LibIDO.
636       // Just to avoid further trouble if user creates a file ex-nihilo,
637       // wants to write it as an ACR-NEMA file,
638       // and forgets to create any Entry belonging to group 0008
639       // (shame on him !)
640       // We add Recognition Code (RET)
641         if ( ! FileInternal->GetValEntry(0x0008, 0x0010) )
642             FileInternal->InsertValEntry("", 0x0008, 0x0010);
643          SetWriteFileTypeToACR();
644         // SetWriteFileTypeToImplicitVR(); // ACR IS implicit VR !
645          break;
646    }
647    CheckMandatoryElements();
648
649    // --------------------------------------------------------------
650    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
651    //
652    // if recognition code tells us we dealt with a LibIDO image
653    // we reproduce on disk the switch between lineNumber and columnNumber
654    // just before writting ...
655    /// \todo the best trick would be *change* the recognition code
656    ///       but pb expected if user deals with, e.g. COMPLEX images
657    
658    if( WriteType == ACR_LIBIDO )
659    {
660       SetWriteToLibido();
661    }
662    else
663    {
664       SetWriteToNoLibido();
665    }
666    // ----------------- End of Special Patch ----------------
667   
668    switch(WriteMode)
669    {
670       case WMODE_RAW :
671          SetWriteToRaw(); // modifies and pushes to the archive, when necessary
672          break;
673       case WMODE_RGB :
674          SetWriteToRGB(); // modifies and pushes to the archive, when necessary
675          break;
676    }
677
678    bool check = CheckWriteIntegrity(); // verifies length
679    if(check)
680    {
681       check = FileInternal->Write(fileName,WriteType);
682    }
683
684    RestoreWrite();
685    RestoreWriteFileType();
686    RestoreWriteMandatory();
687
688    // --------------------------------------------------------------
689    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
690    // 
691    // ...and we restore the header to be Dicom Compliant again 
692    // just after writting
693    RestoreWriteOfLibido();
694    // ----------------- End of Special Patch ----------------
695
696    return check;
697 }
698
699 //-----------------------------------------------------------------------------
700 // Protected
701 /**
702  * \brief Checks the write integrity
703  *
704  * The tests made are :
705  *  - verify the size of the image to write with the possible write
706  *    when the user set an image data
707  * @return true if check is successfull
708  */
709 bool FileHelper::CheckWriteIntegrity()
710 {
711    if(PixelWriteConverter->GetUserData())
712    {
713       int numberBitsAllocated = FileInternal->GetBitsAllocated();
714       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
715       {
716          gdcmWarningMacro( "numberBitsAllocated changed from " 
717                           << numberBitsAllocated << " to 16 " 
718                           << " for consistency purpose" );
719          numberBitsAllocated = 16;
720       }
721
722       size_t decSize = FileInternal->GetXSize()
723                      * FileInternal->GetYSize() 
724                      * FileInternal->GetZSize()
725                      * FileInternal->GetSamplesPerPixel()
726                      * ( numberBitsAllocated / 8 );
727       size_t rgbSize = decSize;
728       if( FileInternal->HasLUT() )
729          rgbSize = decSize * 3;
730
731       switch(WriteMode)
732       {
733          case WMODE_RAW :
734             if( decSize!=PixelWriteConverter->GetUserDataSize() )
735             {
736                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
737                            << decSize << " / Found :" 
738                            << PixelWriteConverter->GetUserDataSize() );
739                return false;
740             }
741             break;
742          case WMODE_RGB :
743             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
744             {
745                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
746                           << decSize << " / Found " 
747                           << PixelWriteConverter->GetUserDataSize() );
748                return false;
749             }
750             break;
751       }
752    }   
753    return true;
754 }
755
756 /**
757  * \brief Updates the File to write RAW data (as opposed to RGB data)
758  *       (modifies, when necessary, photochromatic interpretation, 
759  *       bits allocated, Pixels element VR)
760  */ 
761 void FileHelper::SetWriteToRaw()
762 {
763    if( FileInternal->GetNumberOfScalarComponents() == 3 
764     && !FileInternal->HasLUT())
765    {
766       SetWriteToRGB();
767    } 
768    else
769    {
770       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
771       if(FileInternal->HasLUT())
772       {
773          photInt->SetValue("PALETTE COLOR ");
774       }
775       else
776       {
777          photInt->SetValue("MONOCHROME2 ");
778       }
779
780       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
781                                        PixelReadConverter->GetRawSize());
782
783       std::string vr = "OB";
784       if( FileInternal->GetBitsAllocated()>8 )
785          vr = "OW";
786       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
787          vr = "OB";
788       BinEntry *pixel = 
789          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
790       pixel->SetValue(GDCM_BINLOADED);
791       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
792       pixel->SetLength(PixelWriteConverter->GetDataSize());
793
794       Archive->Push(photInt);
795       Archive->Push(pixel);
796    }
797 }
798
799 /**
800  * \brief Updates the File to write RGB data (as opposed to RAW data)
801  *       (modifies, when necessary, photochromatic interpretation, 
802  *       samples per pixel, Planar configuration, 
803  *       bits allocated, bits stored, high bit -ACR 24 bits-
804  *       Pixels element VR, pushes out the LUT, )
805  */ 
806 void FileHelper::SetWriteToRGB()
807 {
808    if(FileInternal->GetNumberOfScalarComponents()==3)
809    {
810       PixelReadConverter->BuildRGBImage();
811       
812       ValEntry *spp = CopyValEntry(0x0028,0x0002);
813       spp->SetValue("3 ");
814
815       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
816       planConfig->SetValue("0 ");
817
818       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
819       photInt->SetValue("RGB ");
820
821       if(PixelReadConverter->GetRGB())
822       {
823          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
824                                           PixelReadConverter->GetRGBSize());
825       }
826       else // Raw data
827       {
828          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
829                                           PixelReadConverter->GetRawSize());
830       }
831
832       std::string vr = "OB";
833       if( FileInternal->GetBitsAllocated()>8 )
834          vr = "OW";
835       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
836          vr = "OB";
837       BinEntry *pixel = 
838          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
839       pixel->SetValue(GDCM_BINLOADED);
840       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
841       pixel->SetLength(PixelWriteConverter->GetDataSize());
842
843       Archive->Push(spp);
844       Archive->Push(planConfig);
845       Archive->Push(photInt);
846       Archive->Push(pixel);
847
848       // Remove any LUT
849       Archive->Push(0x0028,0x1101);
850       Archive->Push(0x0028,0x1102);
851       Archive->Push(0x0028,0x1103);
852       Archive->Push(0x0028,0x1201);
853       Archive->Push(0x0028,0x1202);
854       Archive->Push(0x0028,0x1203);
855
856       // For old '24 Bits' ACR-NEMA
857       // Thus, we have a RGB image and the bits allocated = 24 and 
858       // samples per pixels = 1 (in the read file)
859       if(FileInternal->GetBitsAllocated()==24) 
860       {
861          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
862          bitsAlloc->SetValue("8 ");
863
864          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
865          bitsStored->SetValue("8 ");
866
867          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
868          highBit->SetValue("7 ");
869
870          Archive->Push(bitsAlloc);
871          Archive->Push(bitsStored);
872          Archive->Push(highBit);
873       }
874    }
875    else
876    {
877       SetWriteToRaw();
878    }
879 }
880
881 /**
882  * \brief Restore the File write mode  
883  */ 
884 void FileHelper::RestoreWrite()
885 {
886    Archive->Restore(0x0028,0x0002);
887    Archive->Restore(0x0028,0x0004);
888    Archive->Restore(0x0028,0x0006);
889    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
890
891    // For old ACR-NEMA (24 bits problem)
892    Archive->Restore(0x0028,0x0100);
893    Archive->Restore(0x0028,0x0101);
894    Archive->Restore(0x0028,0x0102);
895
896    // For the LUT
897    Archive->Restore(0x0028,0x1101);
898    Archive->Restore(0x0028,0x1102);
899    Archive->Restore(0x0028,0x1103);
900    Archive->Restore(0x0028,0x1201);
901    Archive->Restore(0x0028,0x1202);
902    Archive->Restore(0x0028,0x1203);
903
904    // group 0002 may be pushed out for ACR-NEMA writting purposes 
905    Archive->Restore(0x0002,0x0000);
906    Archive->Restore(0x0002,0x0001);
907    Archive->Restore(0x0002,0x0002);
908    Archive->Restore(0x0002,0x0003);
909    Archive->Restore(0x0002,0x0010);
910    Archive->Restore(0x0002,0x0012);
911    Archive->Restore(0x0002,0x0013);
912    Archive->Restore(0x0002,0x0016);
913    Archive->Restore(0x0002,0x0100);
914    Archive->Restore(0x0002,0x0102);
915 }
916
917 /**
918  * \brief Pushes out the whole group 0002
919  *        FIXME : better, set a flag to tell the writer not to write it ...
920  *        FIXME : method should probably have an other name !
921  *                SetWriteFileTypeToACR is NOT opposed to 
922  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
923  */ 
924 void FileHelper::SetWriteFileTypeToACR()
925 {
926    Archive->Push(0x0002,0x0000);
927    Archive->Push(0x0002,0x0001);
928    Archive->Push(0x0002,0x0002);
929    Archive->Push(0x0002,0x0003);
930    Archive->Push(0x0002,0x0010);
931    Archive->Push(0x0002,0x0012);
932    Archive->Push(0x0002,0x0013);
933    Archive->Push(0x0002,0x0016);
934    Archive->Push(0x0002,0x0100);
935    Archive->Push(0x0002,0x0102);
936 }
937
938 /**
939  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
940  */ 
941 void FileHelper::SetWriteFileTypeToExplicitVR()
942 {
943    std::string ts = Util::DicomString( 
944       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
945
946    ValEntry *tss = CopyValEntry(0x0002,0x0010);
947    tss->SetValue(ts);
948
949    Archive->Push(tss);
950 }
951
952 /**
953  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
954  */ 
955 void FileHelper::SetWriteFileTypeToImplicitVR()
956 {
957    std::string ts = Util::DicomString(
958       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
959
960    ValEntry *tss = CopyValEntry(0x0002,0x0010);
961    tss->SetValue(ts);
962
963    Archive->Push(tss);
964 }
965
966
967 /**
968  * \brief Restore in the File the initial group 0002
969  */ 
970 void FileHelper::RestoreWriteFileType()
971 {
972 }
973
974 /**
975  * \brief Set the Write not to Libido format
976  */ 
977 void FileHelper::SetWriteToLibido()
978 {
979    ValEntry *oldRow = dynamic_cast<ValEntry *>
980                 (FileInternal->GetDocEntry(0x0028, 0x0010));
981    ValEntry *oldCol = dynamic_cast<ValEntry *>
982                 (FileInternal->GetDocEntry(0x0028, 0x0011));
983    
984    if( oldRow && oldCol )
985    {
986       std::string rows, columns; 
987
988       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
989       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
990
991       newRow->Copy(oldCol);
992       newCol->Copy(oldRow);
993
994       newRow->SetValue(oldCol->GetValue());
995       newCol->SetValue(oldRow->GetValue());
996
997       Archive->Push(newRow);
998       Archive->Push(newCol);
999    }
1000
1001    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
1002    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
1003    Archive->Push(libidoCode);
1004 }
1005
1006 /**
1007  * \brief Set the Write not to No Libido format
1008  */ 
1009 void FileHelper::SetWriteToNoLibido()
1010 {
1011    ValEntry *recCode = dynamic_cast<ValEntry *>
1012                 (FileInternal->GetDocEntry(0x0008,0x0010));
1013    if( recCode )
1014    {
1015       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
1016       {
1017          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
1018          libidoCode->SetValue("");
1019          Archive->Push(libidoCode);
1020       }
1021    }
1022 }
1023
1024 /**
1025  * \brief Restore the Write format
1026  */ 
1027 void FileHelper::RestoreWriteOfLibido()
1028 {
1029    Archive->Restore(0x0028,0x0010);
1030    Archive->Restore(0x0028,0x0011);
1031    Archive->Restore(0x0008,0x0010);
1032
1033    // Restore 'LibIDO-special' entries, if any
1034    Archive->Restore(0x0028,0x0015);
1035    Archive->Restore(0x0028,0x0016);
1036    Archive->Restore(0x0028,0x0017);
1037    Archive->Restore(0x0028,0x00199);
1038 }
1039
1040 /**
1041  * \brief Duplicates a ValEntry or creates it.
1042  * @param   group   Group number of the Entry 
1043  * @param   elem  Element number of the Entry
1044  * \return  pointer to the new Val Entry (NULL when creation failed).          
1045  */ 
1046 ValEntry *FileHelper::CopyValEntry(uint16_t group, uint16_t elem)
1047 {
1048    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1049    ValEntry *newE;
1050
1051    if( oldE )
1052    {
1053       newE = new ValEntry(oldE->GetDictEntry());
1054       newE->Copy(oldE);
1055    }
1056    else
1057    {
1058       newE = GetFile()->NewValEntry(group, elem);
1059    }
1060
1061    return newE;
1062 }
1063
1064 /**
1065  * \brief   Duplicates a BinEntry or creates it.
1066  * @param   group   Group number of the Entry 
1067  * @param   elem  Element number of the Entry
1068  * @param   vr  Value Representation of the Entry
1069  *          FIXME : what is it used for?
1070  * \return  pointer to the new Bin Entry (NULL when creation failed).
1071  */ 
1072 BinEntry *FileHelper::CopyBinEntry(uint16_t group, uint16_t elem,
1073                                    const std::string &vr)
1074 {
1075    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1076    BinEntry *newE;
1077
1078    if( oldE ) 
1079       if( oldE->GetVR()!=vr )
1080          oldE = NULL;
1081
1082    if( oldE )
1083    {
1084       newE = new BinEntry(oldE->GetDictEntry());
1085       newE->Copy(oldE);
1086    }
1087    else
1088    {
1089       newE = GetFile()->NewBinEntry(group, elem, vr);
1090    }
1091
1092    return newE;
1093 }
1094
1095 /**
1096  * \brief   This method is called automatically, just before writting
1097  *         in order to produce a 'True Dicom V3' image
1098  *         We cannot know *how* the user made the File (reading an old ACR-NEMA
1099  *         file or a not very clean DICOM file ...) 
1100  *          
1101  *          Just before writting :
1102  *             - we check the Entries
1103  *             - we create the mandatory entries if they are missing
1104  *             - we modify the values if necessary
1105  *             - we push the sensitive entries to the Archive
1106  *          The writing process will restore the entries as they where before 
1107  *          entering FileHelper::CheckMandatoryElements, so the user will always
1108  *          see the entries just as he left them.
1109  * 
1110  * \todo : - warn the user if we had to add some entries :
1111  *         even if a mandatory entry is missing, we add it, with a default value
1112  *         (we don't want to give up the writting process if user forgot to
1113  *         specify Lena's Patient ID, for instance ...)
1114  *         - read the whole PS 3.3 Part of DICOM  (890 pages)
1115  *         and write a *full* checker (probably one method per Modality ...)
1116  *         Any contribution is welcome. 
1117  *         - write a user callable full checker, to allow post reading
1118  *         and/or pre writting image consistency check.           
1119  */ 
1120  
1121 void FileHelper::CheckMandatoryElements()
1122 {
1123    // just to remember : 'official' 0002 group
1124    if ( WriteType != ACR && WriteType != ACR_LIBIDO )
1125    {
1126      // Group 000002 (Meta Elements) already pushed out
1127   
1128    //0002 0000 UL 1 Meta Group Length
1129    //0002 0001 OB 1 File Meta Information Version
1130    //0002 0002 UI 1 Media Stored SOP Class UID
1131    //0002 0003 UI 1 Media Stored SOP Instance UID
1132    //0002 0010 UI 1 Transfer Syntax UID
1133    //0002 0012 UI 1 Implementation Class UID
1134    //0002 0013 SH 1 Implementation Version Name
1135    //0002 0016 AE 1 Source Application Entity Title
1136    //0002 0100 UI 1 Private Information Creator
1137    //0002 0102 OB 1 Private Information
1138   
1139    // Create them if not found
1140    // Always modify the value
1141    // Push the entries to the archive.
1142       ValEntry *e_0002_0000 = CopyValEntry(0x0002,0x0000);
1143       e_0002_0000->SetValue("0"); // for the moment
1144       Archive->Push(e_0002_0000);
1145   
1146       BinEntry *e_0002_0001 = CopyBinEntry(0x0002,0x0001, "OB");
1147       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1148                                false);
1149       e_0002_0001->SetLength(2);
1150       Archive->Push(e_0002_0001);
1151
1152    // 'Media Stored SOP Class UID' 
1153       ValEntry *e_0002_0002 = CopyValEntry(0x0002,0x0002);
1154       // [Secondary Capture Image Storage]
1155       e_0002_0002->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1156       Archive->Push(e_0002_0002);
1157  
1158    // 'Media Stored SOP Instance UID'   
1159       ValEntry *e_0002_0003 = CopyValEntry(0x0002,0x0003);
1160       e_0002_0003->SetValue(Util::CreateUniqueUID());
1161       Archive->Push(e_0002_0003); 
1162
1163    // 'Implementation Class UID'
1164       ValEntry *e_0002_0012 = CopyValEntry(0x0002,0x0012);
1165       e_0002_0012->SetValue(Util::CreateUniqueUID());
1166       Archive->Push(e_0002_0012); 
1167
1168    // 'Implementation Version Name'
1169       ValEntry *e_0002_0013 = CopyValEntry(0x0002,0x0013);
1170       e_0002_0013->SetValue("GDCM 1.0");
1171       Archive->Push(e_0002_0013);
1172
1173    //'Source Application Entity Title' Not Mandatory
1174    //ValEntry *e_0002_0016 = CopyValEntry(0x0002,0x0016);
1175    //   e_0002_0016->SetValue("1.2.840.10008.5.1.4.1.1.7");
1176    //   Archive->Push(e_0002_0016);
1177    }
1178
1179    // Push out 'LibIDO-special' entries, if any
1180    Archive->Push(0x0028,0x0015);
1181    Archive->Push(0x0028,0x0016);
1182    Archive->Push(0x0028,0x0017);
1183    Archive->Push(0x0028,0x00199);
1184
1185    // Deal with the pb of (Bits Stored = 12)
1186    // - we're gonna write the image as Bits Stored = 16
1187    if ( FileInternal->GetEntryValue(0x0028,0x0100) ==  "12")
1188    {
1189       ValEntry *e_0028_0100 = CopyValEntry(0x0028,0x0100);
1190       e_0028_0100->SetValue("16");
1191       Archive->Push(e_0028_0100);
1192    }
1193
1194    // Check if user wasn't drunk ;-)
1195
1196    std::ostringstream s;
1197    // check 'Bits Allocated' vs decent values
1198    int nbBitsAllocated = FileInternal->GetBitsAllocated();
1199    if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1200    {
1201       ValEntry *e_0028_0100 = CopyValEntry(0x0028,0x0100);
1202       e_0028_0100->SetValue("16");
1203       Archive->Push(e_0028_0100); 
1204       gdcmWarningMacro("(0028,0100) changed from "
1205          << nbBitsAllocated << " to 16 for consistency purpose");
1206       nbBitsAllocated = 16; 
1207    }
1208    // check 'Bits Stored' vs 'Bits Allocated'   
1209    int nbBitsStored = FileInternal->GetBitsStored();
1210    if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1211    {
1212       s << nbBitsAllocated;
1213       ValEntry *e_0028_0101 = CopyValEntry(0x0028,0x0101);
1214       e_0028_0101->SetValue( s.str() );
1215       Archive->Push(e_0028_0101);
1216       gdcmWarningMacro("(0028,0101) changed from "
1217                        << nbBitsStored << " to " << nbBitsAllocated
1218                        << " for consistency purpose" );
1219       nbBitsStored = nbBitsAllocated; 
1220     }
1221    // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1222    int highBitPosition = FileInternal->GetHighBitPosition();
1223    if ( highBitPosition == 0 || 
1224         highBitPosition > nbBitsAllocated-1 ||
1225         highBitPosition < nbBitsStored-1  )
1226    {
1227       ValEntry *e_0028_0102 = CopyValEntry(0x0028,0x0102);
1228
1229       s << nbBitsStored - 1; 
1230       e_0028_0102->SetValue( s.str() );
1231       Archive->Push(e_0028_0102);
1232       gdcmWarningMacro("(0028,0102) changed from "
1233                        << highBitPosition << " to " << nbBitsAllocated-1
1234                        << " for consistency purpose");
1235    }
1236   // --- Check UID-related Entries ---
1237
1238    // If 'SOP Class UID' exists ('true DICOM' image)
1239    // we create the 'Source Image Sequence' SeqEntry
1240    // to hold informations about the Source Image
1241
1242    ValEntry *e_0008_0016 = FileInternal->GetValEntry(0x0008, 0x0016);
1243    if ( e_0008_0016 != 0 )
1244    {
1245       // Create 'Source Image Sequence' SeqEntry
1246       SeqEntry *sis = new SeqEntry (
1247             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1248       SQItem *sqi = new SQItem(1);
1249       // (we assume 'SOP Instance UID' exists too) 
1250       // create 'Referenced SOP Class UID'
1251       ValEntry *e_0008_1150 = new ValEntry(
1252             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1253       e_0008_1150->SetValue( e_0008_0016->GetValue());
1254       sqi->AddEntry(e_0008_1150);
1255       
1256       // create 'Referenced SOP Instance UID'
1257       ValEntry *e_0008_0018 = FileInternal->GetValEntry(0x0008, 0x0018);
1258       ValEntry *e_0008_1155 = new ValEntry(
1259             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1260       e_0008_1155->SetValue( e_0008_0018->GetValue());
1261       sqi->AddEntry(e_0008_1155);
1262
1263       sis->AddSQItem(sqi,1); 
1264       // temporarily replaces any previous 'Source Image Sequence' 
1265       Archive->Push(sis);
1266  
1267       // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1268       ValEntry *e_0008_0008 = CopyValEntry(0x0008,0x0008);
1269       e_0008_0008->SetValue("DERIVED\\PRIMARY");
1270       Archive->Push(e_0008_0008);
1271    } 
1272    else
1273    {
1274       // There was no 'SOP Class UID'.
1275       // the source image was NOT a true Dicom one.
1276       // We consider the image is a 'Secondary Capture' one
1277       // SOP Class UID
1278       e_0008_0016  =  new ValEntry( 
1279             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0016) );
1280       // [Secondary Capture Image Storage]
1281       e_0008_0016 ->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1282       Archive->Push(e_0008_0016); 
1283    }
1284
1285 // ---- The user will never have to take any action on the following ----.
1286
1287    // new value for 'SOP Instance UID'
1288    ValEntry *e_0008_0018 = new ValEntry(
1289          Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0018) );
1290    e_0008_0018->SetValue( Util::CreateUniqueUID() );
1291    Archive->Push(e_0008_0018);
1292
1293    // Instance Creation Date
1294    ValEntry *e_0008_0012 = CopyValEntry(0x0008,0x0012);
1295    std::string date = Util::GetCurrentDate();
1296    e_0008_0012->SetValue(date.c_str());
1297    Archive->Push(e_0008_0012);
1298  
1299    // Instance Creation Time
1300    ValEntry *e_0008_0013 = CopyValEntry(0x0008,0x0013);
1301    std::string time = Util::GetCurrentTime();
1302    e_0008_0013->SetValue(time.c_str());
1303    Archive->Push(e_0008_0013);
1304
1305 // ----- Add Mandatory Entries if missing ---
1306
1307 // Entries whose type is 1 are mandatory, with a mandatory value
1308 // Entries whose type is 1c are mandatory-inside-a-Sequence
1309 // Entries whose type is 2 are mandatory, with a optional value
1310 // Entries whose type is 2c are mandatory-inside-a-Sequence
1311 // Entries whose type is 3 are optional
1312
1313    // 'Serie Instance UID'
1314    // Keep the value if exists
1315    // The user is allowed to create his own Series, 
1316    // keeping the same 'Serie Instance UID' for various images
1317    // The user shouldn't add any image to a 'Manufacturer Serie'
1318    // but there is no way no to allowed him to do that 
1319    ValEntry *e_0020_000e = FileInternal->GetValEntry(0x0020, 0x000e);
1320    if ( !e_0020_000e )
1321    {
1322       e_0020_000e = new ValEntry(
1323            Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000e) );
1324       e_0020_000e->SetValue(Util::CreateUniqueUID() );
1325       Archive->Push(e_0020_000e);
1326    } 
1327
1328    // 'Study Instance UID'
1329    // Keep the value if exists
1330    // The user is allowed to create his own Study, 
1331    //          keeping the same 'Study Instance UID' for various images
1332    // The user may add images to a 'Manufacturer Study',
1333    //          adding new series to an already existing Study 
1334    ValEntry *e_0020_000d = FileInternal->GetValEntry(0x0020, 0x000d);
1335    if ( !e_0020_000d )
1336    {
1337       e_0020_000d = new ValEntry(
1338             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000d) );
1339       e_0020_000d->SetValue(Util::CreateUniqueUID() );
1340       Archive->Push(e_0020_000d);
1341    }
1342
1343    // Modality : if missing we set it to 'OTher'
1344    ValEntry *e_0008_0060 = FileInternal->GetValEntry(0x0008, 0x0060);
1345    if ( !e_0008_0060 )
1346    {
1347       e_0008_0060 = new ValEntry(
1348             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0060) );
1349       e_0008_0060->SetValue("OT");
1350       Archive->Push(e_0008_0060);
1351    } 
1352
1353    // Manufacturer : if missing we set it to 'GDCM Factory'
1354    ValEntry *e_0008_0070 = FileInternal->GetValEntry(0x0008, 0x0070);
1355    if ( !e_0008_0070 )
1356    {
1357       e_0008_0070 = new ValEntry(
1358             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0070) );
1359       e_0008_0070->SetValue("GDCM Factory");
1360       Archive->Push(e_0008_0070);
1361    } 
1362
1363    // Institution Name : if missing we set it to 'GDCM Hospital'
1364    ValEntry *e_0008_0080 = FileInternal->GetValEntry(0x0008, 0x0080);
1365    if ( !e_0008_0080 )
1366    {
1367       e_0008_0080 = new ValEntry(
1368             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0080) );
1369       e_0008_0080->SetValue("GDCM Hospital");
1370       Archive->Push(e_0008_0080);
1371    } 
1372
1373    // Patient's Name : if missing, we set it to 'GDCM^Patient'
1374    ValEntry *e_0010_0010 = FileInternal->GetValEntry(0x0010, 0x0010);
1375    if ( !e_0010_0010 )
1376    {
1377       e_0010_0010 = new ValEntry(
1378             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0010) );
1379       e_0010_0010->SetValue("GDCM^Patient");
1380       Archive->Push(e_0010_0010);
1381    } 
1382
1383    // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1384    ValEntry *e_0010_0030 = FileInternal->GetValEntry(0x0010, 0x0030);
1385    if ( !e_0010_0030 )
1386    {
1387       e_0010_0030 = new ValEntry(
1388             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0030) );
1389       e_0010_0030->SetValue("");
1390       Archive->Push(e_0010_0030);
1391    }
1392
1393    // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1394    ValEntry *e_0010_0040 = FileInternal->GetValEntry(0x0010, 0x0040);
1395    if ( !e_0010_0040 )
1396    {
1397       e_0010_0040 = new ValEntry(
1398             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0040) );
1399       e_0010_0040->SetValue("");
1400       Archive->Push(e_0010_0040);
1401    }
1402
1403    // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1404    ValEntry *e_0008_0090 = FileInternal->GetValEntry(0x0008, 0x0090);
1405    if ( !e_0008_0090 )
1406    {
1407       e_0008_0090 = new ValEntry(
1408             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0090) );
1409       e_0008_0090->SetValue("");
1410       Archive->Push(e_0008_0090);
1411    }
1412  
1413    // Remove some inconstencies (probably some more will be added)
1414
1415    // if (0028 0008)Number of Frames exists
1416    //    Push out (0020 0052),Frame of Reference UID
1417    //    (only meaningfull within a Serie)
1418    ValEntry *e_0028_0008 = FileInternal->GetValEntry(0x0028, 0x0008);
1419    if ( !e_0028_0008 )
1420    {
1421       Archive->Push(0x0020, 0X0052);
1422    }
1423
1424  
1425 /**
1426  * \brief Restore in the File the initial group 0002
1427  */
1428 void FileHelper::RestoreWriteMandatory()
1429 {
1430    // group 0002 may be pushed out for ACR-NEMA writting purposes 
1431    Archive->Restore(0x0002,0x0000);
1432    Archive->Restore(0x0002,0x0001);
1433    Archive->Restore(0x0002,0x0002);
1434    Archive->Restore(0x0002,0x0003);
1435    Archive->Restore(0x0002,0x0010);
1436    Archive->Restore(0x0002,0x0012);
1437    Archive->Restore(0x0002,0x0013);
1438    Archive->Restore(0x0002,0x0016);
1439    Archive->Restore(0x0002,0x0100);
1440    Archive->Restore(0x0002,0x0102);
1441
1442    Archive->Restore(0x0008,0x0012);
1443    Archive->Restore(0x0008,0x0013);
1444    Archive->Restore(0x0008,0x0016);
1445    Archive->Restore(0x0008,0x0018);
1446    Archive->Restore(0x0008,0x0060);
1447    Archive->Restore(0x0008,0x0070);
1448    Archive->Restore(0x0008,0x0080);
1449    Archive->Restore(0x0008,0x0090);
1450    Archive->Restore(0x0008,0x2112);
1451
1452    Archive->Restore(0x0010,0x0010);
1453    Archive->Restore(0x0010,0x0030);
1454    Archive->Restore(0x0010,0x0040);
1455
1456    Archive->Restore(0x0020,0x000d);
1457    Archive->Restore(0x0020,0x000e);
1458
1459 }
1460
1461 //-----------------------------------------------------------------------------
1462 // Private
1463 /**
1464  * \brief Factorization for various forms of constructors.
1465  */
1466 void FileHelper::Initialize()
1467 {
1468    WriteMode = WMODE_RAW;
1469    WriteType = ExplicitVR;
1470
1471    PixelReadConverter  = new PixelReadConvert;
1472    PixelWriteConverter = new PixelWriteConvert;
1473    Archive = new DocEntryArchive( FileInternal );
1474
1475    if ( FileInternal->IsReadable() )
1476    {
1477       PixelReadConverter->GrabInformationsFromFile( FileInternal );
1478    }
1479 }
1480
1481 /**
1482  * \brief Reads/[decompresses] the pixels, 
1483  *        *without* making RGB from Palette Colors 
1484  * @return the pixels area, whatever its type 
1485  *         (uint8_t is just for prototyping : feel free to Cast it) 
1486  */ 
1487 uint8_t *FileHelper::GetRaw()
1488 {
1489    uint8_t *raw = PixelReadConverter->GetRaw();
1490    if ( ! raw )
1491    {
1492       // The Raw image migth not be loaded yet:
1493       std::ifstream *fp = FileInternal->OpenFile();
1494       PixelReadConverter->ReadAndDecompressPixelData( fp );
1495       if(fp) 
1496          FileInternal->CloseFile();
1497
1498       raw = PixelReadConverter->GetRaw();
1499       if ( ! raw )
1500       {
1501          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1502          return 0;
1503       }
1504    }
1505    return raw;
1506 }
1507
1508 //-----------------------------------------------------------------------------
1509 /**
1510  * \brief   Prints the common part of ValEntry, BinEntry, SeqEntry
1511  * @param   os ostream we want to print in
1512  * @param indent (unused)
1513  */
1514 void FileHelper::Print(std::ostream &os, std::string const &)
1515 {
1516    FileInternal->SetPrintLevel(PrintLevel);
1517    FileInternal->Print(os);
1518
1519    PixelReadConverter->SetPrintLevel(PrintLevel);
1520    PixelReadConverter->Print(os);
1521 }
1522
1523 //-----------------------------------------------------------------------------
1524 } // end namespace gdcm