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