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