]> Creatis software - gdcm.git/blob - src/gdcmFileHelper.cxx
Doxygenation
[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/23 15:24:47 $
8   Version:   $Revision: 1.69 $
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 ... (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 }
870
871 /**
872  * \brief Updates the File to write RGB data (as opposed to RAW data)
873  *       (modifies, when necessary, photochromatic interpretation, 
874  *       samples per pixel, Planar configuration, 
875  *       bits allocated, bits stored, high bit -ACR 24 bits-
876  *       Pixels element VR, pushes out the LUT, )
877  */ 
878 void FileHelper::SetWriteToRGB()
879 {
880    if ( FileInternal->GetNumberOfScalarComponents()==3 )
881    {
882       PixelReadConverter->BuildRGBImage();
883       
884       DataEntry *spp = CopyDataEntry(0x0028,0x0002);
885       spp->SetString("3 ");
886
887       DataEntry *planConfig = CopyDataEntry(0x0028,0x0006);
888       planConfig->SetString("0 ");
889
890       DataEntry *photInt = CopyDataEntry(0x0028,0x0004);
891       photInt->SetString("RGB ");
892
893       if ( PixelReadConverter->GetRGB() )
894       {
895          PixelWriteConverter->SetReadData(PixelReadConverter->GetRGB(),
896                                           PixelReadConverter->GetRGBSize());
897       }
898       else // Raw data
899       {
900          PixelWriteConverter->SetReadData(PixelReadConverter->GetRaw(),
901                                           PixelReadConverter->GetRawSize());
902       }
903
904       std::string vr = "OB";
905       if ( FileInternal->GetBitsAllocated()>8 )
906          vr = "OW";
907       if ( FileInternal->GetBitsAllocated()==24 ) // For RGB ACR files 
908          vr = "OB";
909       DataEntry *pixel = 
910          CopyDataEntry(GetFile()->GetGrPixel(),GetFile()->GetNumPixel(),vr);
911       pixel->SetFlag(DataEntry::FLAG_PIXELDATA);
912       pixel->SetBinArea(PixelWriteConverter->GetData(),false);
913       pixel->SetLength(PixelWriteConverter->GetDataSize());
914
915       Archive->Push(spp);
916       Archive->Push(planConfig);
917       Archive->Push(photInt);
918       Archive->Push(pixel);
919
920       // Remove any LUT
921       Archive->Push(0x0028,0x1101);
922       Archive->Push(0x0028,0x1102);
923       Archive->Push(0x0028,0x1103);
924       Archive->Push(0x0028,0x1201);
925       Archive->Push(0x0028,0x1202);
926       Archive->Push(0x0028,0x1203);
927
928       // push out Palette Color Lookup Table UID, if any
929       Archive->Push(0x0028,0x1199);
930
931       // For old '24 Bits' ACR-NEMA
932       // Thus, we have a RGB image and the bits allocated = 24 and 
933       // samples per pixels = 1 (in the read file)
934       if ( FileInternal->GetBitsAllocated()==24 ) 
935       {
936          DataEntry *bitsAlloc = CopyDataEntry(0x0028,0x0100);
937          bitsAlloc->SetString("8 ");
938
939          DataEntry *bitsStored = CopyDataEntry(0x0028,0x0101);
940          bitsStored->SetString("8 ");
941
942          DataEntry *highBit = CopyDataEntry(0x0028,0x0102);
943          highBit->SetString("7 ");
944
945          Archive->Push(bitsAlloc);
946          Archive->Push(bitsStored);
947          Archive->Push(highBit);
948       }
949    }
950    else
951    {
952       SetWriteToRaw();
953    }
954 }
955
956 /**
957  * \brief Restore the File write mode  
958  */ 
959 void FileHelper::RestoreWrite()
960 {
961    Archive->Restore(0x0028,0x0002);
962    Archive->Restore(0x0028,0x0004);
963    Archive->Restore(0x0028,0x0006);
964    Archive->Restore(GetFile()->GetGrPixel(),GetFile()->GetNumPixel());
965
966    // For old ACR-NEMA (24 bits problem)
967    Archive->Restore(0x0028,0x0100);
968    Archive->Restore(0x0028,0x0101);
969    Archive->Restore(0x0028,0x0102);
970
971    // For the LUT
972    Archive->Restore(0x0028,0x1101);
973    Archive->Restore(0x0028,0x1102);
974    Archive->Restore(0x0028,0x1103);
975    Archive->Restore(0x0028,0x1201);
976    Archive->Restore(0x0028,0x1202);
977    Archive->Restore(0x0028,0x1203);
978
979    // For the Palette Color Lookup Table UID
980    Archive->Restore(0x0028,0x1203); 
981
982
983    // group 0002 may be pushed out for ACR-NEMA writting purposes 
984    Archive->Restore(0x0002,0x0000);
985    Archive->Restore(0x0002,0x0001);
986    Archive->Restore(0x0002,0x0002);
987    Archive->Restore(0x0002,0x0003);
988    Archive->Restore(0x0002,0x0010);
989    Archive->Restore(0x0002,0x0012);
990    Archive->Restore(0x0002,0x0013);
991    Archive->Restore(0x0002,0x0016);
992    Archive->Restore(0x0002,0x0100);
993    Archive->Restore(0x0002,0x0102);
994 }
995
996 /**
997  * \brief Pushes out the whole group 0002
998  *        FIXME : better, set a flag to tell the writer not to write it ...
999  *        FIXME : method should probably have an other name !
1000  *                SetWriteFileTypeToACR is NOT opposed to 
1001  *                SetWriteFileTypeToExplicitVR and SetWriteFileTypeToImplicitVR
1002  */ 
1003 void FileHelper::SetWriteFileTypeToACR()
1004 {
1005    Archive->Push(0x0002,0x0000);
1006    Archive->Push(0x0002,0x0001);
1007    Archive->Push(0x0002,0x0002);
1008    Archive->Push(0x0002,0x0003);
1009    Archive->Push(0x0002,0x0010);
1010    Archive->Push(0x0002,0x0012);
1011    Archive->Push(0x0002,0x0013);
1012    Archive->Push(0x0002,0x0016);
1013    Archive->Push(0x0002,0x0100);
1014    Archive->Push(0x0002,0x0102);
1015 }
1016
1017 /**
1018  * \brief Sets in the File the TransferSyntax to 'Explicit VR Little Endian"   
1019  */ 
1020 void FileHelper::SetWriteFileTypeToJPEG()
1021 {
1022    std::string ts = Util::DicomString( 
1023       Global::GetTS()->GetSpecialTransferSyntax(TS::JPEGBaselineProcess1) );
1024
1025    DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1026    tss->SetString(ts);
1027
1028    Archive->Push(tss);
1029 }
1030
1031 void FileHelper::SetWriteFileTypeToExplicitVR()
1032 {
1033    std::string ts = Util::DicomString( 
1034       Global::GetTS()->GetSpecialTransferSyntax(TS::ExplicitVRLittleEndian) );
1035
1036    DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1037    tss->SetString(ts);
1038
1039    Archive->Push(tss);
1040 }
1041
1042 /**
1043  * \brief Sets in the File the TransferSyntax to 'Implicit VR Little Endian"   
1044  */ 
1045 void FileHelper::SetWriteFileTypeToImplicitVR()
1046 {
1047    std::string ts = Util::DicomString(
1048       Global::GetTS()->GetSpecialTransferSyntax(TS::ImplicitVRLittleEndian) );
1049
1050    DataEntry *tss = CopyDataEntry(0x0002,0x0010);
1051    tss->SetString(ts);
1052
1053    Archive->Push(tss);
1054 }
1055
1056
1057 /**
1058  * \brief Restore in the File the initial group 0002
1059  */ 
1060 void FileHelper::RestoreWriteFileType()
1061 {
1062 }
1063
1064 /**
1065  * \brief Set the Write not to Libido format
1066  */ 
1067 void FileHelper::SetWriteToLibido()
1068 {
1069    DataEntry *oldRow = FileInternal->GetDataEntry(0x0028, 0x0010);
1070    DataEntry *oldCol = FileInternal->GetDataEntry(0x0028, 0x0011);
1071    
1072    if ( oldRow && oldCol )
1073    {
1074       std::string rows, columns; 
1075
1076       DataEntry *newRow=new DataEntry(oldRow->GetDictEntry());
1077       DataEntry *newCol=new DataEntry(oldCol->GetDictEntry());
1078
1079       newRow->Copy(oldCol);
1080       newCol->Copy(oldRow);
1081
1082       newRow->SetString(oldCol->GetString());
1083       newCol->SetString(oldRow->GetString());
1084
1085       Archive->Push(newRow);
1086       Archive->Push(newCol);
1087    }
1088
1089    DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1090    libidoCode->SetString("ACRNEMA_LIBIDO_1.1");
1091    Archive->Push(libidoCode);
1092 }
1093
1094 /**
1095  * \brief Set the Write not to No Libido format
1096  */ 
1097 void FileHelper::SetWriteToNoLibido()
1098 {
1099    DataEntry *recCode = FileInternal->GetDataEntry(0x0008,0x0010);
1100    if ( recCode )
1101    {
1102       if ( recCode->GetString() == "ACRNEMA_LIBIDO_1.1" )
1103       {
1104          DataEntry *libidoCode = CopyDataEntry(0x0008,0x0010);
1105          libidoCode->SetString("");
1106          Archive->Push(libidoCode);
1107       }
1108    }
1109 }
1110
1111 /**
1112  * \brief Restore the Write format
1113  */ 
1114 void FileHelper::RestoreWriteOfLibido()
1115 {
1116    Archive->Restore(0x0028,0x0010);
1117    Archive->Restore(0x0028,0x0011);
1118    Archive->Restore(0x0008,0x0010);
1119
1120    // Restore 'LibIDO-special' entries, if any
1121    Archive->Restore(0x0028,0x0015);
1122    Archive->Restore(0x0028,0x0016);
1123    Archive->Restore(0x0028,0x0017);
1124    Archive->Restore(0x0028,0x00199);
1125 }
1126
1127 /**
1128  * \brief   Duplicates a DataEntry or creates it.
1129  * @param   group   Group number of the Entry 
1130  * @param   elem  Element number of the Entry
1131  * @param   vr  Value Representation of the Entry
1132  *          FIXME : what is it used for?
1133  * \return  pointer to the new Bin Entry (NULL when creation failed).
1134  */ 
1135 DataEntry *FileHelper::CopyDataEntry(uint16_t group, uint16_t elem,
1136                                    const TagName &vr)
1137 {
1138    DocEntry *oldE = FileInternal->GetDocEntry(group, elem);
1139    DataEntry *newE;
1140
1141    if ( oldE && vr != GDCM_VRUNKNOWN ) 
1142       if ( oldE->GetVR() != vr )
1143          oldE = NULL;
1144
1145    if ( oldE )
1146    {
1147       newE = new DataEntry(oldE->GetDictEntry());
1148       newE->Copy(oldE);
1149    }
1150    else
1151    {
1152       newE = GetFile()->NewDataEntry(group, elem, vr);
1153    }
1154
1155    return newE;
1156 }
1157
1158 /**
1159  * \brief   This method is called automatically, just before writting
1160  *         in order to produce a 'True Dicom V3' image
1161  *         We cannot know *how* the user made the File (reading an old ACR-NEMA
1162  *         file or a not very clean DICOM file ...) 
1163  *          
1164  *          Just before writting :
1165  *             - we check the Entries
1166  *             - we create the mandatory entries if they are missing
1167  *             - we modify the values if necessary
1168  *             - we push the sensitive entries to the Archive
1169  *          The writing process will restore the entries as they where before 
1170  *          entering FileHelper::CheckMandatoryElements, so the user will always
1171  *          see the entries just as he left them.
1172  * 
1173  * \todo : - warn the user if we had to add some entries :
1174  *         even if a mandatory entry is missing, we add it, with a default value
1175  *         (we don't want to give up the writting process if user forgot to
1176  *         specify Lena's Patient ID, for instance ...)
1177  *         - read the whole PS 3.3 Part of DICOM  (890 pages)
1178  *         and write a *full* checker (probably one method per Modality ...)
1179  *         Any contribution is welcome. 
1180  *         - write a user callable full checker, to allow post reading
1181  *         and/or pre writting image consistency check.           
1182  */ 
1183  
1184 void FileHelper::CheckMandatoryElements()
1185 {
1186    std::string sop =  Util::CreateUniqueUID();
1187    
1188    // just to remember : 'official' 0002 group
1189    if ( WriteType != ACR && WriteType != ACR_LIBIDO )
1190    {
1191      // Group 000002 (Meta Elements) already pushed out
1192   
1193    //0002 0000 UL 1 Meta Group Length
1194    //0002 0001 OB 1 File Meta Information Version
1195    //0002 0002 UI 1 Media Stored SOP Class UID
1196    //0002 0003 UI 1 Media Stored SOP Instance UID
1197    //0002 0010 UI 1 Transfer Syntax UID
1198    //0002 0012 UI 1 Implementation Class UID
1199    //0002 0013 SH 1 Implementation Version Name
1200    //0002 0016 AE 1 Source Application Entity Title
1201    //0002 0100 UI 1 Private Information Creator
1202    //0002 0102 OB 1 Private Information
1203   
1204    // Create them if not found
1205    // Always modify the value
1206    // Push the entries to the archive.
1207       CopyMandatoryEntry(0x0002,0x0000,"0");
1208   
1209       DataEntry *e_0002_0001 = CopyDataEntry(0x0002,0x0001, "OB");
1210       e_0002_0001->SetBinArea((uint8_t*)Util::GetFileMetaInformationVersion(),
1211                                false);
1212       e_0002_0001->SetLength(2);
1213       Archive->Push(e_0002_0001);
1214
1215    // Potentialy post-processed image --> [Secondary Capture Image Storage]
1216    // 'Media Storage SOP Class UID' 
1217       CopyMandatoryEntry(0x0002,0x0002,"1.2.840.10008.5.1.4.1.1.7");    
1218  
1219    // 'Media Storage SOP Instance UID'   
1220       CopyMandatoryEntry(0x0002,0x0003,sop);
1221       
1222    // 'Implementation Class UID'
1223       CopyMandatoryEntry(0x0002,0x0012,Util::CreateUniqueUID());
1224
1225    // 'Implementation Version Name'
1226       std::string version = "GDCM ";
1227       version += Util::GetVersion();
1228       CopyMandatoryEntry(0x0002,0x0013,version);
1229    }
1230
1231    // Push out 'LibIDO-special' entries, if any
1232    Archive->Push(0x0028,0x0015);
1233    Archive->Push(0x0028,0x0016);
1234    Archive->Push(0x0028,0x0017);
1235    Archive->Push(0x0028,0x00199);
1236
1237    // Deal with the pb of (Bits Stored = 12)
1238    // - we're gonna write the image as Bits Stored = 16
1239    if ( FileInternal->GetEntryString(0x0028,0x0100) ==  "12")
1240    {
1241       CopyMandatoryEntry(0x0028,0x0100,"16");
1242    }
1243
1244    // Check if user wasn't drunk ;-)
1245
1246    std::ostringstream s;
1247    // check 'Bits Allocated' vs decent values
1248    int nbBitsAllocated = FileInternal->GetBitsAllocated();
1249    if ( nbBitsAllocated == 0 || nbBitsAllocated > 32)
1250    {
1251       CopyMandatoryEntry(0x0028,0x0100,"16");
1252       gdcmWarningMacro("(0028,0100) changed from "
1253          << nbBitsAllocated << " to 16 for consistency purpose");
1254       nbBitsAllocated = 16; 
1255    }
1256    // check 'Bits Stored' vs 'Bits Allocated'   
1257    int nbBitsStored = FileInternal->GetBitsStored();
1258    if ( nbBitsStored == 0 || nbBitsStored > nbBitsAllocated )
1259    {
1260       s.str("");
1261       s << nbBitsAllocated;
1262       CopyMandatoryEntry(0x0028,0x0101,s.str());
1263       gdcmWarningMacro("(0028,0101) changed from "
1264                        << nbBitsStored << " to " << nbBitsAllocated
1265                        << " for consistency purpose" );
1266       nbBitsStored = nbBitsAllocated; 
1267     }
1268    // check 'Hight Bit Position' vs 'Bits Allocated' and 'Bits Stored'
1269    int highBitPosition = FileInternal->GetHighBitPosition();
1270    if ( highBitPosition == 0 || 
1271         highBitPosition > nbBitsAllocated-1 ||
1272         highBitPosition < nbBitsStored-1  )
1273    {
1274       s.str("");
1275       s << nbBitsStored - 1; 
1276       CopyMandatoryEntry(0x0028,0x0102,s.str());
1277       gdcmWarningMacro("(0028,0102) changed from "
1278                        << highBitPosition << " to " << nbBitsAllocated-1
1279                        << " for consistency purpose");
1280    }
1281   // --- Check UID-related Entries ---
1282
1283    // If 'SOP Class UID' exists ('true DICOM' image)
1284    // we create the 'Source Image Sequence' SeqEntry
1285    // to hold informations about the Source Image
1286
1287    DataEntry *e_0008_0016 = FileInternal->GetDataEntry(0x0008, 0x0016);
1288    if ( e_0008_0016 )
1289    {
1290       // Create 'Source Image Sequence' SeqEntry
1291       SeqEntry *sis = new SeqEntry (
1292             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x2112) );
1293       SQItem *sqi = new SQItem(1);
1294       // (we assume 'SOP Instance UID' exists too) 
1295       // create 'Referenced SOP Class UID'
1296       DataEntry *e_0008_1150 = new DataEntry(
1297             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1150) );
1298       e_0008_1150->SetString( e_0008_0016->GetString());
1299       sqi->AddEntry(e_0008_1150);
1300       
1301       // create 'Referenced SOP Instance UID'
1302       DataEntry *e_0008_0018 = FileInternal->GetDataEntry(0x0008, 0x0018);
1303       DataEntry *e_0008_1155 = new DataEntry(
1304             Global::GetDicts()->GetDefaultPubDict()->GetEntry(0x0008, 0x1155) );
1305       e_0008_1155->SetString( e_0008_0018->GetString());
1306       sqi->AddEntry(e_0008_1155);
1307
1308       sis->AddSQItem(sqi,1); 
1309       // temporarily replaces any previous 'Source Image Sequence' 
1310       Archive->Push(sis);
1311  
1312       // 'Image Type' (The written image is no longer an 'ORIGINAL' one)
1313       CopyMandatoryEntry(0x0008,0x0008,"DERIVED\\PRIMARY");
1314    }
1315
1316    // At the end, not to overwrite the original ones,
1317    // needed by 'Referenced SOP Instance UID', 'Referenced SOP Class UID'   
1318    // 'SOP Instance UID'  
1319    CopyMandatoryEntry(0x0008,0x0018,sop);
1320    
1321    // whether a 'SOP Class UID' already exists or not in the original image
1322    // the gdcm written image *is* a [Secondary Capture Image Storage] !
1323    // 'SOP Class UID' : [Secondary Capture Image Storage]
1324    CopyMandatoryEntry(0x0008,0x0016,"1.2.840.10008.5.1.4.1.1.7"); 
1325              
1326 // ---- The user will never have to take any action on the following ----.
1327    // new value for 'SOP Instance UID'
1328    //SetMandatoryEntry(0x0008,0x0018,Util::CreateUniqueUID());
1329
1330    // Instance Creation Date
1331    CopyMandatoryEntry(0x0008,0x0012,Util::GetCurrentDate().c_str());
1332  
1333    // Instance Creation Time
1334    CopyMandatoryEntry(0x0008,0x0013,Util::GetCurrentTime().c_str());
1335
1336 // ----- Add Mandatory Entries if missing ---
1337     // Entries whose type is 1 are mandatory, with a mandatory value
1338     // Entries whose type is 1c are mandatory-inside-a-Sequence,
1339     //                          with a mandatory value
1340     // Entries whose type is 2 are mandatory, with an optional value
1341     // Entries whose type is 2c are mandatory-inside-a-Sequence,
1342     //                          with an optional value
1343     // Entries whose type is 3 are optional
1344
1345    // 'Study Instance UID'
1346    // Keep the value if exists
1347    // The user is allowed to create his own Study, 
1348    //          keeping the same 'Study Instance UID' for various images
1349    // The user may add images to a 'Manufacturer Study',
1350    //          adding new series to an already existing Study 
1351    CheckMandatoryEntry(0x0020,0x000d,Util::CreateUniqueUID());
1352
1353    // 'Serie Instance UID'
1354    // Keep the value if exists
1355    // The user is allowed to create his own Series, 
1356    // keeping the same 'Serie Instance UID' for various images
1357    // The user shouldn't add any image to a 'Manufacturer Serie'
1358    // but there is no way no to allowed him to do that 
1359    CheckMandatoryEntry(0x0020,0x000e,Util::CreateUniqueUID());
1360    
1361    // Modality : if missing we set it to 'OTher'
1362    CheckMandatoryEntry(0x0008,0x0060,"OT");
1363
1364    // Manufacturer : if missing we set it to 'GDCM Factory'
1365    CheckMandatoryEntry(0x0008,0x0070,"GDCM Factory");
1366
1367    // Institution Name : if missing we set it to 'GDCM Hospital'
1368    CheckMandatoryEntry(0x0008,0x0080,"GDCM Hospital");
1369
1370    // Patient's Name : if missing, we set it to 'GDCM^Patient'
1371    CheckMandatoryEntry(0x0010,0x0010,"GDCM^Patient");
1372
1373    // Patient's Birth Date : 'type 2' entry -> must exist, value not mandatory
1374    CheckMandatoryEntry(0x0010,0x0030,"");
1375
1376    // Patient's Sex :'type 2' entry -> must exist, value not mandatory
1377    CheckMandatoryEntry(0x0010,0x0040,"");
1378
1379    // Referring Physician's Name :'type 2' entry -> must exist, value not mandatory
1380    CheckMandatoryEntry(0x0008,0x0090,"");
1381
1382     // Pixel Spacing : defaulted to 1.0\1.0
1383    CheckMandatoryEntry(0x0028,0x0030,"1.0\\1.0");
1384    
1385    // Remove some inconstencies (probably some more will be added)
1386
1387    // if (0028 0008)Number of Frames exists
1388    //    Push out (0020 0052),Frame of Reference UID
1389    //    (only meaningfull within a Serie)
1390    DataEntry *e_0028_0008 = FileInternal->GetDataEntry(0x0028, 0x0008);
1391    if ( !e_0028_0008 )
1392    {
1393       Archive->Push(0x0020, 0X0052);
1394    }
1395
1396
1397 void FileHelper::CheckMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1398 {
1399    DataEntry *entry = FileInternal->GetDataEntry(group,elem);
1400    if ( !entry )
1401    {
1402       entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1403       entry->SetString(value);
1404       Archive->Push(entry);
1405    }
1406 }
1407
1408 void FileHelper::SetMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1409 {
1410    DataEntry *entry = new DataEntry(Global::GetDicts()->GetDefaultPubDict()->GetEntry(group,elem));
1411    entry->SetString(value);
1412    Archive->Push(entry);
1413 }
1414
1415 void FileHelper::CopyMandatoryEntry(uint16_t group,uint16_t elem,std::string value)
1416 {
1417    DataEntry *entry = CopyDataEntry(group,elem);
1418    entry->SetString(value);
1419    Archive->Push(entry);
1420 }
1421
1422 /**
1423  * \brief Restore in the File the initial group 0002
1424  */
1425 void FileHelper::RestoreWriteMandatory()
1426 {
1427    // group 0002 may be pushed out for ACR-NEMA writting purposes 
1428    Archive->Restore(0x0002,0x0000);
1429    Archive->Restore(0x0002,0x0001);
1430    Archive->Restore(0x0002,0x0002);
1431    Archive->Restore(0x0002,0x0003);
1432    Archive->Restore(0x0002,0x0010);
1433    Archive->Restore(0x0002,0x0012);
1434    Archive->Restore(0x0002,0x0013);
1435    Archive->Restore(0x0002,0x0016);
1436    Archive->Restore(0x0002,0x0100);
1437    Archive->Restore(0x0002,0x0102);
1438
1439    Archive->Restore(0x0008,0x0012);
1440    Archive->Restore(0x0008,0x0013);
1441    Archive->Restore(0x0008,0x0016);
1442    Archive->Restore(0x0008,0x0018);
1443    Archive->Restore(0x0008,0x0060);
1444    Archive->Restore(0x0008,0x0070);
1445    Archive->Restore(0x0008,0x0080);
1446    Archive->Restore(0x0008,0x0090);
1447    Archive->Restore(0x0008,0x2112);
1448
1449    Archive->Restore(0x0010,0x0010);
1450    Archive->Restore(0x0010,0x0030);
1451    Archive->Restore(0x0010,0x0040);
1452
1453    Archive->Restore(0x0020,0x000d);
1454    Archive->Restore(0x0020,0x000e);
1455
1456 }
1457
1458 //-----------------------------------------------------------------------------
1459 // Private
1460 /**
1461  * \brief Factorization for various forms of constructors.
1462  */
1463 void FileHelper::Initialize()
1464 {
1465    UserFunction = 0;
1466
1467    WriteMode = WMODE_RAW;
1468    WriteType = ExplicitVR;
1469
1470    PixelReadConverter  = new PixelReadConvert;
1471    PixelWriteConverter = new PixelWriteConvert;
1472    Archive = new DocEntryArchive( FileInternal );
1473 }
1474
1475 /**
1476  * \brief Reads/[decompresses] the pixels, 
1477  *        *without* making RGB from Palette Colors 
1478  * @return the pixels area, whatever its type 
1479  *         (uint8_t is just for prototyping : feel free to Cast it) 
1480  */ 
1481 uint8_t *FileHelper::GetRaw()
1482 {
1483    PixelReadConverter->SetUserFunction( UserFunction );
1484
1485    uint8_t *raw = PixelReadConverter->GetRaw();
1486    if ( ! raw )
1487    {
1488       // The Raw image migth not be loaded yet:
1489       std::ifstream *fp = FileInternal->OpenFile();
1490       PixelReadConverter->ReadAndDecompressPixelData( fp );
1491       if ( fp ) 
1492          FileInternal->CloseFile();
1493
1494       raw = PixelReadConverter->GetRaw();
1495       if ( ! raw )
1496       {
1497          gdcmWarningMacro( "Read/decompress of pixel data apparently went wrong.");
1498          return 0;
1499       }
1500    }
1501    return raw;
1502 }
1503
1504 //-----------------------------------------------------------------------------
1505 /**
1506  * \brief   Prints the common part of DataEntry, SeqEntry
1507  * @param   os ostream we want to print in
1508  * @param indent (unused)
1509  */
1510 void FileHelper::Print(std::ostream &os, std::string const &)
1511 {
1512    FileInternal->SetPrintLevel(PrintLevel);
1513    FileInternal->Print(os);
1514
1515    if ( FileInternal->IsReadable() )
1516    {
1517       PixelReadConverter->SetPrintLevel(PrintLevel);
1518       PixelReadConverter->Print(os);
1519    }
1520 }
1521
1522 //-----------------------------------------------------------------------------
1523 } // end namespace gdcm