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