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