]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
Aware user (who *does* know all the files whose names
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkGdcmReader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/04/28 09:29:05 $
7   Version:   $Revision: 1.69 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18                                                                                 
19 //-----------------------------------------------------------------------------
20 // //////////////////////////////////////////////////////////////
21 // WARNING TODO CLEANME 
22 // Actual limitations of this code:
23 //
24 // /////// Redundant and unnecessary header parsing
25 // In it's current state this code actually parses three times the Dicom
26 // header of a file before the corresponding image gets loaded in the
27 // ad-hoc vtkData !
28 // Here is the process:
29 //  1/ First loading happens in ExecuteInformation which, in order to
30 //     positionate the vtk extents, calls CheckFileCoherence. The purpose
31 //     of CheckFileCoherence is to make sure all the images in the future
32 //     stack are "homogenous" (same size, same representation...).
33 //     This can only be achieved by parsing all the Dicom headers...
34 //     --> to avoid loosing too much time :
35 //     If user is 150% sure *all* the files are coherent, that is to say :
36 //     they may be open, they are gdcm-readable, they have the same sizes,
37 //     they have the same 'pixel' type, they are single frame, 
38 //     they have the same color convention ...
39 //     he may use SetCheckFileCoherenceLight() to request a 'light' coherence
40 //     checking
41 //  2/ ExecuteData is then responsible for the next two loadings - 2 ?!?-:
42 //  2a/ ExecuteData calls AllocateOutputData that in turn seems to 
43 //      (indirectely call) ExecuteInformation which ends up in a second
44 //      header parsing
45 //      This is fixed by adding a test at the beginning of ExecuteInformation
46 //      on the modification of the object instance. If a modification have been
47 //      made (method Modified() ), the MTime value is increased. The fileTime
48 //      is compared to this new value to find a modification in the class
49 //      parameters
50 //  2b/ the core of ExecuteData then needs gdcmFile (which in turns
51 //      initialises gdcmFile in the constructor) in order to access
52 //      the data-image.
53 //
54 // Possible solution:
55 // maintain a list of gdcmFiles (created by say ExecuteInformation) created
56 // once and for all accross the life of vtkGdcmFile (it would only load
57 // new gdcmFile if the user changes the list). ExecuteData would then use 
58 // those gdcmFile and hence avoid calling the construtor:
59 //  - advantage: the header of the files would only be parser once.
60 //  - drawback: once execute information is called (i.e. on creation of
61 //              a vtkGdcmFile) the gdcmFile structure is loaded in memory.
62 //              The average size of a gdcm::File being of 100Ko, 
63 //              - 100 Ko ? Better say 1 Mo; we are in 2005 ! - 
64 //              if oneloads 10 stacks of images with say 200 images each,
65 //              you end-up with a loss of 200Mo...
66 //
67 // /////// Never unallocated memory:
68 // ExecuteData allocates space for the pixel data [which will get pointed
69 // by the vtkPointData() through the call
70 // data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);]
71 // This data is never "freed" neither in the destructor nor when the
72 // filename list is extended, ExecuteData is called a second (or third)
73 // time...
74 // //////////////////////////////////////////////////////////////
75
76 #include "gdcmFileHelper.h"
77 #include "gdcmFile.h"
78 #include "vtkGdcmReader.h"
79
80 //#include <stdio.h>
81 #include <vtkObjectFactory.h>
82 #include <vtkImageData.h>
83 #include <vtkPointData.h>
84 #include <vtkLookupTable.h>
85
86 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.69 $");
87 vtkStandardNewMacro(vtkGdcmReader);
88
89 //-----------------------------------------------------------------------------
90 // Constructor / Destructor
91 vtkGdcmReader::vtkGdcmReader()
92 {
93    this->LookupTable = NULL;
94    this->AllowLookupTable = 0;
95    this->LightChecking = false;
96 }
97
98 vtkGdcmReader::~vtkGdcmReader()
99 {
100    this->RemoveAllFileName();
101    this->InternalFileNameList.clear();
102    if(this->LookupTable) 
103       this->LookupTable->Delete();
104 }
105
106 //-----------------------------------------------------------------------------
107 // Print
108 void vtkGdcmReader::PrintSelf(ostream& os, vtkIndent indent)
109 {
110    this->Superclass::PrintSelf(os,indent);
111    os << indent << "Filenames  : " << endl;
112    vtkIndent nextIndent = indent.GetNextIndent();
113    for (std::list<std::string>::iterator it = FileNameList.begin();
114         it != FileNameList.end();
115         ++it)
116    {
117       os << nextIndent << it->c_str() << endl ;
118    }
119 }
120
121 //-----------------------------------------------------------------------------
122 // Public
123 /*
124  * Remove all files from the list of images to read.
125  */
126 void vtkGdcmReader::RemoveAllFileName(void)
127 {
128    this->FileNameList.clear();
129    this->Modified();
130 }
131
132 /*
133  * Adds a file name to the list of images to read.
134  */
135 void vtkGdcmReader::AddFileName(const char* name)
136 {
137    // We need to bypass the const pointer [since list<>.push_bash() only
138    // takes a char* (but not a const char*)] by making a local copy:
139    char *LocalName = new char[strlen(name) + 1];
140    strcpy(LocalName, name);
141    this->FileNameList.push_back(LocalName);
142    delete[] LocalName;
143    this->Modified();
144 }
145
146 /*
147  * Sets up a filename to be read.
148  */
149 void vtkGdcmReader::SetFileName(const char *name) 
150 {
151    vtkImageReader2::SetFileName(name);
152    // Since we maintain a list of filenames, when building a volume,
153    // (see vtkGdcmReader::AddFileName), we additionaly need to purge
154    // this list when we manually positionate the filename.
155    vtkDebugMacro(<< "Clearing all files given with AddFileName");
156    this->FileNameList.clear();
157    this->Modified();
158 }
159
160 /*
161  * Ask for a 'light' checking - actually : just initializing-
162  *if you are 150% sure *all* the files are coherent
163  */
164 void vtkGdcmReader::SetCheckFileCoherenceLight()
165 {
166    LightChecking = true;
167 }
168
169 //-----------------------------------------------------------------------------
170 // Protected
171 /*
172  * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
173  */
174 void vtkGdcmReader::ExecuteInformation()
175 {
176    if(this->MTime>this->fileTime)
177    {
178       if ( this->LightChecking )
179          this->TotalNumberOfPlanes = this->CheckFileCoherenceLight();
180       else
181           this->TotalNumberOfPlanes = this->CheckFileCoherence();
182
183       if ( this->TotalNumberOfPlanes == 0)
184       {
185          vtkErrorMacro(<< "File set is not coherent. Exiting...");
186          return;
187       }
188       
189       // if the user has not set the extent, but has set the VOI
190       // set the z axis extent to the VOI z axis
191       if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
192       (this->DataVOI[4] || this->DataVOI[5]))
193       {
194          this->DataExtent[4] = this->DataVOI[4];
195          this->DataExtent[5] = this->DataVOI[5];
196       }
197
198       // When the user has set the VOI, check it's coherence with the file content.
199       if (this->DataVOI[0] || this->DataVOI[1] || 
200       this->DataVOI[2] || this->DataVOI[3] ||
201       this->DataVOI[4] || this->DataVOI[5])
202       { 
203          if ((this->DataVOI[0] < 0) ||
204              (this->DataVOI[1] >= this->NumColumns) ||
205              (this->DataVOI[2] < 0) ||
206              (this->DataVOI[3] >= this->NumLines) ||
207              (this->DataVOI[4] < 0) ||
208              (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
209          {
210             vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
211             this->DataVOI[0] = 0;
212             this->DataVOI[1] = this->NumColumns - 1;
213             this->DataVOI[2] = 0;
214             this->DataVOI[3] = this->NumLines - 1;
215             this->DataVOI[4] = 0;
216             this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
217          }
218       }
219
220       // Positionate the Extent.
221       this->DataExtent[0] = 0;
222       this->DataExtent[1] = this->NumColumns - 1;
223       this->DataExtent[2] = 0;
224       this->DataExtent[3] = this->NumLines - 1;
225       this->DataExtent[4] = 0;
226       this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
227   
228       // We don't need to positionate the Endian related stuff (by using
229       // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
230       // since the reading of the file is done by gdcm.
231       // But we do need to set up the data type for downstream filters:
232       if      ( ImageType == "8U" )
233       {
234          vtkDebugMacro(<< "8 bits unsigned image");
235          this->SetDataScalarTypeToUnsignedChar(); 
236       }
237       else if ( ImageType == "8S" )
238       {
239          vtkErrorMacro(<< "Cannot handle 8 bit signed files");
240          return;
241       }
242       else if ( ImageType == "16U" )
243       {
244          vtkDebugMacro(<< "16 bits unsigned image");
245          this->SetDataScalarTypeToUnsignedShort();
246       }
247       else if ( ImageType == "16S" )
248       {
249          vtkDebugMacro(<< "16 bits signed image");
250          this->SetDataScalarTypeToShort();
251       }
252       else if ( ImageType == "32U" )
253       {
254          vtkDebugMacro(<< "32 bits unsigned image");
255          vtkDebugMacro(<< "WARNING: forced to signed int !");
256          this->SetDataScalarTypeToInt();
257       }
258       else if ( ImageType == "32S" )
259       {
260          vtkDebugMacro(<< "32 bits signed image");
261          this->SetDataScalarTypeToInt();
262       }
263       else if ( ImageType == "FD" )
264       {
265          vtkDebugMacro(<< "64 bits Double image");
266          this->SetDataScalarTypeToDouble();
267       }
268       //Set number of scalar components:
269       this->SetNumberOfScalarComponents(this->NumComponents);
270
271       this->fileTime=this->MTime;
272    }
273
274    this->Superclass::ExecuteInformation();
275 }
276
277 /*
278  * Update => ouput->Update => UpdateData => Execute => ExecuteData 
279  * (see vtkSource.cxx for last step).
280  * This function (redefinition of vtkImageReader::ExecuteData, see 
281  * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
282  * extent/axes are assumed to be the same as the file extent/order.
283  */
284 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
285 {
286    if (this->InternalFileNameList.empty())
287    {
288       vtkErrorMacro(<< "A least a valid FileName must be specified.");
289       return;
290    }
291
292    // FIXME : extraneous parsing of header is made when allocating OuputData
293    //         --> ?!?
294    vtkImageData *data = this->AllocateOutputData(output);
295    data->SetExtent(this->DataExtent);
296    data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
297
298    // Test if output has valid extent
299    // Prevent memory errors
300    if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
301       (this->DataExtent[3]-this->DataExtent[2]>=0) &&
302       (this->DataExtent[5]-this->DataExtent[4]>=0))
303    {
304       // The memory size for a full stack of images of course depends
305       // on the number of planes and the size of each image:
306       //size_t StackNumPixels = this->NumColumns * this->NumLines
307       //                      * this->TotalNumberOfPlanes * this->NumComponents;
308       //size_t stack_size = StackNumPixels * this->PixelSize; //not used
309       // Allocate pixel data space itself.
310
311       // Variables for the UpdateProgress. We shall use 50 steps to signify
312       // the advance of the process:
313       unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
314                                          * this->TotalNumberOfPlanes
315                                          / 50.0);
316       // The actual advance measure:
317       unsigned long UpdateProgressCount = 0;
318
319       // Filling the allocated memory space with each image/volume:
320       unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
321       for (std::list<std::string>::iterator filename  = InternalFileNameList.begin();
322            filename != InternalFileNameList.end();
323            ++filename)
324       { 
325          // Images that were tagged as unreadable in CheckFileCoherence()
326          // are substituted with a black image to let the caller visually
327          // notice something wrong is going on:
328          if (*filename != "GDCM_UNREADABLE")
329          {
330             // Update progress related for good files is made in LoadImageInMemory
331             Dest += this->LoadImageInMemory(*filename, Dest,
332                                             UpdateProgressTarget,
333                                             UpdateProgressCount);
334          } 
335          else 
336          {
337             // We insert a black image in the stack for the user to be aware that
338             // this image/volume couldn't be loaded. We simply skip one image
339             // size:
340             Dest += this->NumColumns * this->NumLines * this->PixelSize;
341
342             // Update progress related for bad files:
343             UpdateProgressCount += this->NumLines;
344             if (UpdateProgressTarget > 0)
345             {
346                if (!(UpdateProgressCount%UpdateProgressTarget))
347                {
348                   this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
349                }
350             }
351          } // Else, file not loadable
352       } // Loop on files
353    }
354 }
355
356 /*
357  * vtkGdcmReader can have the file names specified through two ways:
358  * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
359  *     SetFilePattern()
360  * (2) By successive calls to vtkGdcmReader::AddFileName()
361  * When the first method was used by caller we need to update the local
362  * filename list
363  */
364 void vtkGdcmReader::BuildFileListFromPattern()
365 {
366    this->RemoveAllInternalFileName();
367
368    if ((! this->FileNameList.empty()) && this->FileName )
369    {
370       vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
371       vtkErrorMacro(<< "No images loaded ! ");
372       return;
373    }
374
375    if ((! this->FileNameList.empty()) && this->FilePrefix )
376    {
377       vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
378       vtkErrorMacro(<< "No images loaded ! ");
379       return;
380    }
381
382    if (this->FileName && this->FilePrefix)
383    {
384       vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
385       vtkErrorMacro(<< "No images loaded ! ");
386       return;
387    }
388
389    if (! this->FileNameList.empty()  )
390    {
391       vtkDebugMacro(<< "Using the AddFileName specified files");
392       this->InternalFileNameList=this->FileNameList;
393       return;
394    }
395
396    if (!this->FileName && !this->FilePrefix)
397    {
398       vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
399       vtkErrorMacro(<< "specify a FileName or FilePrefix.");
400       return;
401    }
402
403    if( this->FileName )
404    {
405       // Single file loading (as given with ::SetFileName()):
406       // Case of multi-frame file considered here
407       this->ComputeInternalFileName(this->DataExtent[4]);
408       vtkDebugMacro(<< "Adding file " << this->InternalFileName);
409       this->AddInternalFileName(this->InternalFileName);
410    }
411    else
412    {
413       // Multi file loading (as given with ::SetFilePattern()):
414       for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
415       {
416          this->ComputeInternalFileName(idx);
417          vtkDebugMacro(<< "Adding file " << this->InternalFileName);
418          this->AddInternalFileName(this->InternalFileName);
419       }
420    }
421 }
422
423 /*
424  * When more than one filename is specified (i.e. we expect loading
425  * a stack or volume) we need to check that the corresponding images/volumes
426  * to be loaded are coherent i.e. to make sure:
427  *     - they all share the same X dimensions
428  *     - they all share the same Y dimensions
429  *     - they all share the same ImageType ( 8 bit signed, or unsigned...)
430  *
431  * Eventually, we emit a warning when all the files do NOT share the
432  * Z dimension, since we can still build a stack but the
433  * files are not coherent in Z, which is probably a source a trouble...
434  *   When files are not readable (either the file cannot be opened or
435  * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
436  *   This method returns the total number of planar images to be loaded
437  * (i.e. an image represents one plane, but a volume represents many planes)
438  */
439 int vtkGdcmReader::CheckFileCoherence()
440 {
441    int ReturnedTotalNumberOfPlanes = 0;   // The returned value.
442
443    this->BuildFileListFromPattern();
444    if (this->InternalFileNameList.empty())
445    {
446       vtkErrorMacro(<< "FileNames are not set.");
447       return 0;
448    }
449
450    bool FoundReferenceFile = false;
451    int  ReferenceNZ = 0;
452
453    // Loop on the filenames:
454    // - check for their existence and gdcm "parsability"
455    // - get the coherence check done:
456    for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
457         filename != InternalFileNameList.end();
458         ++filename)
459    {
460       // The file is always added in the number of planes
461       //  - If file doesn't exist, it will be replaced by a black plane in the 
462       //    ExecuteData method
463       //  - If file has more than 1 plane, other planes will be added later to
464       //    to the ReturnedTotalNumberOfPlanes variable counter
465       ReturnedTotalNumberOfPlanes += 1;
466
467       /////// Stage 0: check for file name:
468
469       // fixme : how can the filename be equal to "GDCM_UNREADABLE"
470       //         right now ?!?
471
472       if(*filename == std::string("GDCM_UNREADABLE"))
473          continue;
474
475       /////// Stage 1: check for file readability:
476       // Stage 1.1: check for file existence.
477       FILE *fp;
478       fp = fopen(filename->c_str(),"rb");
479       if (!fp)
480       {
481          vtkErrorMacro(<< "Unable to open file " << filename->c_str());
482          vtkErrorMacro(<< "Removing this file from read files: "
483                      << filename->c_str());
484          *filename = "GDCM_UNREADABLE";
485          continue;
486       }
487       fclose(fp);
488
489       // Stage 1.2: check for Gdcm parsability
490
491       //gdcm::File GdcmFile( filename->c_str() );
492       // to save some parsing time.
493       gdcm::File GdcmFile;
494       GdcmFile.SetLoadMode( NO_SEQ | NO_SHADOW );
495       GdcmFile.Load(filename->c_str() );
496       if (!GdcmFile.IsReadable())
497       {
498          vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
499          vtkErrorMacro(<< "Removing this file from read files: "
500                         << filename->c_str());
501          *filename = "GDCM_UNREADABLE";
502          continue;
503       }
504
505       // Stage 1.3: further gdcm compatibility on PixelType
506       std::string type = GdcmFile.GetPixelType();
507       if (   (type !=  "8U") && (type !=  "8S")
508           && (type != "16U") && (type != "16S")
509           && (type != "32U") && (type != "32S") )
510       {
511          vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
512                        << "   File type found : " << type.c_str() 
513                        << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
514                        << "   Removing this file from readed files");
515          *filename = "GDCM_UNREADABLE";
516          continue;
517       }
518
519       // Stage 2: check coherence of the set of files
520       int NX = GdcmFile.GetXSize();
521       int NY = GdcmFile.GetYSize();
522       int NZ = GdcmFile.GetZSize();
523       if (FoundReferenceFile) 
524       {
525          // Stage 2.1: mandatory coherence stage:
526          if (   ( NX   != this->NumColumns )
527              || ( NY   != this->NumLines )
528              || ( type != this->ImageType ) ) 
529          {
530             vtkErrorMacro(<< "This file is not coherent with previous ones: "
531                            << filename->c_str());
532             vtkErrorMacro(<< "Removing this file from readed files: "
533                            << filename->c_str());
534             *filename = "GDCM_UNREADABLE";
535             continue;
536          }
537
538          // Stage 2.2: optional coherence stage
539          if ( NZ != ReferenceNZ )
540          {
541             vtkErrorMacro(<< "File is not coherent in Z with previous ones: "
542                            << filename->c_str());
543          }
544          else
545          {
546             vtkDebugMacro(<< "File is coherent with previous ones: "
547                            << filename->c_str());
548          }
549
550          // Stage 2.3: when the file is 'multiframe', notify the caller.
551          if (NZ > 1)
552          {
553             vtkErrorMacro(<< "This file is a 'Multiframe' one: "
554                            << filename->c_str());
555          }
556
557          // Eventually, this file can be added on the stack. Update the
558          // full size of the stack
559          vtkDebugMacro("Number of planes added to the stack: " << NZ);
560          ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
561          continue;
562
563       } 
564       else 
565       {
566          // We didn't have a workable reference file yet. 
567          // Set this one as the reference.
568          FoundReferenceFile = true;
569          vtkDebugMacro(<< "This file taken as coherence reference:"
570                        << filename->c_str());
571          vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
572                        << NX << " " << NY << " " << NZ);
573          vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
574          // Set aside the size of the image
575          this->NumColumns = NX;
576          this->NumLines   = NY;
577          ReferenceNZ      = NZ;
578          ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
579          this->ImageType = type;
580          this->PixelSize = GdcmFile.GetPixelSize();
581
582          if( GdcmFile.HasLUT() && this->AllowLookupTable )
583          {
584             // I could raise an error is AllowLookupTable is on and HasLUT() off
585             this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
586          }
587          else
588          {
589             this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
590          }             
591          //Set image spacing
592          this->DataSpacing[0] = GdcmFile.GetXSpacing();
593          this->DataSpacing[1] = GdcmFile.GetYSpacing();
594          this->DataSpacing[2] = GdcmFile.GetZSpacing();
595       }
596    } // End of loop on filename
597
598    ///////// The files we CANNOT load are flaged. On debugging purposes
599    // count the loadable number of files and display their number:
600    int NumberCoherentFiles = 0;
601    for (std::list<std::string>::iterator it = InternalFileNameList.begin();
602         it != InternalFileNameList.end();
603         ++it)
604    {
605       if (*it != "GDCM_UNREADABLE")
606       {
607          NumberCoherentFiles++;
608       }
609    }
610    vtkDebugMacro(<< "Number of coherent files: " << NumberCoherentFiles);
611
612    if (ReturnedTotalNumberOfPlanes == 0)
613    {
614       vtkErrorMacro(<< "No loadable file.");
615    }
616
617    vtkDebugMacro(<< "Total number of planes on the stack: "
618                   << ReturnedTotalNumberOfPlanes);
619    
620    return ReturnedTotalNumberOfPlanes;
621 }
622
623 //-----------------------------------------------------------------------------
624 // Private
625 /*
626  * Remove all file names to the internal list of images to read.
627  */
628 void vtkGdcmReader::RemoveAllInternalFileName(void)
629 {
630    this->InternalFileNameList.clear();
631 }
632
633 /*
634  * Adds a file name to the internal list of images to read.
635  */
636 void vtkGdcmReader::AddInternalFileName(const char *name)
637 {
638    char *LocalName = new char[strlen(name) + 1];
639    strcpy(LocalName, name);
640    this->InternalFileNameList.push_back(LocalName);
641    delete[] LocalName;
642 }
643
644 /*
645  * Loads the contents of the image/volume contained by Filename at
646  * the Dest memory address. Returns the size of the data loaded.
647  */
648 size_t vtkGdcmReader::LoadImageInMemory(
649              std::string fileName, 
650              unsigned char *dest,
651              const unsigned long updateProgressTarget,
652              unsigned long & updateProgressCount)
653 {
654    vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
655    gdcm::FileHelper file( fileName.c_str() );
656    size_t size;
657
658    // If the data structure of vtk for image/volume representation
659    // were straigthforwards the following would be enough:
660    //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
661    // But vtk chooses to invert the lines of an image, that is the last
662    // line comes first (for some axis related reasons?). Hence we need
663    // to load the image line by line, starting from the end.
664
665    int numColumns = file.GetFile()->GetXSize();
666    int numLines   = file.GetFile()->GetYSize();
667    int numPlanes  = file.GetFile()->GetZSize();
668    int lineSize   = NumComponents * numColumns * file.GetFile()->GetPixelSize();
669    int planeSize  = lineSize * numLines;
670
671    unsigned char *src;
672    
673    if( file.GetFile()->HasLUT() && AllowLookupTable )
674    {
675       size               = file.GetImageDataSize();
676       src                = (unsigned char*) file.GetImageDataRaw();
677       unsigned char *lut = (unsigned char*) file.GetLutRGBA();
678
679       if(!this->LookupTable)
680       {
681          this->LookupTable = vtkLookupTable::New();
682       }
683
684       this->LookupTable->SetNumberOfTableValues(256);
685       for (int tmp=0; tmp<256; tmp++)
686       {
687          this->LookupTable->SetTableValue(tmp,
688          (float)lut[4*tmp+0]/255.0,
689          (float)lut[4*tmp+1]/255.0,
690          (float)lut[4*tmp+2]/255.0,
691          1);
692       }
693       this->LookupTable->SetRange(0,255);
694       vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
695       a->GetScalars()->SetLookupTable(this->LookupTable);
696       free(lut);
697    }
698    else
699    {
700       size = file.GetImageDataSize();
701       src  = (unsigned char*)file.GetImageData();
702    } 
703
704    unsigned char *dst = dest + planeSize - lineSize;
705    for (int plane = 0; plane < numPlanes; plane++)
706    {
707       for (int line = 0; line < numLines; line++)
708       {
709          // Copy one line at proper destination:
710          memcpy((void*)dst, (void*)src, lineSize);
711          src += lineSize;
712          dst -= lineSize;
713          // Update progress related:
714          if (!(updateProgressCount%updateProgressTarget))
715          {
716             this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
717          }
718          updateProgressCount++;
719       }
720       dst += 2 * planeSize;
721    }   
722    return size;
723 }
724
725 // -------------------------------------------------------------------------
726
727 // We assume the use *does* know all the files whose names 
728 //  are in InternalFileNameList exist, may be open, are gdcm-readable
729 //  have the same sizes, have the same 'pixel' type, are single frame
730 //  have the same color convention, ..., anything else ? 
731
732 int vtkGdcmReader::CheckFileCoherenceLight()
733 {
734    std::list<std::string>::iterator filename = InternalFileNameList.begin();
735
736    gdcm::File GdcmFile;
737    GdcmFile.SetLoadMode( NO_SEQ | NO_SHADOW );
738    GdcmFile.Load(filename->c_str() );
739    if (!GdcmFile.IsReadable())
740    {
741       vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
742       vtkErrorMacro(<< "you should try vtkGdcmReader::CheckFileCoherence "
743                     << "instead of try vtkGdcmReader::CheckFileCoherenceLight");
744       return 0;
745    }
746    int NX           = GdcmFile.GetXSize();
747    int NY           = GdcmFile.GetYSize();
748    int NZ           = GdcmFile.GetZSize();
749    std::string type = GdcmFile.GetPixelType();
750    vtkDebugMacro(<< "The first file is taken as reference: "
751                  << filename->c_str());
752    vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
753                  << NX << " " << NY << " " << NZ);
754    vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
755    // Set aside the size of the image
756    this->NumColumns = NX;
757    this->NumLines   = NY;
758    this->ImageType  = type;
759    this->PixelSize  = GdcmFile.GetPixelSize();
760
761    if( GdcmFile.HasLUT() && this->AllowLookupTable )
762    {
763       // I could raise an error is AllowLookupTable is on and HasLUT() off
764       this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
765    }
766    else
767    {
768       this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
769    }
770        
771    //Set image spacing
772    this->DataSpacing[0] = GdcmFile.GetXSpacing();
773    this->DataSpacing[1] = GdcmFile.GetYSpacing();
774    this->DataSpacing[2] = GdcmFile.GetZSpacing();
775
776    return InternalFileNameList.size();
777 }
778 //-----------------------------------------------------------------------------