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