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