]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
Name Space
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkGdcmReader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/06/19 13:09:45 $
7   Version:   $Revision: 1.90 $
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 //
22 //===>  Many users expect from vtkGdcmReader it 'orders' the images
23 //     (that's the job of gdcm::SerieHelper ...)
24 //     When user *knows* the files with same Serie UID 
25 //        have same sizes, same 'pixel' type, same color convention, ...
26 //     the right way to proceed is as follow :
27 //
28 //      gdcm::SerieHelper *sh= new gdcm::SerieHelper();
29 //      // if user wants *not* to load some parts of the file headers
30 //      sh->SetLoadMode(loadMode);
31 //
32 //      // if user wants *not* to load some files 
33 //      sh->AddRestriction(group, element, value, operator);
34 //      sh->AddRestriction( ...
35 //      sh->SetDirectory(directoryWithImages);
36 //
37 //      // if user wants to sort reverse order
38 //      sh->SetSortOrderToReverse(); 
39 //
40 //      // here, we suppose only the first 'Serie' is of interest
41 //      // it's up to the user to decide !
42 //      gdcm::FileList *l = sh->GetFirstSingleSerieUIDFileSet();
43 //
44 //      // if user is doesn't trust too much the files with same Serie UID 
45 //      if ( !sh->IsCoherent(l) )
46 //         return; // not same sizes, same 'pixel' type -> stop
47 //
48 //      // WARNING : all  that follows works only with 'bona fide' Series
49 //      // (In some Series; there are more than one 'orientation'
50 //      // Don't expected to build a 'volume' with that!
51 //      //
52 //      // -> use sh->SplitOnOrientation(l)
53 //      //  - or sh->SplitOnPosition(l), or SplitOnTagValue(l, gr, el) -
54 //      // depending on what you want to do
55 //      // and iterate on the various 'X Coherent File Sets'
56 //
57 //      // if user *knows* he has to drop the 'duplicates' images
58 //      // (same Position)
59 //      sh->SetDropDuplicatePositions(true);
60 //
61 //      // Sorting the list is mandatory
62 //      // a side effect is to compute ZSpacing for the fle set
63 //      sh->OrderFileList(l);        // sort the list
64 //
65 //      vtkGdcmReader *reader = vtkGdcmReader::New();
66 //
67 //      // if user wants to modify pixel order (Mirror, TopDown, 90°Rotate, ...)
68 //      // he has to supply the function that does the job 
69 //      // (a *very* simple example is given in vtkgdcmSerieViewer.cxx)
70 //      reader->SetUserFunction (userSuppliedFunction);
71 //
72 //      // to pass a 'Coherent File List' as produced by gdcm::SerieHelper
73 //      reader->SetCoherentFileList(l); 
74 //      reader->Update();
75 //
76 // WARNING TODO CLEANME 
77 // Actual limitations of this code 
78 //  when a Coherent File List from SerieHelper is not used (bad idea :-(
79 //
80 // //////////////////////////////////////////////////////////////
81
82 #include "gdcmFileHelper.h"
83 #include "gdcmFile.h"
84 #include "gdcmSerieHelper.h" // for ImagePositionPatientOrdering()
85
86 #include "vtkGdcmReader.h"
87 #include "gdcmDebug.h"
88 #include "gdcmCommon.h"
89
90 #include <vtkObjectFactory.h>
91 #include <vtkImageData.h>
92 #include <vtkPointData.h>
93 #include <vtkLookupTable.h>
94
95 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.90 $")
96 vtkStandardNewMacro(vtkGdcmReader)
97
98 //-----------------------------------------------------------------------------
99 // Constructor / Destructor
100 vtkGdcmReader::vtkGdcmReader()
101 {
102    this->LookupTable = NULL;
103    this->AllowLookupTable = false;
104    //this->AllowLightChecking = false;
105    this->LoadMode = GDCM_NAME_SPACE::LD_ALL; // Load everything (possible values : 
106                                   //  - LD_NOSEQ, 
107                                   //  - LD_NOSHADOW,
108                                   //  - LD_NOSHADOWSEQ)
109    this->CoherentFileList = 0;
110    this->UserFunction     = 0;
111
112    this->OwnFile=true;
113    // this->Execution=false; // For VTK5.0
114 }
115
116 vtkGdcmReader::~vtkGdcmReader()
117 {
118    this->RemoveAllFileName();
119    this->InternalFileNameList.clear();
120    if(this->LookupTable) 
121       this->LookupTable->Delete();
122 }
123
124 //-----------------------------------------------------------------------------
125 // Print
126 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
127 {
128    this->Superclass::PrintSelf(os,indent);
129    os << indent << "Filenames  : " << endl;
130    vtkIndent nextIndent = indent.GetNextIndent();
131    for (std::list<std::string>::iterator it = FileNameList.begin();
132         it != FileNameList.end();
133         ++it)
134    {
135       os << nextIndent << it->c_str() << endl ;
136    }
137 }
138
139 //-----------------------------------------------------------------------------
140 // Public
141 /*
142  * Remove all files from the list of images to read.
143  */
144 void vtkGdcmReader::RemoveAllFileName(void)
145 {
146    this->FileNameList.clear();
147    this->Modified();
148 }
149
150 /*
151  * Adds a file name to the list of images to read.
152  */
153 void vtkGdcmReader::AddFileName(const char* name)
154 {
155    // We need to bypass the const pointer [since list<>.push_bash() only
156    // takes a char* (but not a const char*)] by making a local copy:
157    this->FileNameList.push_back(name);
158    this->Modified();
159 }
160
161 /*
162  * Sets up a filename to be read.
163  */
164 void vtkGdcmReader::SetFileName(const char *name) 
165 {
166    vtkImageReader2::SetFileName(name);
167    // Since we maintain a list of filenames, when building a volume,
168    // (see vtkGdcmReader::AddFileName), we additionaly need to purge
169    // this list when we manually positionate the filename.
170    vtkDebugMacro(<< "Clearing all files given with AddFileName");
171    this->FileNameList.clear();
172    this->Modified();
173 }
174
175 //-----------------------------------------------------------------------------
176 // Protected
177 /*
178  * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
179  */
180 void vtkGdcmReader::ExecuteInformation()
181 {
182 //   if(this->Execution)  // For VTK5.0
183 //      return;
184 //
185 //   this->Execution=true; // end For VTK5.0
186    this->RemoveAllInternalFile();
187    if(this->MTime>this->fileTime)
188    {
189       this->TotalNumberOfPlanes = 0;
190
191       if ( this->CoherentFileList != 0 )
192       {
193          this->UpdateFileInformation();
194       }
195       else
196       {
197          this->BuildFileListFromPattern();
198          this->LoadFileInformation();
199       }
200
201       if ( this->TotalNumberOfPlanes == 0)
202       {
203          vtkErrorMacro(<< "File set is not coherent. Exiting...");
204          return;
205       }
206
207       // if the user has not set the extent, but has set the VOI
208       // set the z axis extent to the VOI z axis
209       if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
210          (this->DataVOI[4] || this->DataVOI[5]))
211       {
212          this->DataExtent[4] = this->DataVOI[4];
213          this->DataExtent[5] = this->DataVOI[5];
214       }
215
216       // When the user has set the VOI, check it's coherence with the file content.
217       if (this->DataVOI[0] || this->DataVOI[1] || 
218       this->DataVOI[2] || this->DataVOI[3] ||
219       this->DataVOI[4] || this->DataVOI[5])
220       { 
221          if ((this->DataVOI[0] < 0) ||
222              (this->DataVOI[1] >= this->NumColumns) ||
223              (this->DataVOI[2] < 0) ||
224              (this->DataVOI[3] >= this->NumLines) ||
225              (this->DataVOI[4] < 0) ||
226              (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
227          {
228             vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
229             this->DataVOI[0] = 0;
230             this->DataVOI[1] = this->NumColumns - 1;
231             this->DataVOI[2] = 0;
232             this->DataVOI[3] = this->NumLines - 1;
233             this->DataVOI[4] = 0;
234             this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
235          }
236       }
237
238       // Set the Extents.
239       this->DataExtent[0] = 0;
240       this->DataExtent[1] = this->NumColumns - 1;
241       this->DataExtent[2] = 0;
242       this->DataExtent[3] = this->NumLines - 1;
243       this->DataExtent[4] = 0;
244       this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
245   
246       // We don't need to set the Endian related stuff (by using
247       // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
248       // since the reading of the file is done by gdcm.
249       // But we do need to set up the data type for downstream filters:
250       if      ( ImageType == "8U" )
251       {
252          vtkDebugMacro(<< "8 bits unsigned image");
253          this->SetDataScalarTypeToUnsignedChar(); 
254       }
255       else if ( ImageType == "8S" )
256       {
257          vtkErrorMacro(<< "Cannot handle 8 bit signed files");
258          return;
259       }
260       else if ( ImageType == "16U" )
261       {
262          vtkDebugMacro(<< "16 bits unsigned image");
263          this->SetDataScalarTypeToUnsignedShort();
264       }
265       else if ( ImageType == "16S" )
266       {
267          vtkDebugMacro(<< "16 bits signed image");
268          this->SetDataScalarTypeToShort();
269       }
270       else if ( ImageType == "32U" )
271       {
272          vtkDebugMacro(<< "32 bits unsigned image");
273          vtkDebugMacro(<< "WARNING: forced to signed int !");
274          this->SetDataScalarTypeToInt();
275       }
276       else if ( ImageType == "32S" )
277       {
278          vtkDebugMacro(<< "32 bits signed image");
279          this->SetDataScalarTypeToInt();
280       }
281       else if ( ImageType == "FD" )
282       {
283          vtkDebugMacro(<< "64 bits Double image");
284          this->SetDataScalarTypeToDouble();
285       }
286       //Set number of scalar components:
287       this->SetNumberOfScalarComponents(this->NumComponents);
288
289       this->fileTime=this->MTime;
290    }
291
292    this->Superclass::ExecuteInformation();  
293
294    //this->GetOutput()->SetUpdateExtentToWholeExtent();// For VTK5.0
295    //this->BuildData(this->GetOutput());
296
297    //this->Execution=false;
298    //this->RemoveAllInternalFile();                   // End For VTK5.0
299 }
300  
301 /*
302  * Update => ouput->Update => UpdateData => Execute => ExecuteData 
303  * (see vtkSource.cxx for last step).
304  * This function (redefinition of vtkImageReader::ExecuteData, see 
305  * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
306  * extent/axes are assumed to be the same as the file extent/order.
307  */
308 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
309 {
310    vtkImageData *data=vtkImageData::SafeDownCast(output);
311    data->SetExtent(this->DataExtent);
312
313 /*   if ( CoherentFileList != 0 )   // When a list of names is passed
314    {
315       if (this->CoherentFileList->empty())
316       {
317          vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
318          return;
319       }
320    }
321    else if (this->InternalFileNameList.empty())
322    {
323       vtkErrorMacro(<< "A least a valid FileName must be specified.");
324       return;
325    }
326 */
327   
328   // data->AllocateScalars();  // For VTK5.0
329   // if (this->UpdateExtentIsEmpty(output))
330   // {
331   //    return;
332   // }
333 //}                           // end For VTK5.0
334
335    data->AllocateScalars();  // For VTK5.0
336    if (this->UpdateExtentIsEmpty(output))
337    {
338       return;
339    }
340    
341 //void vtkGdcmReader::BuildData(vtkDataObject *output)  // For VTK5.0
342 //{
343 //   vtkImageData *data = this->AllocateOutputData(output);  // end For VTK5.0
344
345    data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
346
347    // Test if output has valid extent
348    // Prevent memory errors
349    if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
350       (this->DataExtent[3]-this->DataExtent[2]>=0) &&
351       (this->DataExtent[5]-this->DataExtent[4]>=0))
352    {
353       // The memory size for a full stack of images of course depends
354       // on the number of planes and the size of each image:
355       //size_t StackNumPixels = this->NumColumns * this->NumLines
356       //                      * this->TotalNumberOfPlanes * this->NumComponents;
357       //size_t stack_size = StackNumPixels * this->PixelSize; //not used
358       // Allocate pixel data space itself.
359
360       // Variables for the UpdateProgress. We shall use 50 steps to signify
361       // the advance of the process:
362       unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
363                                          * this->TotalNumberOfPlanes
364                                          / 50.0);
365       // The actual advance measure:
366       unsigned long UpdateProgressCount = 0;
367
368       // Filling the allocated memory space with each image/volume:
369
370       size_t size = this->NumColumns * this->NumLines * this->NumPlanes
371                   * data->GetScalarSize() * this->NumComponents;
372       unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
373       for (std::vector<GDCM_NAME_SPACE::File* >::iterator it =  InternalFileList.begin();
374                                                it != InternalFileList.end();
375                                              ++it)
376       {
377          this->LoadImageInMemory(*it, Dest,
378                                  UpdateProgressTarget,
379                                  UpdateProgressCount); 
380          Dest += size;
381       }
382    }
383    this->RemoveAllInternalFile(); // For VTK5.0
384 }
385
386 /*
387  * vtkGdcmReader can have the file names specified through two ways:
388  * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
389  *     SetFilePattern()
390  * (2) By successive calls to vtkGdcmReader::AddFileName()
391  * When the first method was used by caller we need to update the local
392  * filename list
393  */
394 void vtkGdcmReader::BuildFileListFromPattern()
395 {
396    this->RemoveAllInternalFileName();
397
398    // Test miscellanous cases
399    if ((! this->FileNameList.empty()) && this->FileName )
400    {
401       vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
402       vtkErrorMacro(<< "No images loaded ! ");
403       return;
404    }
405
406    if ((! this->FileNameList.empty()) && this->FilePrefix )
407    {
408       vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
409       vtkErrorMacro(<< "No images loaded ! ");
410       return;
411    }
412
413    if (this->FileName && this->FilePrefix)
414    {
415       vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
416       vtkErrorMacro(<< "No images loaded ! ");
417       return;
418    }
419
420    // Create the InternalFileNameList
421    if (! this->FileNameList.empty()  )
422    {
423       vtkDebugMacro(<< "Using the AddFileName specified files");
424       this->InternalFileNameList=this->FileNameList;
425       return;
426    }
427
428    if (!this->FileName && !this->FilePrefix)
429    {
430       vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
431       vtkErrorMacro(<< "specify a FileName or FilePrefix.");
432       return;
433    }
434
435    if( this->FileName )
436    {
437       // Single file loading (as given with ::SetFileName()):
438       // Case of multi-frame file considered here
439       this->ComputeInternalFileName(this->DataExtent[4]);
440       vtkDebugMacro(<< "Adding file " << this->InternalFileName);
441       this->AddInternalFileName(this->InternalFileName);
442    }
443    else
444    {
445       // Multi file loading (as given with ::SetFilePattern()):
446       for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
447       {
448          this->ComputeInternalFileName(idx);
449          vtkDebugMacro(<< "Adding file " << this->InternalFileName);
450          this->AddInternalFileName(this->InternalFileName);
451       }
452    }
453 }
454
455 /**
456  * Load all the files and set it in the InternalFileList
457  * For each file, the readability and the coherence of image caracteristics 
458  * are tested. If an image doesn't agree the required specifications, it
459  * isn't considered and no data will be set for the planes corresponding
460  * to this image
461  *
462  * The source of this work is the list of file name generated by the
463  * BuildFileListFromPattern method
464  */
465 void vtkGdcmReader::LoadFileInformation()
466 {
467    GDCM_NAME_SPACE::File *file;
468    bool foundReference=false;
469    std::string type;
470
471    this->OwnFile=true;
472    for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
473         filename != InternalFileNameList.end();
474         ++filename)
475    {
476       // check for file readability
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          file = NULL;
485          InternalFileList.push_back(file);
486          continue;
487       }
488       fclose(fp);
489
490       // Read the file
491       file=GDCM_NAME_SPACE::File::New();
492       file->SetLoadMode( LoadMode );
493       file->SetFileName(filename->c_str() );
494       file->Load();
495
496       // Test the Dicom file readability
497       if(!file->IsReadable())
498       {
499          vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
500          vtkErrorMacro(<< "Removing this file from read files: "
501                         << filename->c_str());
502          file->Delete();
503          file=NULL;
504          InternalFileList.push_back(file);
505          continue;
506       }
507
508       // Test the Pixel Type recognition
509       type = file->GetPixelType();
510       if (   (type !=  "8U") && (type !=  "8S")
511           && (type != "16U") && (type != "16S")
512           && (type != "32U") && (type != "32S") )
513       {
514          vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
515                        << "   File type found : " << type.c_str() 
516                        << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
517                        << "   Removing this file from read files");
518          file->Delete();
519          file=NULL;
520          InternalFileList.push_back(file);
521          continue;
522       }
523
524       // Test the image informations
525       if(!foundReference)
526       {
527          foundReference = true;
528          GetFileInformation(file);
529
530          vtkDebugMacro(<< "This file taken as coherence reference:"
531                         << filename->c_str());
532          vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
533                         << this->NumColumns << " " << this->NumLines << " " 
534                         << this->NumPlanes);
535       }
536       else if(!TestFileInformation(file))
537       {
538          file->Delete();
539          file=NULL;
540       }
541
542       InternalFileList.push_back(file);
543    }
544 }
545
546 /**
547  * Update the file informations.
548  * This works exactly like LoadFileInformation, but the source of work
549  * is the list of coherent files
550  */
551 void vtkGdcmReader::UpdateFileInformation()
552 {
553    this->InternalFileList=*(this->CoherentFileList);
554    this->OwnFile=false;
555
556    for(gdcmFileList::iterator it=InternalFileList.begin();
557                               it!=InternalFileList.end();
558                               ++it)
559    {
560       if( *it != NULL)
561       {
562          GetFileInformation(*it);
563          break;
564       }
565    }
566 }
567
568 /**
569  * Get the informations from a file.
570  * These informations are required to specify the output image
571  * caracteristics
572  */
573 void vtkGdcmReader::GetFileInformation(GDCM_NAME_SPACE::File *file)
574 {
575    // Get the image caracteristics
576    this->NumColumns = file->GetXSize();
577    this->NumLines   = file->GetYSize();
578    this->NumPlanes  = file->GetZSize();
579
580    if (CoherentFileList == 0)
581       this->TotalNumberOfPlanes = this->NumPlanes*InternalFileNameList.size();
582    else
583       this->TotalNumberOfPlanes = this->NumPlanes*CoherentFileList->size();
584
585    this->ImageType = file->GetPixelType();
586    this->PixelSize = file->GetPixelSize();
587
588    this->DataSpacing[0] = file->GetXSpacing();
589    this->DataSpacing[1] = file->GetYSpacing();
590    
591    //  Most of the file headers have NO z spacing
592    //  It must be calculated from the whole gdcm::Serie (if any)
593    //  using Jolinda Smith's algoritm.
594    //  see gdcm::SerieHelper::ImagePositionPatientOrdering()
595    if (CoherentFileList == 0)   
596       this->DataSpacing[2] = file->GetZSpacing();
597    else
598    {
599        // Just because OrderFileList() is a member of gdcm::SerieHelper
600        // we need to instanciate sh.
601       GDCM_NAME_SPACE::SerieHelper *sh = GDCM_NAME_SPACE::SerieHelper::New();
602       sh->OrderFileList(CoherentFileList); // calls ImagePositionPatientOrdering()
603       this->DataSpacing[2] = sh->GetZSpacing();
604       sh->Delete();         
605    } 
606
607    // Get the image data caracteristics
608    if( file->HasLUT() && this->AllowLookupTable )
609    {
610       // I could raise an error is AllowLookupTable is on and HasLUT() off
611       this->NumComponents = file->GetNumberOfScalarComponentsRaw();
612    }
613    else
614    {
615       this->NumComponents = file->GetNumberOfScalarComponents(); //rgb or mono
616    }
617 }
618
619 /*
620  * When more than one filename is specified (i.e. we expect loading
621  * a stack or volume) we need to check that the corresponding images/volumes
622  * to be loaded are coherent i.e. to make sure:
623  *     - they all share the same X dimensions
624  *     - they all share the same Y dimensions
625  *     - they all share the same ImageType ( 8 bit signed, or unsigned...)
626  *
627  * Eventually, we emit a warning when all the files do NOT share the
628  * Z dimension, since we can still build a stack but the
629  * files are not coherent in Z, which is probably a source a trouble...
630  *   When files are not readable (either the file cannot be opened or
631  * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
632  *   This method returns the total number of planar images to be loaded
633  * (i.e. an image represents one plane, but a volume represents many planes)
634  */
635 /**
636  * Test the coherent informations of the file with the reference informations
637  * used as image caracteristics. The tested informations are :
638  * - they all share the same X dimensions
639  * - they all share the same Y dimensions
640  * - they all share the same Z dimensions
641  * - they all share the same number of components
642  * - they all share the same ImageType ( 8 bit signed, or unsigned...)
643  *
644  * \return True if the file match, False otherwise
645  */
646 bool vtkGdcmReader::TestFileInformation(GDCM_NAME_SPACE::File *file)
647 {
648    int numColumns = file->GetXSize();
649    int numLines   = file->GetYSize();
650    int numPlanes  = file->GetZSize();
651    int numComponents;
652    unsigned int pixelSize  = file->GetPixelSize();
653
654    if( file->HasLUT() && this->AllowLookupTable )
655       numComponents = file->GetNumberOfScalarComponentsRaw();
656    else
657       numComponents = file->GetNumberOfScalarComponents(); //rgb or mono
658
659    if( numColumns != this->NumColumns )
660    {
661       vtkErrorMacro(<< "File X value doesn't match with the previous ones: "
662                     << file->GetFileName().c_str()
663                     << ". Found " << numColumns << ", must be "
664                     << this->NumColumns);
665       return false;
666    }
667    if( numLines != this->NumLines )
668    {
669       vtkErrorMacro(<< "File Y value doesn't match with the previous ones: "
670                     << file->GetFileName().c_str()
671                     << ". Found " << numLines << ", must be "
672                     << this->NumLines);
673       return false;
674    }
675    if( numPlanes != this->NumPlanes )
676    {
677       vtkErrorMacro(<< "File Z value doesn't match with the previous ones: "
678                     << file->GetFileName().c_str()
679                     << ". Found " << numPlanes << ", must be "
680                     << this->NumPlanes);
681       return false;
682    }
683    if( numComponents != this->NumComponents )
684    {
685       vtkErrorMacro(<< "File Components count doesn't match with the previous ones: "
686                     << file->GetFileName().c_str()
687                     << ". Found " << numComponents << ", must be "
688                     << this->NumComponents);
689       return false;
690    }
691    if( pixelSize != this->PixelSize )
692    {
693       vtkErrorMacro(<< "File pixel size doesn't match with the previous ones: "
694                     << file->GetFileName().c_str()
695                     << ". Found " << pixelSize << ", must be "
696                     << this->PixelSize);
697       return false;
698    }
699
700    return true;
701 }
702
703 //-----------------------------------------------------------------------------
704 // Private
705 /*
706  * Remove all file names to the internal list of images to read.
707  */
708 void vtkGdcmReader::RemoveAllInternalFileName(void)
709 {
710    this->InternalFileNameList.clear();
711 }
712
713 /*
714  * Adds a file name to the internal list of images to read.
715  */
716 void vtkGdcmReader::AddInternalFileName(const char *name)
717 {
718    char *LocalName = new char[strlen(name) + 1];
719    strcpy(LocalName, name);
720    this->InternalFileNameList.push_back(LocalName);
721    delete[] LocalName;
722 }
723
724 /*
725  * Remove all file names to the internal list of images to read.
726  */
727 void vtkGdcmReader::RemoveAllInternalFile(void)
728 {
729    if(this->OwnFile)
730    {
731       for(gdcmFileList::iterator it=InternalFileList.begin();
732                                  it!=InternalFileList.end();
733                                  ++it)
734       {
735          (*it)->Delete();
736       }
737    }
738    this->InternalFileList.clear();
739 }
740
741 void vtkGdcmReader::IncrementProgress(const unsigned long updateProgressTarget,
742                                       unsigned long &updateProgressCount)
743 {
744    // Update progress related for bad files:
745    updateProgressCount += this->NumLines;
746    if (updateProgressTarget > 0)
747    {
748       if (!(updateProgressCount%updateProgressTarget))
749       {
750          this->UpdateProgress(
751              updateProgressCount/(50.0*updateProgressTarget));
752       }
753    }
754 }
755
756 /*
757  * Loads the contents of the image/volume contained by char *fileName at
758  * the dest memory address. Returns the size of the data loaded.
759  */
760 /*void vtkGdcmReader::LoadImageInMemory(
761              std::string fileName, 
762              unsigned char *dest,
763              const unsigned long updateProgressTarget,
764              unsigned long &updateProgressCount)
765 {
766    vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
767
768    gdcm::File *f;
769    f = new gdcm::File();
770    f->SetLoadMode( LoadMode );
771    f->SetFileName( fileName.c_str() );
772    f->Load( );
773
774    LoadImageInMemory(f,dest,
775                      updateProgressTarget,
776                      updateProgressCount);
777    delete f;
778 }*/
779
780 /*
781  * Loads the contents of the image/volume contained by gdcm::File* f at
782  * the Dest memory address. Returns the size of the data loaded.
783  * \ param f File to consider. NULL if the file must be skiped
784  * \remarks Assume that if (f != NULL) then its caracteristics match
785  * with the previous ones
786  */
787 void vtkGdcmReader::LoadImageInMemory(
788              GDCM_NAME_SPACE::File *f, 
789              unsigned char *dest,
790              const unsigned long updateProgressTarget,
791              unsigned long &updateProgressCount)
792 {
793    if(!f)
794       return;
795
796    GDCM_NAME_SPACE::FileHelper *fileH = GDCM_NAME_SPACE::FileHelper::New( f );
797    fileH->SetUserFunction( UserFunction );
798
799    int numColumns = f->GetXSize();
800    int numLines   = f->GetYSize();
801    int numPlanes  = f->GetZSize();
802    int numComponents;
803
804    if( f->HasLUT() && this->AllowLookupTable )
805       numComponents = f->GetNumberOfScalarComponentsRaw();
806    else
807       numComponents = f->GetNumberOfScalarComponents(); //rgb or mono
808    vtkDebugMacro(<< "numComponents:" << numComponents);
809    vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName().c_str() << "]");
810    //size_t size;
811
812    // If the data structure of vtk for image/volume representation
813    // were straigthforwards the following would be enough:
814    //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
815    // But vtk chooses to invert the lines of an image, that is the last
816    // line comes first (for some axis related reasons?). Hence we need
817    // to load the image line by line, starting from the end.
818
819    int lineSize   = NumComponents * numColumns * f->GetPixelSize();
820    int planeSize  = lineSize * numLines;
821
822    unsigned char *src;
823    
824    if( fileH->GetFile()->HasLUT() && AllowLookupTable )
825    {
826       // to avoid bcc 5.5 w
827       /*size               = */ fileH->GetImageDataSize(); 
828       src                = (unsigned char*) fileH->GetImageDataRaw();
829       unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
830
831       if(!this->LookupTable)
832       {
833          this->LookupTable = vtkLookupTable::New();
834       }
835
836       this->LookupTable->SetNumberOfTableValues(256);
837       for (int tmp=0; tmp<256; tmp++)
838       {
839          this->LookupTable->SetTableValue(tmp,
840          (float)lut[4*tmp+0]/255.0,
841          (float)lut[4*tmp+1]/255.0,
842          (float)lut[4*tmp+2]/255.0,
843          1);
844       }
845       this->LookupTable->SetRange(0,255);
846       vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
847       a->GetScalars()->SetLookupTable(this->LookupTable);
848       free(lut);
849    }
850    else
851    {
852       //size = fileH->GetImageDataSize(); 
853       // useless - just an accessor;  'size' unused
854       src  = (unsigned char*)fileH->GetImageData();  
855    } 
856
857    unsigned char *dst = dest + planeSize - lineSize;
858    for (int plane = 0; plane < numPlanes; plane++)
859    {
860       for (int line = 0; line < numLines; line++)
861       {
862          // Copy one line at proper destination:
863          memcpy((void*)dst, (void*)src, lineSize);
864          src += lineSize;
865          dst -= lineSize;
866          // Update progress related:
867          if (!(updateProgressCount%updateProgressTarget))
868          {
869             this->UpdateProgress(
870                updateProgressCount/(50.0*updateProgressTarget));
871          }
872          updateProgressCount++;
873       }
874       dst += 2 * planeSize;
875    }
876
877    fileH->Delete();
878 }
879
880 //-----------------------------------------------------------------------------