]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
Typo
[gdcm.git] / src / gdcmFileHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFileHelper.cxx,v $
5   Language:  C++
6
7   Date:      $Date: 2005/03/11 11:12:13 $
8   Version:   $Revision: 1.30 $
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
289    return PixelReadConverter->GetRGBSize();
290 }
291
292 /**
293  * \brief   Get the size of the image data
294  *          If the image could be converted to RGB using a LUT, 
295  *          this transformation is not taken into account by GetImageDataRawSize
296  *          (use GetImageDataSize if you wish)
297  * @return  The raw image size
298  */
299 size_t FileHelper::GetImageDataRawSize()
300 {
301    if ( PixelWriteConverter->GetUserData() )
302    {
303       return PixelWriteConverter->GetUserDataSize();
304    }
305
306    return PixelReadConverter->GetRawSize();
307 }
308
309 /**
310  * \brief   - Allocates necessary memory,
311  *          - Reads the pixels from disk (uncompress if necessary),
312  *          - Transforms YBR pixels, if any, into RGB pixels,
313  *          - Transforms 3 planes R, G, B, if any, into a single RGB Plane
314  *          - Transforms single Grey plane + 3 Palettes into a RGB Plane
315  *          - Copies the pixel data (image[s]/volume[s]) to newly allocated zone.
316  * @return  Pointer to newly allocated pixel data.
317  *          NULL if alloc fails 
318  */
319 uint8_t *FileHelper::GetImageData()
320 {
321    if ( PixelWriteConverter->GetUserData() )
322    {
323       return PixelWriteConverter->GetUserData();
324    }
325
326    if ( ! GetRaw() )
327    {
328       // If the decompression failed nothing can be done.
329       return 0;
330    }
331
332    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
333    {
334       return PixelReadConverter->GetRGB();
335    }
336    else
337    {
338       // When no LUT or LUT conversion fails, return the Raw
339       return PixelReadConverter->GetRaw();
340    }
341 }
342
343 /**
344  * \brief   Allocates necessary memory, 
345  *          Transforms YBR pixels (if any) into RGB pixels
346  *          Transforms 3 planes R, G, B  (if any) into a single RGB Plane
347  *          Copies the pixel data (image[s]/volume[s]) to newly allocated zone. 
348  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
349  * @return  Pointer to newly allocated pixel data.
350  *          NULL if alloc fails 
351  */
352 uint8_t *FileHelper::GetImageDataRaw ()
353 {
354    return GetRaw();
355 }
356
357 /**
358  * \brief
359  *          Read the pixels from disk (uncompress if necessary),
360  *          Transforms YBR pixels, if any, into RGB pixels
361  *          Transforms 3 planes R, G, B, if any, into a single RGB Plane
362  *          Transforms single Grey plane + 3 Palettes into a RGB Plane   
363  *          Copies at most MaxSize bytes of pixel data to caller allocated
364  *          memory space.
365  * \warning This function allows people that want to build a volume
366  *          from an image stack *not to* have, first to get the image pixels, 
367  *          and then move them to the volume area.
368  *          It's absolutely useless for any VTK user since vtk chooses 
369  *          to invert the lines of an image, that is the last line comes first
370  *          (for some axis related reasons?). Hence he will have 
371  *          to load the image line by line, starting from the end.
372  *          VTK users have to call GetImageData
373  *     
374  * @param   destination Address (in caller's memory space) at which the
375  *          pixel data should be copied
376  * @param   maxSize Maximum number of bytes to be copied. When MaxSize
377  *          is not sufficient to hold the pixel data the copy is not
378  *          executed (i.e. no partial copy).
379  * @return  On success, the number of bytes actually copied. Zero on
380  *          failure e.g. MaxSize is lower than necessary.
381  */
382 size_t FileHelper::GetImageDataIntoVector (void *destination, size_t maxSize)
383 {
384    if ( ! GetRaw() )
385    {
386       // If the decompression failed nothing can be done.
387       return 0;
388    }
389
390    if ( FileInternal->HasLUT() && PixelReadConverter->BuildRGBImage() )
391    {
392       if ( PixelReadConverter->GetRGBSize() > maxSize )
393       {
394          gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
395          return 0;
396       }
397       memcpy( destination,
398               (void*)PixelReadConverter->GetRGB(),
399               PixelReadConverter->GetRGBSize() );
400       return PixelReadConverter->GetRGBSize();
401    }
402
403    // Either no LUT conversion necessary or LUT conversion failed
404    if ( PixelReadConverter->GetRawSize() > maxSize )
405    {
406       gdcmWarningMacro( "Pixel data bigger than caller's expected MaxSize");
407       return 0;
408    }
409    memcpy( destination,
410            (void*)PixelReadConverter->GetRaw(),
411            PixelReadConverter->GetRawSize() );
412    return PixelReadConverter->GetRawSize();
413 }
414
415 /**
416  * \brief   Points the internal pointer to the callers inData
417  *          image representation, BUT WITHOUT COPYING THE DATA.
418  *          'image' Pixels are presented as C-like 2D arrays : line per line.
419  *          'volume'Pixels are presented as C-like 3D arrays : plane per plane 
420  * \warning Since the pixels are not copied, it is the caller's responsability
421  *          not to deallocate its data before gdcm uses them (e.g. with
422  *          the Write() method )
423  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
424  *               user is allowed to pass any kind of pixelsn since the size is
425  *               given in bytes) 
426  * @param expectedSize total image size, *in Bytes*
427  */
428 void FileHelper::SetImageData(uint8_t *inData, size_t expectedSize)
429 {
430    SetUserData(inData, expectedSize);
431 }
432
433 /**
434  * \brief   Set the image data defined by the user
435  * \warning When writting the file, this data are get as default data to write
436  * @param inData user supplied pixel area (uint8_t* is just for the compiler.
437  *               user is allowed to pass any kind of pixels since the size is
438  *               given in bytes) 
439  * @param expectedSize total image size, *in Bytes* 
440  */
441 void FileHelper::SetUserData(uint8_t *inData, size_t expectedSize)
442 {
443    PixelWriteConverter->SetUserData(inData, expectedSize);
444 }
445
446 /**
447  * \brief   Get the image data defined by the user
448  * \warning When writting the file, this data are get as default data to write
449  */
450 uint8_t *FileHelper::GetUserData()
451 {
452    return PixelWriteConverter->GetUserData();
453 }
454
455 /**
456  * \brief   Get the image data size defined by the user
457  * \warning When writting the file, this data are get as default data to write
458  */
459 size_t FileHelper::GetUserDataSize()
460 {
461    return PixelWriteConverter->GetUserDataSize();
462 }
463
464 /**
465  * \brief   Get the image data from the file.
466  *          If a LUT is found, the data are expanded to be RGB
467  */
468 uint8_t *FileHelper::GetRGBData()
469 {
470    return PixelReadConverter->GetRGB();
471 }
472
473 /**
474  * \brief   Get the image data size from the file.
475  *          If a LUT is found, the data are expanded to be RGB
476  */
477 size_t FileHelper::GetRGBDataSize()
478 {
479    return PixelReadConverter->GetRGBSize();
480 }
481
482 /**
483  * \brief   Get the image data from the file.
484  *          Even when a LUT is found, the data are not expanded to RGB!
485  */
486 uint8_t *FileHelper::GetRawData()
487 {
488    return PixelReadConverter->GetRaw();
489 }
490
491 /**
492  * \brief   Get the image data size from the file.
493  *          Even when a LUT is found, the data are not expanded to RGB!
494  */
495 size_t FileHelper::GetRawDataSize()
496 {
497    return PixelReadConverter->GetRawSize();
498 }
499
500 /**
501  * \brief Access to the underlying \ref PixelReadConverter RGBA LUT
502  */
503 uint8_t* FileHelper::GetLutRGBA()
504 {
505    return PixelReadConverter->GetLutRGBA();
506 }
507
508 /**
509  * \brief Writes on disk A SINGLE Dicom file
510  *        NO test is performed on  processor "Endiannity".
511  *        It's up to the user to call his Reader properly
512  * @param fileName name of the file to be created
513  *                 (any already existing file is over written)
514  * @return false if write fails
515  */
516 bool FileHelper::WriteRawData(std::string const &fileName)
517 {
518    std::ofstream fp1(fileName.c_str(), std::ios::out | std::ios::binary );
519    if (!fp1)
520    {
521       gdcmWarningMacro( "Fail to open (write) file:" << fileName.c_str());
522       return false;
523    }
524
525    if( PixelWriteConverter->GetUserData() )
526    {
527       fp1.write( (char*)PixelWriteConverter->GetUserData(), 
528                  PixelWriteConverter->GetUserDataSize() );
529    }
530    else if ( PixelReadConverter->GetRGB() )
531    {
532       fp1.write( (char*)PixelReadConverter->GetRGB(), 
533                  PixelReadConverter->GetRGBSize());
534    }
535    else if ( PixelReadConverter->GetRaw() )
536    {
537       fp1.write( (char*)PixelReadConverter->GetRaw(), 
538                  PixelReadConverter->GetRawSize());
539    }
540    else
541    {
542       gdcmErrorMacro( "Nothing written." );
543    }
544
545    fp1.close();
546
547    return true;
548 }
549
550 /**
551  * \brief Writes on disk A SINGLE Dicom file, 
552  *        using the Implicit Value Representation convention
553  *        NO test is performed on  processor "Endiannity".
554  * @param fileName name of the file to be created
555  *                 (any already existing file is overwritten)
556  * @return false if write fails
557  */
558
559 bool FileHelper::WriteDcmImplVR (std::string const &fileName)
560 {
561    SetWriteTypeToDcmImplVR();
562    return Write(fileName);
563 }
564
565 /**
566 * \brief Writes on disk A SINGLE Dicom file, 
567  *        using the Explicit Value Representation convention
568  *        NO test is performed on  processor "Endiannity". 
569  * @param fileName name of the file to be created
570  *                 (any already existing file is overwritten)
571  * @return false if write fails
572  */
573
574 bool FileHelper::WriteDcmExplVR (std::string const &fileName)
575 {
576    SetWriteTypeToDcmExplVR();
577    return Write(fileName);
578 }
579
580 /**
581  * \brief Writes on disk A SINGLE Dicom file, 
582  *        using the ACR-NEMA convention
583  *        NO test is performed on  processor "Endiannity".
584  *        (a l'attention des logiciels cliniques 
585  *        qui ne prennent en entrée QUE des images ACR ...
586  * \warning if a DICOM_V3 header is supplied,
587  *         groups < 0x0008 and shadow groups are ignored
588  * \warning NO TEST is performed on processor "Endiannity".
589  * @param fileName name of the file to be created
590  *                 (any already existing file is overwritten)
591  * @return false if write fails
592  */
593
594 bool FileHelper::WriteAcr (std::string const &fileName)
595 {
596    SetWriteTypeToAcr();
597    return Write(fileName);
598 }
599
600 /**
601  * \brief Writes on disk A SINGLE Dicom file, 
602  * @param fileName name of the file to be created
603  *                 (any already existing file is overwritten)
604  * @return false if write fails
605  */
606 bool FileHelper::Write(std::string const &fileName)
607 {
608    switch(WriteType)
609    {
610       case ImplicitVR:
611          SetWriteFileTypeToImplicitVR();
612          CheckMandatoryElements();
613          break;
614       case ExplicitVR:
615          SetWriteFileTypeToExplicitVR();
616          CheckMandatoryElements();
617          break;
618       case ACR:
619       case ACR_LIBIDO:
620       // Just to avoid further trouble if user create a file ex-nihilo,
621       // wants to write it as an ACR-NEMA file,
622       // and forget to create any Entry belonging to group 0008
623       // (shame on him !)
624       // We add Recognition Code (RET)
625         if ( ! FileInternal->GetValEntry(0x0008, 0x0010) )
626             FileInternal->InsertValEntry("", 0x0008, 0x0010);
627          SetWriteFileTypeToACR();
628          break;
629       default:
630          SetWriteFileTypeToExplicitVR();
631          CheckMandatoryElements();
632    }
633
634    // --------------------------------------------------------------
635    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
636    //
637    // if recognition code tells us we dealt with a LibIDO image
638    // we reproduce on disk the switch between lineNumber and columnNumber
639    // just before writting ...
640    /// \todo the best trick would be *change* the recognition code
641    ///       but pb expected if user deals with, e.g. COMPLEX images
642    if( WriteType == ACR_LIBIDO )
643    {
644       SetWriteToLibido();
645    }
646    else
647    {
648       SetWriteToNoLibido();
649    }
650    // ----------------- End of Special Patch ----------------
651   
652    switch(WriteMode)
653    {
654       case WMODE_RAW :
655          SetWriteToRaw(); // modifies and pushes to the archive, when necessary
656          break;
657       case WMODE_RGB :
658          SetWriteToRGB(); // modifies and pushes to the archive, when necessary
659          break;
660    }
661
662    bool check = CheckWriteIntegrity(); // verifies length
663    if(check)
664    {
665       check = FileInternal->Write(fileName,WriteType);
666    }
667
668    RestoreWrite();
669    RestoreWriteFileType();
670    RestoreWriteMandatory();
671
672    // --------------------------------------------------------------
673    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
674    // 
675    // ...and we restore the header to be Dicom Compliant again 
676    // just after writting
677    RestoreWriteOfLibido();
678    // ----------------- End of Special Patch ----------------
679
680    return check;
681 }
682
683 //-----------------------------------------------------------------------------
684 // Protected
685 /**
686  * \brief Checks the write integrity
687  *
688  * The tests made are :
689  *  - verify the size of the image to write with the possible write
690  *    when the user set an image data
691  * @return true if check is successfull
692  */
693 bool FileHelper::CheckWriteIntegrity()
694 {
695    if(PixelWriteConverter->GetUserData())
696    {
697       int numberBitsAllocated = FileInternal->GetBitsAllocated();
698       if ( numberBitsAllocated == 0 || numberBitsAllocated == 12 )
699       {
700          numberBitsAllocated = 16;
701       }
702
703       size_t decSize = FileInternal->GetXSize()
704                     * FileInternal->GetYSize() 
705                     * FileInternal->GetZSize()
706                     * ( numberBitsAllocated / 8 )
707                     * FileInternal->GetSamplesPerPixel();
708       size_t rgbSize = decSize;
709       if( FileInternal->HasLUT() )
710          rgbSize = decSize * 3;
711
712       switch(WriteMode)
713       {
714          case WMODE_RAW :
715             if( decSize!=PixelWriteConverter->GetUserDataSize() )
716             {
717                gdcmWarningMacro( "Data size (Raw) is incorrect. Should be " 
718                            << decSize << " / Found :" 
719                            << PixelWriteConverter->GetUserDataSize() );
720                return false;
721             }
722             break;
723          case WMODE_RGB :
724             if( rgbSize!=PixelWriteConverter->GetUserDataSize() )
725             {
726                gdcmWarningMacro( "Data size (RGB) is incorrect. Should be " 
727                           << decSize << " / Found " 
728                           << PixelWriteConverter->GetUserDataSize() );
729                return false;
730             }
731             break;
732       }
733    }
734    
735    return true;
736 }
737
738 /**
739  * \brief Updates the File to write RAW data (as opposed to RGB data)
740  *       (modifies, when necessary, photochromatic interpretation, 
741  *       bits allocated, Pixels element VR)
742  */ 
743 void FileHelper::SetWriteToRaw()
744 {
745    if( FileInternal->GetNumberOfScalarComponents() == 3 
746     && !FileInternal->HasLUT())
747    {
748       SetWriteToRGB();
749    } 
750    else
751    {
752       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
753       if(FileInternal->HasLUT())
754       {
755          photInt->SetValue("PALETTE COLOR ");
756       }
757       else
758       {
759          photInt->SetValue("MONOCHROME2 ");
760       }
761
762       PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
763                                        PixelReadConverter->GetRawSize());
764
765       std::string vr = "OB";
766       if( FileInternal->GetBitsAllocated()>8 )
767          vr = "OW";
768       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
769          vr = "OB";
770       BinEntry *pixel = 
771          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
772       pixel->SetValue(GDCM_BINLOADED);
773       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
774       pixel->SetLength(PixelWriteConverter->GetDataSize());
775
776       Archive->Push(photInt);
777       Archive->Push(pixel);
778    }
779 }
780
781 /**
782  * \brief Updates the File to write RGB data (as opposed to RAW data)
783  *       (modifies, when necessary, photochromatic interpretation, 
784  *       samples per pixel, Planar configuration, 
785  *       bits allocated, bits stored, high bit -ACR 24 bits-
786  *       Pixels element VR, pushes out the LUT, )
787  */ 
788 void FileHelper::SetWriteToRGB()
789 {
790    if(FileInternal->GetNumberOfScalarComponents()==3)
791    {
792       PixelReadConverter->BuildRGBImage();
793       
794       ValEntry *spp = CopyValEntry(0x0028,0x0002);
795       spp->SetValue("3 ");
796
797       ValEntry *planConfig = CopyValEntry(0x0028,0x0006);
798       planConfig->SetValue("0 ");
799
800       ValEntry *photInt = CopyValEntry(0x0028,0x0004);
801       photInt->SetValue("RGB ");
802
803       if(PixelReadConverter->GetRGB())
804       {
805          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
806                                           PixelReadConverter->GetRGBSize());
807       }
808       else // Raw data
809       {
810          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
811                                           PixelReadConverter->GetRawSize());
812       }
813
814       std::string vr = "OB";
815       if( FileInternal->GetBitsAllocated()>8 )
816          vr = "OW";
817       if( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
818          vr = "OB";
819       BinEntry *pixel = 
820          CopyBinEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
821       pixel->SetValue(GDCM_BINLOADED);
822       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
823       pixel->SetLength(PixelWriteConverter->GetDataSize());
824
825       Archive->Push(spp);
826       Archive->Push(planConfig);
827       Archive->Push(photInt);
828       Archive->Push(pixel);
829
830       // Remove any LUT
831       Archive->Push(0x0028,0x1101);
832       Archive->Push(0x0028,0x1102);
833       Archive->Push(0x0028,0x1103);
834       Archive->Push(0x0028,0x1201);
835       Archive->Push(0x0028,0x1202);
836       Archive->Push(0x0028,0x1203);
837
838       // For old '24 Bits' ACR-NEMA
839       // Thus, we have a RGB image and the bits allocated = 24 and 
840       // samples per pixels = 1 (in the read file)
841       if(FileInternal->GetBitsAllocated()==24) 
842       {
843          ValEntry *bitsAlloc = CopyValEntry(0x0028,0x0100);
844          bitsAlloc->SetValue("8 ");
845
846          ValEntry *bitsStored = CopyValEntry(0x0028,0x0101);
847          bitsStored->SetValue("8 ");
848
849          ValEntry *highBit = CopyValEntry(0x0028,0x0102);
850          highBit->SetValue("7 ");
851
852          Archive->Push(bitsAlloc);
853          Archive->Push(bitsStored);
854          Archive->Push(highBit);
855       }
856    }
857    else
858    {
859       SetWriteToRaw();
860    }
861 }
862
863 /**
864  * \brief Restore the File write mode  
865  */ 
866 void FileHelper::RestoreWrite()
867 {
868    Archive->Restore(0x0028,0x0002);
869    Archive->Restore(0x0028,0x0004);
870    Archive->Restore(0x0028,0x0006);
871    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
872
873    // For old ACR-NEMA (24 bits problem)
874    Archive->Restore(0x0028,0x0100);
875    Archive->Restore(0x0028,0x0101);
876    Archive->Restore(0x0028,0x0102);
877
878    // For the LUT
879    Archive->Restore(0x0028,0x1101);
880    Archive->Restore(0x0028,0x1102);
881    Archive->Restore(0x0028,0x1103);
882    Archive->Restore(0x0028,0x1201);
883    Archive->Restore(0x0028,0x1202);
884    Archive->Restore(0x0028,0x1203);
885
886    // group 0002 may be pushed out for ACR-NEMA writting purposes 
887    Archive->Restore(0x0002,0x0000);
888    Archive->Restore(0x0002,0x0001);
889    Archive->Restore(0x0002,0x0002);
890    Archive->Restore(0x0002,0x0003);
891    Archive->Restore(0x0002,0x0010);
892    Archive->Restore(0x0002,0x0012);
893    Archive->Restore(0x0002,0x0013);
894    Archive->Restore(0x0002,0x0016);
895    Archive->Restore(0x0002,0x0100);
896    Archive->Restore(0x0002,0x0102);
897 }
898
899 /**
900  * \brief Pushes out the whole group 0002
901  *        FIXME : better, set a flag to tell the writer not to write it ...
902  *        FIXME : method should probably have an other name !
903  *                SetWriteFileTypeToACR is NOT opposed to 
904  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
905  */ 
906 void FileHelper::SetWriteFileTypeToACR()
907 {
908    Archive->Push(0x0002,0x0000);
909    Archive->Push(0x0002,0x0001);
910    Archive->Push(0x0002,0x0002);
911    Archive->Push(0x0002,0x0003);
912    Archive->Push(0x0002,0x0010);
913    Archive->Push(0x0002,0x0012);
914    Archive->Push(0x0002,0x0013);
915    Archive->Push(0x0002,0x0016);
916    Archive->Push(0x0002,0x0100);
917    Archive->Push(0x0002,0x0102);
918 }
919
920 /**
921  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
922  */ 
923 void FileHelper::SetWriteFileTypeToExplicitVR()
924 {
925    std::string ts = Util::DicomString( 
926       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
927
928    ValEntry *tss = CopyValEntry(0x0002,0x0010);
929    tss->SetValue(ts);
930
931    Archive->Push(tss);
932 }
933
934 /**
935  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
936  */ 
937 void FileHelper::SetWriteFileTypeToImplicitVR()
938 {
939    std::string ts = Util::DicomString(
940       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
941
942    ValEntry *tss = CopyValEntry(0x0002,0x0010);
943    tss->SetValue(ts);
944
945    Archive->Push(tss);
946 }
947
948
949 /**
950  * \brief Restore in the File the initial group 0002
951  */ 
952 void FileHelper::RestoreWriteFileType()
953 {
954 }
955
956 /**
957  * \brief Set the Write not to Libido format
958  */ 
959 void FileHelper::SetWriteToLibido()
960 {
961    ValEntry *oldRow = dynamic_cast<ValEntry *>
962                 (FileInternal->GetDocEntry(0x0028, 0x0010));
963    ValEntry *oldCol = dynamic_cast<ValEntry *>
964                 (FileInternal->GetDocEntry(0x0028, 0x0011));
965    
966    if( oldRow && oldCol )
967    {
968       std::string rows, columns; 
969
970       ValEntry *newRow=new ValEntry(oldRow->GetDictEntry());
971       ValEntry *newCol=new ValEntry(oldCol->GetDictEntry());
972
973       newRow->Copy(oldCol);
974       newCol->Copy(oldRow);
975
976       newRow->SetValue(oldCol->GetValue());
977       newCol->SetValue(oldRow->GetValue());
978
979       Archive->Push(newRow);
980       Archive->Push(newCol);
981    }
982
983    ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
984    libidoCode->SetValue("ACRNEMA_LIBIDO_1.1");
985    Archive->Push(libidoCode);
986 }
987
988 /**
989  * \brief Set the Write not to No Libido format
990  */ 
991 void FileHelper::SetWriteToNoLibido()
992 {
993    ValEntry *recCode = dynamic_cast<ValEntry *>
994                 (FileInternal->GetDocEntry(0x0008,0x0010));
995    if( recCode )
996    {
997       if( recCode->GetValue() == "ACRNEMA_LIBIDO_1.1" )
998       {
999          ValEntry *libidoCode = CopyValEntry(0x0008,0x0010);
1000          libidoCode->SetValue("");
1001          Archive->Push(libidoCode);
1002       }
1003    }
1004 }
1005
1006 /**
1007  * \brief Restore the Write format
1008  */ 
1009 void FileHelper::RestoreWriteOfLibido()
1010 {
1011    Archive->Restore(0x0028,0x0010);
1012    Archive->Restore(0x0028,0x0011);
1013    Archive->Restore(0x0008,0x0010);
1014 }
1015
1016 /**
1017  * \brief Duplicates a ValEntry or creates it.
1018  * @param   group   Group number of the Entry 
1019  * @param   elem  Element number of the Entry
1020  * \return  pointer to the new Val Entry (NULL when creation failed).          
1021  */ 
1022 ValEntry *FileHelper::CopyValEntry(uint16_t group, uint16_t elem)
1023 {
1024    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1025    ValEntry *newE;
1026
1027    if( oldE )
1028    {
1029       newE = new ValEntry(oldE->GetDictEntry());
1030       newE->Copy(oldE);
1031    }
1032    else
1033    {
1034       newE = GetFile()->NewValEntry(group, elem);
1035    }
1036
1037    return newE;
1038 }
1039
1040 /**
1041  * \brief   Duplicates a BinEntry or creates it.
1042  * @param   group   Group number of the Entry 
1043  * @param   elem  Element number of the Entry
1044  * @param   vr  Value Representation of the Entry
1045  *          FIXME : what is it used for?
1046  * \return  pointer to the new Bin Entry (NULL when creation failed).
1047  */ 
1048 BinEntry *FileHelper::CopyBinEntry(uint16_t group, uint16_t elem,
1049                                    const std::string &vr)
1050 {
1051    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1052    BinEntry *newE;
1053
1054    if( oldE ) 
1055       if( oldE->GetVR()!=vr )
1056          oldE = NULL;
1057
1058    if( oldE )
1059    {
1060       newE = new BinEntry(oldE->GetDictEntry());
1061       newE->Copy(oldE);
1062    }
1063    else
1064    {
1065       newE = GetFile()->NewBinEntry(group, elem, vr);
1066    }
1067
1068    return newE;
1069 }
1070
1071 /**
1072  * \brief   This method is called automatically, just before writting
1073  *         in order to produce a 'True Dicom V3' image
1074  *         We cannot know *how* the user made the File (reading an old ACR-NEMA
1075  *         file or a not very clean DICOM file ...) 
1076  *          
1077  *          Just before writting :
1078  *             - we check the Entries
1079  *             - we create the mandatory entries if they are missing
1080  *             - we modify the values if necessary
1081  *             - we push the sensitive entries to the Archive
1082  *          The writing process will restore the entries as they where before 
1083  *          entering FileHelper::CheckMandatoryElements, so the user will always
1084  *          see the entries just as he left them.
1085  * 
1086  * \todo : - warn the user if we had to add some entries :
1087  *         even if a mandatory entry is missing, we add it, with a default value
1088  *         (we don't want to give up the writting process if user forgot to
1089  *         specify Lena's Patient ID, for instance ...)
1090  *         - read the whole PS 3.3 Part of DICOM  (890 pages)
1091  *         and write a *full* checker (probably one method per Modality ...)
1092  *         Any contribution is welcome. 
1093  *         - write a user callable full checker, to allow post reading
1094  *         and/or pre writting image consistency check.           
1095  */ 
1096  
1097 void FileHelper::CheckMandatoryElements()
1098 {
1099    // just to remember : 'official' 0002 group
1100
1101    //0002 0000 UL 1 Meta Group Length
1102    //0002 0001 OB 1 File Meta Information Version
1103    //0002 0002 UI 1 Media Stored SOP Class UID
1104    //0002 0003 UI 1 Media Stored SOP Instance UID
1105    //0002 0010 UI 1 Transfer Syntax UID
1106    //0002 0012 UI 1 Implementation Class UID
1107    //0002 0013 SH 1 Implementation Version Name
1108    //0002 0016 AE 1 Source Application Entity Title
1109    //0002 0100 UI 1 Private Information Creator
1110    //0002 0102 OB 1 Private Information
1111   
1112    // Create them if not found
1113    // Always modify the value
1114    // Push the entries to the archive.
1115    ValEntry *e_0002_0000 = CopyValEntry(0x0002,0x0000);
1116       e_0002_0000->SetValue("0"); // for the moment
1117       Archive->Push(e_0002_0000);
1118   
1119    BinEntry *e_0002_0001 = CopyBinEntry(0x0002,0x0001, "OB");
1120       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1121                                false);
1122       e_0002_0001->SetLength(2);
1123       Archive->Push(e_0002_0001);
1124
1125    ValEntry *e_0002_0002 = CopyValEntry(0x0002,0x0002);
1126       // [Secondary Capture Image Storage]
1127       e_0002_0002->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1128       Archive->Push(e_0002_0002);
1129  
1130    // 'Media Stored SOP Instance UID'   
1131    ValEntry *e_0002_0003 = CopyValEntry(0x0002,0x0003);
1132       e_0002_0003->SetValue(Util::CreateUniqueUID());
1133       Archive->Push(e_0002_0003); 
1134
1135    // 'Implementation Class UID'
1136    ValEntry *e_0002_0012 = CopyValEntry(0x0002,0x0012);
1137       e_0002_0012->SetValue(Util::CreateUniqueUID());
1138       Archive->Push(e_0002_0012); 
1139
1140    // 'Implementation Version Name'
1141    ValEntry *e_0002_0013 = CopyValEntry(0x0002,0x0013);
1142       e_0002_0013->SetValue("GDCM 1.0");
1143       Archive->Push(e_0002_0013);
1144
1145    //'Source Application Entity Title' Not Mandatory
1146    //ValEntry *e_0002_0016 = CopyValEntry(0x0002,0x0016);
1147    //   e_0002_0016->SetValue("1.2.840.10008.5.1.4.1.1.7");
1148    //   Archive->Push(e_0002_0016);
1149
1150    // Push out 'LibIDO-special' entries, if any
1151    Archive->Push(0x0028,0x0015);
1152    Archive->Push(0x0028,0x0016);
1153    Archive->Push(0x0028,0x0017);
1154    Archive->Push(0x0028,0x00199);
1155
1156    // --- Check UID-related Entries ---
1157
1158    // If 'SOP Class UID' exists ('true DICOM' image)
1159    // we create the 'Source Image Sequence' SeqEntry
1160    // to hold informations about the Source Image
1161
1162    ValEntry *e_0008_0016 = FileInternal->GetValEntry(0x0008, 0x0016);
1163    if ( e_0008_0016 != 0 )
1164    {
1165       // Create 'Source Image Sequence' SeqEntry
1166       SeqEntry *s = new SeqEntry (
1167             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1168       SQItem *sqi = new SQItem(1);
1169       // (we assume 'SOP Instance UID' exists too) 
1170       // create 'Referenced SOP Class UID'
1171       ValEntry *e_0008_1150 = new ValEntry(
1172             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1173       e_0008_1150->SetValue( e_0008_0016->GetValue());
1174       sqi->AddEntry(e_0008_1150);
1175       
1176       // create 'Referenced SOP Instance UID'
1177       ValEntry *e_0008_0018 = FileInternal->GetValEntry(0x0008, 0x0018);
1178       ValEntry *e_0008_1155 = new ValEntry(
1179             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1180       e_0008_1155->SetValue( e_0008_0018->GetValue());
1181       sqi->AddEntry(e_0008_1155);
1182
1183       s->AddSQItem(sqi,1); 
1184       // temporarily replaces any previous 'Source Image Sequence' 
1185       Archive->Push(s);
1186  
1187       // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1188       ValEntry *e_0008_0008 = CopyValEntry(0x0008,0x0008);
1189       e_0008_0008->SetValue("DERIVED\\PRIMARY");
1190       Archive->Push(e_0008_0008);
1191    } 
1192    else
1193    {
1194       // There was no 'SOP Class UID'.
1195       // the source image was NOT a true Dicom one.
1196       // We consider the image is a 'Secondary Capture' one
1197       // SOP Class UID
1198       e_0008_0016  =  new ValEntry( 
1199             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0016) );
1200       // [Secondary Capture Image Storage]
1201       e_0008_0016 ->SetValue("1.2.840.10008.5.1.4.1.1.7"); 
1202       Archive->Push(e_0008_0016); 
1203    }
1204
1205 // ---- The user will never have to take any action on the following ----.
1206
1207    // new value for 'SOP Instance UID'
1208    ValEntry *e_0008_0018 = new ValEntry(
1209          Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0018) );
1210    e_0008_0018->SetValue( Util::CreateUniqueUID() );
1211    Archive->Push(e_0008_0018);
1212
1213    // Instance Creation Date
1214    ValEntry *e_0008_0012 = CopyValEntry(0x0008,0x0012);
1215    std::string date = Util::GetCurrentDate();
1216    e_0008_0012->SetValue(date.c_str());
1217    Archive->Push(e_0008_0012);
1218  
1219    // Instance Creation Time
1220    ValEntry *e_0008_0013 = CopyValEntry(0x0008,0x0013);
1221    std::string time = Util::GetCurrentTime();
1222    e_0008_0013->SetValue(time.c_str());
1223    Archive->Push(e_0008_0013);
1224
1225 // ----- Add Mandatory Entries if missing ---
1226
1227 // Entries whose type is 1 are mandatory, with a mandatory value
1228 // Entries whose type is 1c are mandatory-inside-a-Sequence
1229 // Entries whose type is 2 are mandatory, with a optional value
1230 // Entries whose type is 2c are mandatory-inside-a-Sequence
1231 // Entries whose type is 3 are optional
1232
1233    // 'Serie Instance UID'
1234    // Keep the value if exists
1235    // The user is allowed to create his own Series, 
1236    // keeping the same 'Serie Instance UID' for various images
1237    // The user shouldn't add any image to a 'Manufacturer Serie'
1238    // but there is no way no to allowed him to do that 
1239    ValEntry *e_0020_000e = FileInternal->GetValEntry(0x0020, 0x000e);
1240    if ( !e_0020_000e )
1241    {
1242       e_0020_000e = new ValEntry(
1243            Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000e) );
1244       e_0020_000e->SetValue(Util::CreateUniqueUID() );
1245       Archive->Push(e_0020_000e);
1246    } 
1247
1248    // 'Study Instance UID'
1249    // Keep the value if exists
1250    // The user is allowed to create his own Study, 
1251    //          keeping the same 'Study Instance UID' for various images
1252    // The user may add images to a 'Manufacturer Study',
1253    //          adding new series to an already existing Study 
1254    ValEntry *e_0020_000d = FileInternal->GetValEntry(0x0020, 0x000d);
1255    if ( !e_0020_000d )
1256    {
1257       e_0020_000d = new ValEntry(
1258             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0020, 0x000d) );
1259       e_0020_000d->SetValue(Util::CreateUniqueUID() );
1260       Archive->Push(e_0020_000d);
1261    }
1262
1263    // Modality : if missing we set it to 'OTher'
1264    ValEntry *e_0008_0060 = FileInternal->GetValEntry(0x0008, 0x0060);
1265    if ( !e_0008_0060 )
1266    {
1267       e_0008_0060 = new ValEntry(
1268             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0060) );
1269       e_0008_0060->SetValue("OT");
1270       Archive->Push(e_0008_0060);
1271    } 
1272
1273    // Manufacturer : if missing we set it to 'GDCM Factory'
1274    ValEntry *e_0008_0070 = FileInternal->GetValEntry(0x0008, 0x0070);
1275    if ( !e_0008_0070 )
1276    {
1277       e_0008_0070 = new ValEntry(
1278             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0070) );
1279       e_0008_0070->SetValue("GDCM Factory");
1280       Archive->Push(e_0008_0070);
1281    } 
1282
1283    // Institution Name : if missing we set it to 'GDCM Hospital'
1284    ValEntry *e_0008_0080 = FileInternal->GetValEntry(0x0008, 0x0080);
1285    if ( !e_0008_0080 )
1286    {
1287       e_0008_0080 = new ValEntry(
1288             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0080) );
1289       e_0008_0080->SetValue("GDCM Hospital");
1290       Archive->Push(e_0008_0080);
1291    } 
1292
1293    // Patient's Name : if missing, we set it to 'GDCM^Patient'
1294    ValEntry *e_0010_0010 = FileInternal->GetValEntry(0x0010, 0x0010);
1295    if ( !e_0010_0010 )
1296    {
1297       e_0010_0010 = new ValEntry(
1298             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0010) );
1299       e_0010_0010->SetValue("GDCM^Patient");
1300       Archive->Push(e_0010_0010);
1301    } 
1302
1303    // Patient's ID : if missing, we set it to 'GDCM_Patient_ID'
1304    ValEntry *e_0010_0020 = FileInternal->GetValEntry(0x0010, 0x0020);
1305    if ( !e_0010_0020 )
1306    {
1307       e_0010_0020 = new ValEntry(
1308             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0020) );
1309       e_0010_0020->SetValue("GDCM_Patient_ID");
1310       Archive->Push(e_0010_0020);
1311    }
1312
1313    // Patient's Birth Date :'type 2' entry -> must exist, value not mandatory
1314    ValEntry *e_0010_0030 = FileInternal->GetValEntry(0x0010, 0x0030);
1315    if ( !e_0010_0030 )
1316    {
1317       e_0010_0030 = new ValEntry(
1318             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0030) );
1319       e_0010_0030->SetValue("");
1320       Archive->Push(e_0010_0030);
1321    }
1322
1323    // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1324    ValEntry *e_0010_0040 = FileInternal->GetValEntry(0x0010, 0x0040);
1325    if ( !e_0010_0040 )
1326    {
1327       e_0010_0040 = new ValEntry(
1328             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0010, 0x0040) );
1329       e_0010_0040->SetValue("");
1330       Archive->Push(e_0010_0040);
1331    }
1332
1333    // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1334    ValEntry *e_0008_0090 = FileInternal->GetValEntry(0x0008, 0x0090);
1335    if ( !e_0008_0090 )
1336    {
1337       e_0008_0090 = new ValEntry(
1338             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x0090) );
1339       e_0008_0090->SetValue("");
1340       Archive->Push(e_0008_0090);
1341    }
1342  
1343    // Remove some inconstencies (probably some more will be added)
1344
1345    // if (0028 0008)Number of Frames exists
1346    //    Push out (0020 0052),Frame of Reference UID
1347    //    (only meaningfull within a Serie)
1348    ValEntry *e_0028_0008 = FileInternal->GetValEntry(0x0028, 0x0008);
1349    if ( !e_0028_0008 )
1350    {
1351       Archive->Push(0x0020, 0X0052);
1352    }
1353
1354  
1355 /**
1356  * \brief Restore in the File the initial group 0002
1357  */
1358 void FileHelper::RestoreWriteMandatory()
1359 {
1360    // group 0002 may be pushed out for ACR-NEMA writting purposes 
1361    Archive->Restore(0x0002,0x0000);
1362    Archive->Restore(0x0002,0x0001);
1363    Archive->Restore(0x0002,0x0002);
1364    Archive->Restore(0x0002,0x0003);
1365    Archive->Restore(0x0002,0x0012);
1366    Archive->Restore(0x0002,0x0013);
1367    Archive->Restore(0x0002,0x0016);
1368    Archive->Restore(0x0002,0x0100);
1369    Archive->Restore(0x0002,0x0102);
1370 }
1371
1372 //-----------------------------------------------------------------------------
1373 // Private
1374 /**
1375  * \brief Factorization for various forms of constructors.
1376  */
1377 void FileHelper::Initialize()
1378 {
1379    WriteMode = WMODE_RAW;
1380    WriteType = ExplicitVR;
1381
1382    PixelReadConverter  = new PixelReadConvert;
1383    PixelWriteConverter = new PixelWriteConvert;
1384    Archive = new DocEntryArchive( FileInternal );
1385
1386    if ( FileInternal->IsReadable() )
1387    {
1388       PixelReadConverter->GrabInformationsFromFile( FileInternal );
1389    }
1390 }
1391
1392 /**
1393  * \brief   
1394  */ 
1395 uint8_t *FileHelper::GetRaw()
1396 {
1397    uint8_t *raw = PixelReadConverter->GetRaw();
1398    if ( ! raw )
1399    {
1400       // The Raw image migth not be loaded yet:
1401       std::ifstream *fp = FileInternal->OpenFile();
1402       PixelReadConverter->ReadAndDecompressPixelData( fp );
1403       if(fp) 
1404          FileInternal->CloseFile();
1405
1406       raw = PixelReadConverter->GetRaw();
1407       if ( ! raw )
1408       {
1409          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1410          return 0;
1411       }
1412    }
1413
1414    return raw;
1415 }
1416
1417 //-----------------------------------------------------------------------------
1418 // Print
1419 void FileHelper::Print(std::ostream &os, std::string const &)
1420 {
1421    FileInternal->SetPrintLevel(PrintLevel);
1422    FileInternal->Print(os);
1423
1424    PixelReadConverter->SetPrintLevel(PrintLevel);
1425    PixelReadConverter->Print(os);
1426 }
1427
1428 //-----------------------------------------------------------------------------
1429 } // end namespace gdcm