vtkWindBladeReader.cxx 47 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
/*=========================================================================

Program:   Visualization Toolkit
Module:    vtkWindBladeReader.cxx

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkWindBladeReader.h"

#include "vtkCallbackCommand.h"
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkDataArraySelection.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkStructuredGrid.h"
#include "vtkUnstructuredGrid.h"
#include "vtkStreamingDemandDrivenPipeline.h"

#include <vtkstd/string>
#include <vtksys/ios/sstream>
#include <vtksys/ios/iostream>

#include "vtkMultiProcessController.h"

using namespace vtkstd;

#ifdef WIN32
string Slash("\\");
#else
string Slash("/");
#endif

vtkCxxRevisionMacro(vtkWindBladeReader, "1.1");
vtkStandardNewMacro(vtkWindBladeReader);

//----------------------------------------------------------------------------
// Constructor for WindBlade Reader
//----------------------------------------------------------------------------
vtkWindBladeReader::vtkWindBladeReader()
{
  this->Filename = NULL;
  this->SetNumberOfInputPorts(0);

  // Set up two output ports, one for fields, one for blades
  this->SetNumberOfOutputPorts(2);
  vtkUnstructuredGrid* blade = vtkUnstructuredGrid::New();
  blade->ReleaseData();
  this->GetExecutive()->SetOutputData(1, blade);
  blade->Delete();

  // Irregularly spaced grid description for entire problem
  this->Points = vtkPoints::New();
  this->SetSpacing = 1;

  // Blade geometry
  this->BPoints = vtkPoints::New();
  this->NumberOfBladePoints = 0;
  this->NumberOfBladeCells = 0;

  // Static tower information
  this->NumberOfBladeTowers = 0;
  this->XPosition = vtkFloatArray::New();
  this->YPosition = vtkFloatArray::New();
  this->HubHeight = vtkFloatArray::New();
  this->BladeCount = vtkIntArray::New();

  // Options to include extra files for topography and turbines
  this->UseTopographyFile = 0;
  this->UseTurbineFile = 0;

  // Setup selection callback to modify this object when array selection changes
  this->SelectionObserver = vtkCallbackCommand::New();
  this->SelectionObserver->SetCallback(&vtkWindBladeReader::SelectionCallback);
  this->SelectionObserver->SetClientData(this);

  this->PointDataArraySelection = vtkDataArraySelection::New();
  this->PointDataArraySelection->AddObserver(vtkCommand::ModifiedEvent,
                                             this->SelectionObserver);

  // Variables need to be divided by density
  this->NumberOfTimeSteps = 1;
  this->NumberOfVariables = 0;
  this->DivideVariables = vtkStringArray::New();
  this->DivideVariables->InsertNextValue("UVW");
  this->DivideVariables->InsertNextValue("A-scale turbulence");
  this->DivideVariables->InsertNextValue("B-scale turbulence");
  this->DivideVariables->InsertNextValue("Oxygen");

  // Two output require Modified() to be set causing RequestData done twice
  // Keep track of which time through on a time step to save reloading data
  this->RequestDataLoop = 0;

  // Set rank and total number of processors
  this->MPIController = vtkMultiProcessController::GetGlobalController();
  
  if(this->MPIController)
    {
    this->Rank = this->MPIController->GetLocalProcessId();
    this->TotalRank = this->MPIController->GetNumberOfProcesses();
    }
  else
    {
    this->Rank = 0;
    this->TotalRank = 1;
    }

}

//----------------------------------------------------------------------------
// Destructor for WindBlade Reader
//----------------------------------------------------------------------------
vtkWindBladeReader::~vtkWindBladeReader()
{
  if (this->Filename)
    {
      delete[] this->Filename;
    }
  this->PointDataArraySelection->Delete();
  this->DivideVariables->Delete();

  this->XPosition->Delete();
  this->YPosition->Delete();
  this->HubHeight->Delete();
  this->BladeCount->Delete();

  this->Points->Delete();
  this->BPoints->Delete();
}

//----------------------------------------------------------------------------
// Print information about WindBlade Reader
//----------------------------------------------------------------------------
void vtkWindBladeReader::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "FileName: "
     << (this->Filename ? this->Filename : "(NULL)") << endl;

  os << indent << "VariableArraySelection:" << endl;
  this->PointDataArraySelection->PrintSelf(os, indent.GetNextIndent());
}

//----------------------------------------------------------------------------
// RequestInformation supplies global meta information
//----------------------------------------------------------------------------
int vtkWindBladeReader::RequestInformation(
      vtkInformation* request,
      vtkInformationVector** inputVector,
      vtkInformationVector* outputVector)
{ 
  // Get ParaView information and output pointers
  vtkInformation* fieldInfo = outputVector->GetInformationObject(0);
  vtkStructuredGrid *field = vtkStructuredGrid::SafeDownCast(
                             fieldInfo->Get(vtkDataObject::DATA_OBJECT()));

  // Read global size and variable information from input file one time
  if (this->NumberOfVariables == 0) {

    // Read the size of the problem and variables in data set
    ReadGlobalData();

    // If turbine file exists setup number of cells and points in blades, towers
    if (this->UseTurbineFile == 1)
      SetupBladeData();

    // Allocate the ParaView data arrays which will hold the variable data
    this->data = new vtkFloatArray*[this->NumberOfVariables];
    for (int var = 0; var < this->NumberOfVariables; var++) {
      this->data[var] = vtkFloatArray::New();
      this->data[var]->SetName(VariableName[var].c_str());
      this->PointDataArraySelection->AddArray(this->VariableName[var].c_str());
    }

    // Set up extent information manually for now
    this->WholeExtent[0] = this->WholeExtent[2] = this->WholeExtent[4] = 0;
    this->WholeExtent[1] = this->Dimension[0] - 1;
    this->WholeExtent[3] = this->Dimension[1] - 1;
    this->WholeExtent[5] = this->Dimension[2] - 1;     

    field->SetWholeExtent(this->WholeExtent);
    fieldInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
                   this->WholeExtent, 6);

    // Collect temporal information
    this->TimeSteps = NULL;

    if (this->NumberOfTimeSteps > 0) {
      this->TimeSteps = new double[this->NumberOfTimeSteps];

      this->TimeSteps[0] = (double) this->TimeStepFirst;
      for (int step = 1; step < this->NumberOfTimeSteps; step++)
        this->TimeSteps[step] = this->TimeSteps[step-1] + 
                                (double) this->TimeStepDelta;

      // Tell the pipeline what steps are available
      fieldInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),
                     this->TimeSteps, this->NumberOfTimeSteps);

      // Range is required to get GUI to show things
      double tRange[2];
      tRange[0] = this->TimeSteps[0];
      tRange[1] = this->TimeSteps[this->NumberOfTimeSteps - 1];
      fieldInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), tRange, 2);
    } else {
      fieldInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
      fieldInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),
                   this->TimeSteps, this->NumberOfTimeSteps);
    }
  }
  return 1;
}

//----------------------------------------------------------------------------
// RequestUpdateExtent asks the partitioning for this processor
// ParaView is doing the partitioning for this reader
//----------------------------------------------------------------------------
int vtkWindBladeReader::RequestUpdateExtent(
      vtkInformation* request,
      vtkInformationVector** inputVector,
      vtkInformationVector* outputVector)
{
  // If Modified is not set, blades do not turn
  this->Modified();

  vtkInformation* fieldInfo = outputVector->GetInformationObject(0);
  vtkStructuredGrid *field = GetFieldOutput();
  field->SetDimensions(this->Dimension);
  field->SetWholeExtent(this->WholeExtent);

  vtkInformation* bladeInfo = outputVector->GetInformationObject(1);
  vtkUnstructuredGrid* blade = GetBladeOutput();
  blade->SetWholeExtent(this->WholeExtent);

  // Fetch the extents on this processor from stream and set in output object
  fieldInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), 
                 this->SubExtent);

  // Set the subextent dimension size
  this->SubDimension[0] = this->SubExtent[1] - this->SubExtent[0] + 1;
  this->SubDimension[1] = this->SubExtent[3] - this->SubExtent[2] + 1;
  this->SubDimension[2] = this->SubExtent[5] - this->SubExtent[4] + 1;

  // Total size of the subextent
  this->NumberOfTuples = 1;
  for (int dim = 0; dim < DIMENSION; dim++)
    this->NumberOfTuples *= this->SubDimension[dim];

  // Set the variable spacing for this subextent one time only
  if (this->SetSpacing == 1) {
    CreateCoordinates();
    this->SetSpacing = 0;
  }
  return 1;
}

//----------------------------------------------------------------------------
// RequestData populates the output object with data for rendering
// Using two output ports (one for fields and one for turbine blades)
// is not working as expected.  Modified() must be set on the reader in
// order for the blade geometry to be updated.  This means every RequestData
// for a time step will be called twice.  To keep from reading field data
// twice, we use RequestDataLoop, so that the second time will set the
// data but not actually read in again.
//----------------------------------------------------------------------------
int vtkWindBladeReader::RequestData(
      vtkInformation *vtkNotUsed(reqInfo),
      vtkInformationVector **vtkNotUsed(inVector),
      vtkInformationVector *outVector)
{
  // Get the information and output pointers
  vtkInformation* fieldInfo = outVector->GetInformationObject(0);
  vtkStructuredGrid *field = GetFieldOutput();

  // Set the info for this processor every time
  field->SetDimensions(this->Dimension);
  field->SetWholeExtent(this->WholeExtent);
  field->SetExtent(this->SubExtent);
  field->SetPoints(this->Points);

  // Collect the time step requested
  double* requestedTimeSteps = NULL;
  int numRequestedTimeSteps = 0;
  vtkInformationDoubleVectorKey* timeKey =
    static_cast<vtkInformationDoubleVectorKey*>
      (vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS());

  if (fieldInfo->Has(timeKey)) {
    numRequestedTimeSteps = fieldInfo->Length(timeKey);
    requestedTimeSteps = fieldInfo->Get(timeKey);
  }

  // Actual time for the time step
  double dTime = requestedTimeSteps[0];
  field->GetInformation()->Set(vtkDataObject::DATA_TIME_STEPS(), &dTime, 1);

  // Index of the time step to request
  int timeStep = 0;
  while (timeStep < this->NumberOfTimeSteps &&
         this->TimeSteps[timeStep] < dTime)
    timeStep++;

  // Open the data file for time step if needed
  if (this->RequestDataLoop == 0) {
    ostringstream fileName;
    fileName << this->RootDirectory << Slash
             << this->DataDirectory << Slash << this->DataBaseName 
             << this->TimeSteps[timeStep];
    this->FilePtr = fopen(fileName.str().c_str(), "r");
    if (this->FilePtr == NULL)
      cout << "Could not open file " << fileName.str() << endl;
    if (this->Rank == 0)
      cout << "Load file " << fileName.str() << endl;
  }

  // Some variables depend on others, so force their loading
  for (int i = 0; i < this->DivideVariables->GetNumberOfTuples(); i++)
    if (GetPointArrayStatus(this->DivideVariables->GetValue(i)))
      SetPointArrayStatus("Density", 1);

  // Examine each file variable to see if it is selected and load
  for (int var = 0; var < this->NumberOfFileVariables; var++) {
    if (this->PointDataArraySelection->GetArraySetting(var)) {

      if (this->RequestDataLoop == 0)
        LoadVariableData(var);

      field->GetPointData()->AddArray(this->data[var]);
    }
  }

  // Divide variables by Density if required
  for (int i = 0; i < this->DivideVariables->GetNumberOfTuples(); i++)
    if (GetPointArrayStatus(this->DivideVariables->GetValue(i)))
      if (this->RequestDataLoop == 0)
        DivideByDensity(this->DivideVariables->GetValue(i));

  // Calculate pressure if requested
  if (GetPointArrayStatus("Pressure")) {
    int pressure = this->PointDataArraySelection->GetArrayIndex("Pressure");
    int prespre = this->PointDataArraySelection->GetArrayIndex("Pressure-Pre");
    int tempg = this->PointDataArraySelection->GetArrayIndex("tempg");
    int density = this->PointDataArraySelection->GetArrayIndex("Density");

    if (this->RequestDataLoop == 0)
      CalculatePressure(pressure, prespre, tempg, density);

    field->GetPointData()->AddArray(this->data[pressure]);
    field->GetPointData()->AddArray(this->data[pressure + 1]);
  }

  // Calculate vorticity if requested
  if (GetPointArrayStatus("Vorticity")) {
    int vort = this->PointDataArraySelection->GetArrayIndex("Vorticity");
    int uvw = this->PointDataArraySelection->GetArrayIndex("UVW");
    int density = this->PointDataArraySelection->GetArrayIndex("Density");

    if (this->RequestDataLoop == 0)
      CalculateVorticity(vort, uvw, density);

    field->GetPointData()->AddArray(this->data[vort]);
  }

  // Load the second output
  if (this->UseTurbineFile == 1 && this->Rank == 0)
    LoadBladeData(timeStep);

  // Close file after all data is read
  if (this->RequestDataLoop == 0) {
    fclose(this->FilePtr);
    this->RequestDataLoop = 1;
  } else {
    this->RequestDataLoop = 0;
  }
  return 1;
}

//----------------------------------------------------------------------------
// Divide data variable by density for display
//----------------------------------------------------------------------------
void vtkWindBladeReader::DivideByDensity(const char* varName)
{
  int var = this->PointDataArraySelection->GetArrayIndex(varName);
  int density = this->PointDataArraySelection->GetArrayIndex("Density");

  float* varData = this->data[var]->GetPointer(0);
  float* densityData = this->data[density]->GetPointer(0);

  int numberOfTuples = this->data[var]->GetNumberOfTuples();
  int numberOfComponents = this->data[var]->GetNumberOfComponents();

  int index = 0;
  for (int i = 0; i < numberOfTuples; i++) {
    for (int j = 0; j < numberOfComponents; j++) {
      varData[index++] /= densityData[i];
    }
  }
}

//----------------------------------------------------------------------------
// Calculate pressure from tempg and density
// Calculate pressure - pre from pressure in first z position
// Requires that all data be present
//----------------------------------------------------------------------------
void vtkWindBladeReader::CalculatePressure(int pressure, int prespre,
                                           int tempg, int density)
{
  // Set the number of components and tuples for the requested data
  this->data[pressure]->SetNumberOfComponents(1);
  this->data[pressure]->SetNumberOfTuples(this->NumberOfTuples);
  float* pressureData = this->data[pressure]->GetPointer(0);

  this->data[prespre]->SetNumberOfComponents(1);
  this->data[prespre]->SetNumberOfTuples(this->NumberOfTuples);
  float* prespreData = this->data[prespre]->GetPointer(0);

  // Read tempg and Density components from file
  float* tempgData = new float[this->BlockSize];
  float* densityData = new float[this->BlockSize];
  fseek(this->FilePtr, this->VariableOffset[tempg], SEEK_SET);
  fread(tempgData, sizeof(float), this->BlockSize, this->FilePtr);
  fseek(this->FilePtr, this->VariableOffset[density], SEEK_SET);
  fread(densityData, sizeof(float), this->BlockSize, this->FilePtr);

  // Entire block of data is read so to calculate index into that data we
  // must use the entire Dimension and not the SubDimension
  int planeSize = this->Dimension[0] * this->Dimension[1];
  int rowSize = this->Dimension[0];
    
  // Pressure - pre needs the first XY plane pressure values
  float* firstPressure = new float[this->Dimension[2]];
  for (int k = 0; k < this->Dimension[2]; k++) {
    int index = k * planeSize;
    firstPressure[k] = densityData[index] * DRY_AIR_CONSTANT * tempgData[index];
  }

  // Only the requested subextents are stored on this processor
  int pos = 0;
  for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++) {
    for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++) {
      for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++) {
        int index = (k * planeSize) + (j * rowSize) + i;

        // Pressure is function of density and tempg for the same position
        // Pressure - pre is the pressure at a position minus the pressure
        // from the first value in the z plane

        pressureData[pos] = densityData[index] * 
                            DRY_AIR_CONSTANT * tempgData[index];
        prespreData[pos] = pressureData[pos] - firstPressure[k];
        pos++;
      }
    }
  }
  delete [] tempgData;
  delete [] densityData;
  delete [] firstPressure;
}

//----------------------------------------------------------------------------
// Calculate vorticity from UVW
// Requires ghost cell information so fetch all data from files for now
//----------------------------------------------------------------------------
void vtkWindBladeReader::CalculateVorticity(int vort, int uvw, int density)
{
  // Set the number of components and tuples for the requested data
  this->data[vort]->SetNumberOfComponents(1);
  this->data[vort]->SetNumberOfTuples(this->NumberOfTuples);
  float* vortData = this->data[vort]->GetPointer(0);

  // Read U and V components (two int block sizes in between)
  float* uData = new float[this->BlockSize];
  float* vData = new float[this->BlockSize];
  fseek(this->FilePtr, this->VariableOffset[uvw], SEEK_SET);
  fread(uData, sizeof(float), this->BlockSize, this->FilePtr);
  fseek(this->FilePtr, (2 * sizeof(int)), SEEK_SET);
  fread(vData, sizeof(float), this->BlockSize, this->FilePtr);

  // Read Density component
  float* densityData = new float[this->BlockSize];
  fseek(this->FilePtr, this->VariableOffset[density], SEEK_SET);
  fread(densityData, sizeof(float), this->BlockSize, this->FilePtr);

  // Divide U and V components by Density
  for (int i = 0; i < this->BlockSize; i++) {
    uData[i] /= densityData[i];
    vData[i] /= densityData[i];
  }

  // Entire block of data is read so to calculate index into that data we
  // must use the entire Dimension and not the SubDimension
  // Only the requested subextents are stored on this processor
  int planeSize = this->Dimension[0] * this->Dimension[1];
  int rowSize = this->Dimension[0];
    
  // Initialize to 0.0 because edges have no values
  int pos = 0;
  for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++)
    for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++)
      for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++)
        vortData[pos++] = 0.0;

  // For inner positions calculate vorticity
  pos = 0;
  float ddx = this->Step[0];
  float ddy = this->Step[1];

  for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++) {
    for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++) {
      for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++) {
        int index = (k * planeSize) + (j * rowSize) + i;

        // Edges are initialized to 0
        if (j == this->SubExtent[2] || j == this->SubExtent[3] ||
            i == this->SubExtent[0] || i == this->SubExtent[1]) {
              pos++;
        } else {
          // Vorticity depends on four cells surrounding this cell
          int index_vp = (k * planeSize) + (j * rowSize) + (i + 1);
          int index_vm = (k * planeSize) + (j * rowSize) + (i - 1);
          int index_up = (k * planeSize) + ((j + 1) * rowSize) + i;
          int index_um = (k * planeSize) + ((j - 1) * rowSize) + i;

          vortData[pos++] = ((vData[index_vp] - vData[index_vm]) / ddx) -
                            ((uData[index_up] - uData[index_um]) / ddy);
        }
      }
    }
  }
  delete [] uData;
  delete [] vData;
  delete [] densityData;
} 

//----------------------------------------------------------------------------
// Load one variable data array of BLOCK structure into ParaView
//----------------------------------------------------------------------------
void vtkWindBladeReader::LoadVariableData(int var)
{
  // Skip to the appropriate variable block and read byte count
  int byteCount;
  fseek(this->FilePtr, this->VariableOffset[var], SEEK_SET);

  // Set the number of components for this variable
  int numberOfComponents;
  if (this->VariableStruct[var] == SCALAR) {
    numberOfComponents = 1;
    this->data[var]->SetNumberOfComponents(numberOfComponents);
  }
  else if (this->VariableStruct[var] == VECTOR) {
    numberOfComponents = DIMENSION;
    this->data[var]->SetNumberOfComponents(numberOfComponents);
  }

  // Set the number of tuples which will allocate all tuples
  this->data[var]->SetNumberOfTuples(this->NumberOfTuples);

  // For each component of the requested variable load data
  float* block = new float[this->BlockSize];
  float* varData = this->data[var]->GetPointer(0);

  // Entire block of data is read so to calculate index into that data we
  // must use the entire Dimension and not the SubDimension
  // Only the requested subextents are stored on this processor
  int planeSize = this->Dimension[0] * this->Dimension[1];
  int rowSize = this->Dimension[0];
    
  for (int comp = 0; comp < numberOfComponents; comp++) {

    // Read the block of data
    fread(block, sizeof(float), this->BlockSize, this->FilePtr);
    
    int pos = comp;
    for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++) {
      for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++) {
        for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++) {
          int index = (k * planeSize) + (j * rowSize) + i;
          varData[pos] = block[index];
          pos += numberOfComponents;
        }
      }
    }

    // Skip closing and opening byte sizes
    fseek(this->FilePtr, (2 * sizeof(int)), SEEK_CUR);
  }
  delete [] block;
}

//----------------------------------------------------------------------------
// Load one variable data array of BLOCK structure into ParaView
//----------------------------------------------------------------------------
void vtkWindBladeReader::ReadGlobalData()
{
  ifstream inStr(this->Filename);
  if (!inStr) {
    cout << "Could not open the global .wind file " << this->Filename << endl;
  }

  string::size_type dirPos = string(this->Filename).rfind(Slash);
   if (dirPos == string::npos) {
      cout << "Bad input file name " << this->Filename << endl;
   }
  this->RootDirectory = string(this->Filename).substr(0, dirPos);

  char inBuf[LINE_SIZE];
  string keyword;
  string rest;
  string headerVersion;

  while (inStr.getline(inBuf, LINE_SIZE)) {
    if (inBuf[0] != '#' && inStr.gcount() > 1) {

      string line(inBuf);
      string::size_type keyPos = line.find(' ');
      keyword = line.substr(0, keyPos);
      rest = line.substr(keyPos + 1);
      istringstream lineStr(rest.c_str());

      // Header information
      if (keyword == "WIND_HEADER_VERSION")
        lineStr >> headerVersion;

      // Topology variables
      else if (keyword == "GRID_SIZE_X")
        lineStr >> this->Dimension[0];
      else if (keyword == "GRID_SIZE_Y")
        lineStr >> this->Dimension[1];
      else if (keyword == "GRID_SIZE_Z")
        lineStr >> this->Dimension[2];
      else if (keyword == "GRID_DELTA_X")
        lineStr >> this->Step[0];
      else if (keyword == "GRID_DELTA_Y")
        lineStr >> this->Step[1];
      else if (keyword == "GRID_DELTA_Z")
        lineStr >> this->Step[2];

      // Geometry variables
      else if (keyword == "USE_TOPOGRAPHY_FILE")
        lineStr >> this->UseTopographyFile;
      else if (keyword == "TOPOGRAPHY_FILE")
        this->TopographyFile = rest;
      else if (keyword == "COMPRESSION")
        lineStr >> this->Compression;
      else if (keyword == "FIT")
        lineStr >> this->Fit;

      // Time variables
      else if (keyword == "TIME_STEP_FIRST")
        lineStr >> this->TimeStepFirst;
      else if (keyword == "TIME_STEP_LAST")
        lineStr >> this->TimeStepLast;
      else if (keyword == "TIME_STEP_DELTA")
        lineStr >> this->TimeStepDelta;

      // Turbine variables
      else if (keyword == "USE_TURBINE_FILE")
        lineStr >> this->UseTurbineFile;
      else if (keyword == "TURBINE_DIRECTORY")
        this->TurbineDirectory = rest;
      else if (keyword == "TURBINE_TOWER")
        this->TurbineTowerName = rest;
      else if (keyword == "TURBINE_BLADE")
        this->TurbineBladeName = rest;

      // Data variables
      else if (keyword == "DATA_DIRECTORY")
        this->DataDirectory = rest;
      else if (keyword == "DATA_BASE_FILENAME")
        this->DataBaseName = rest;
      else if (keyword == "DATA_VARIABLES") {
        lineStr >> this->NumberOfFileVariables;
        ReadDataVariables(inStr);
        FindVariableOffsets();
      }
    }
  }
  if (this->TimeStepFirst < this->TimeStepLast)
    this->NumberOfTimeSteps = ((this->TimeStepLast - this->TimeStepFirst) /
                                this->TimeStepDelta) + 1;
}

//----------------------------------------------------------------------------
//
// Read the field variable information
//
//----------------------------------------------------------------------------
void vtkWindBladeReader::ReadDataVariables(ifstream& inStr)
{
  char inBuf[LINE_SIZE];
  string structType, basicType;

  // Derive Vorticity = f(UVW, Density)
  // Derive Pressure = f(tempg, Density)
  // Derive Pressure - pre = f(Pressure)
  this->NumberOfDerivedVariables = 3;
  this->NumberOfVariables = this->NumberOfFileVariables;
  int totalVariables = this->NumberOfFileVariables + 
                       this->NumberOfDerivedVariables;

  this->VariableName = new vtkStdString[totalVariables];
  this->VariableStruct = new int[totalVariables];
  this->VariableCompSize = new int[totalVariables];
  this->VariableBasicType = new int[totalVariables];
  this->VariableByteCount = new int[totalVariables];
  this->VariableOffset = new long int[totalVariables];

  bool hasUVW = false;
  bool hasDensity = false;
  bool hasTempg = false;

  for (int i = 0; i < this->NumberOfFileVariables; i++) {
    inStr.getline(inBuf, LINE_SIZE);

    // Variable name
    string varLine(inBuf);
    string::size_type lastPos = varLine.rfind('"');
    this->VariableName[i] = varLine.substr(1, lastPos-1);

    if (this->VariableName[i] == "UVW") hasUVW = true;
    if (this->VariableName[i] == "Density") hasDensity = true;
    if (this->VariableName[i] == "tempg") hasTempg = true;

    // Structure, number of components, type, number of bytes
    string rest = varLine.substr(lastPos+1);
    istringstream line(rest);

    line >> structType;
    line >> this->VariableCompSize[i];

    if (structType == "SCALAR")
      this->VariableStruct[i] = SCALAR;
    else if (structType == "VECTOR")
      this->VariableStruct[i] = VECTOR;
    else
      cout << "Error in structure type " << structType << endl;

    line >> basicType;
    line >> this->VariableByteCount[i];

    if (basicType == "FLOAT")
      this->VariableBasicType[i] = FLOAT;
    else if (basicType == "INTEGER")
      this->VariableBasicType[i] = INTEGER;
    else
      cout << "Error in basic type " << basicType << endl;
  }

  // Add any derived variables
  if (hasUVW && hasDensity) {
    this->VariableName[this->NumberOfVariables] = "Vorticity";
    this->NumberOfVariables++;
  }
  if (hasTempg && hasDensity) {
    this->VariableName[this->NumberOfVariables] = "Pressure";
    this->NumberOfVariables++;
    this->VariableName[this->NumberOfVariables] = "Pressure-Pre";
    this->NumberOfVariables++;
  }
}

//----------------------------------------------------------------------------
//
// Open the first data file and verify that the data is where is should be
// Each data block is enclosed by two ints which record the number of bytes
// Save the file offset for each varible
//
//----------------------------------------------------------------------------
void vtkWindBladeReader::FindVariableOffsets()
{
  // Open the first data file
  ostringstream fileName; 
  cout << "DataDirectory: " << this->DataDirectory << endl;
  cout << "DataBaseName: " << this->DataBaseName << endl;
  fileName << this->RootDirectory << Slash
           << this->DataDirectory << Slash 
           << this->DataBaseName << this->TimeStepFirst;
  this->FilePtr = fopen(fileName.str().c_str(), "r");
  if (this->FilePtr == NULL) {
    cout << "Could not open file " << fileName.str() << endl;
    exit(1);
  }

  // Scan file recording offsets which points to the first data value
  int byteCount;
  fread(&byteCount, sizeof(int), 1, this->FilePtr);
  this->BlockSize = byteCount / BYTES_PER_DATA;

  for (int var = 0; var < this->NumberOfFileVariables; var++) {
    this->VariableOffset[var] = ftell(this->FilePtr);

    // Skip over the SCALAR or VECTOR components for this variable
    int numberOfComponents = 1;
    if (this->VariableStruct[var] == VECTOR)
      numberOfComponents = DIMENSION;

    for (int comp = 0; comp < numberOfComponents; comp++) {
      // Skip data plus two integer byte counts
      fseek(this->FilePtr, (byteCount+(2 * sizeof(int))), SEEK_CUR);
    }
  }
  fclose(this->FilePtr);
}

//----------------------------------------------------------------------------
// Calculate the Points for flat Rectilinear type grid or topographic
// generalized StructuredGrid which is what is being created here
//----------------------------------------------------------------------------
void vtkWindBladeReader::CreateCoordinates()
{
  vtkFloatArray* xSpacing = vtkFloatArray::New();
  vtkFloatArray* ySpacing = vtkFloatArray::New();
  vtkFloatArray* zSpacing = vtkFloatArray::New();

  // If dataset is flat, x and y are constant spacing, z is stretched
  if (this->UseTopographyFile == 0) {
    float value = 0.0;
    for (int i = 0; i < this->Dimension[0]; i++) {
      xSpacing->InsertNextValue(value);
      value += this->Step[0];
    }

    value = 0.0;
    for (int j = 0; j < this->Dimension[1]; j++) {
      ySpacing->InsertNextValue(value);
      value += this->Step[1];
    }
  
    double maxZ = this->Step[2] * this->Dimension[2];
    for (int k = 0; k < this->Dimension[2]; k++) {
      double zcoord = (k * this->Step[2]) + (0.5 * this->Step[2]);
      double zcartesian = GDeform(zcoord, maxZ, 0);
      zSpacing->InsertNextValue(zcartesian);
    }

    // Save vtkPoints instead of spacing coordinates because topography file
    // requires this to be vtkStructuredGrid and not vtkRectilinearGrid
    for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++) {
      float z = zSpacing->GetValue(k);
      for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++) {
        float y = ySpacing->GetValue(j);
        for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++) {
          float x = xSpacing->GetValue(i);
          this->Points->InsertNextPoint(x, y, z);
        }
      }
    }
  }

  // If dataset is topographic, x and y are constant spacing center on (0,0)
  // Z data is calculated from an x by y topographic data file
  else {
    float xHalf = (((this->Dimension[0] + 1.0) / 2.0) - 1.0) * this->Step[0];
    for (int i = 0; i < this->Dimension[0]; i++)
      xSpacing->InsertNextValue((i * this->Step[0]) - xHalf);

    float yHalf = (((this->Dimension[1] + 1.0) / 2.0) - 1.0) * this->Step[1];
    for (int j = 0; j < this->Dimension[1]; j++)
      ySpacing->InsertNextValue((j * this->Step[1]) - yHalf);

    float* zValues = new float[this->BlockSize];
    CreateZTopography(zValues);

    int planeSize = this->Dimension[0] * this->Dimension[1];
    int rowSize = this->Dimension[0];

    for (int k = this->SubExtent[4]; k <= this->SubExtent[5]; k++) {
      for (int j = this->SubExtent[2]; j <= this->SubExtent[3]; j++) {
        float y = ySpacing->GetValue(j);
        for (int i = this->SubExtent[0]; i <= this->SubExtent[1]; i++) {
          float x = xSpacing->GetValue(i);
          int index = (k * planeSize) + (j * rowSize) + i;
          this->Points->InsertNextPoint(x, y, zValues[index]);
        }
      }
    }
    delete [] zValues;
  }
  xSpacing->Delete();
  ySpacing->Delete();
  zSpacing->Delete();
}

//----------------------------------------------------------------------------
// Create the z topography from 2D (x,y) elevations and return in zData
//----------------------------------------------------------------------------
void vtkWindBladeReader::CreateZTopography(float* zValues)
{
  // Read the x,y topography data file
  FILE* filePtr = fopen(this->TopographyFile.c_str(), "r");
  int blockSize = this->Dimension[0] * this->Dimension[1];
  float* topoData = new float[blockSize];

  fseek(filePtr, BYTES_PER_DATA, SEEK_SET);  // Fortran byte count
  fread(topoData, sizeof(float), blockSize, filePtr);

  // Initial z coordinate processing
  float* zedge = new float[this->Dimension[2] + 1];
  float* z = new float[this->Dimension[2]];
  float zb;
  int ibctopbot = 1;

  if (ibctopbot == 1) {
    for (int k = 0; k <= this->Dimension[2]; k++)
      zedge[k] = k * this->Step[2];
    zb = zedge[this->Dimension[2]];
    for (int k = 0; k < this->Dimension[2]; k++)
      z[k] = k * this->Step[2] + 0.5 * this->Step[2];
  }

  else {
    for (int k = 0; k < this->Dimension[2]; k++)
      z[k] = k * this->Step[2];
    zb = z[this->Dimension[2] - 1];
  }

  // Use cubic spline or deformation to calculate z values
  int npoints = 31;
  float* zdata = new float[npoints];
  float* zcoeff = new float[npoints];
  float zcrdata[] = {
        0.0 ,    2.00,    4.00,     6.00,      8.00,
       10.00,   14.00,   18.00,    22.00,     26.00,
       30.00,   34.00,   40.00,    50.00,     70.00,
      100.00,  130.00,  160.00,   200.00,    250.00,
      300.00,  350.00,  450.00,   550.00,    750.00,
      950.00, 1150.00, 1400.00,  1700.00,   2000.00,   2400.00 };

  // No deformation, use spline to define z coefficients
  if (this->Compression == 0.0) {
    for (int i = 0; i < npoints; i++)
      zdata[i] = (z[i] * zb) / z[npoints - 1];

    // Call spline with zcoeff being the answer
    spline(zdata, zcrdata, npoints, 99.0e31, 99.0e31, zcoeff);
  }

  // Fill the zValues array depending on compression
  int planeSize = this->Dimension[0] * this->Dimension[1];
  int rowSize = this->Dimension[0];
  int flag = 0;

  for (int k = 0; k < this->Dimension[2]; k++) {
    for (int j = 0; j < this->Dimension[1]; j++) {
      for (int i = 0; i < this->Dimension[0]; i++) {
        int index = (k * planeSize) + (j * rowSize) + i;
        int tIndex = (j * rowSize) + i;

        if (this->Compression == 0.0) {
          // Use spline interpolation
          float zinterp;
          splint(zdata, zcrdata, zcoeff, npoints, z[k], &zinterp, flag);
          zValues[index] = zinterp;
        } else {
          // Use deformation
          zValues[index] = GDeform(z[k], zb, flag) * 
                                (zb - topoData[tIndex]) / zb + topoData[tIndex];
        }
      }
    }
  }

  delete [] topoData;
  delete [] zedge;
  delete [] z;
  delete [] zdata;
  delete [] zcoeff;
}

//----------------------------------------------------------------------------
//
// Stretch the Z coordinate for flat topography
// If flag = 0 compute gdeform(z)
// If flag = 1 compute derivative of gdeform(z)
// Return cubic polynomial fit
//
//----------------------------------------------------------------------------
float vtkWindBladeReader::GDeform(float sigma, float sigmaMax, int flag)
{
  float sigma_2 = sigma * sigma;
  float sigma_3 = sigma_2 * sigma;

  float f = this->Fit;
  float aa1 = this->Compression;

  float aa2 = (f * (1.0 - aa1)) / sigmaMax;
  float aa3 = (1.0 - (aa2 * sigmaMax) - aa1) / (sigmaMax * sigmaMax);

  float zcoord;
  if (flag == 0)
    zcoord = (aa3 * sigma_3) + (aa2 * sigma_2) + (aa1 * sigma);
  else if (flag == 1)
    zcoord = (3.0 * aa3 * sigma_2) + (2.0 * aa2 * sigma) + aa1;

  return zcoord;
}

//----------------------------------------------------------------------------
// Cubic spline from Numerical Recipes (altered for zero based arrays)
// Called only once to process entire tabulated function
//
// Given arrays x[0..n-1] and y[0..n-1] containing a tabulated function
// with x0 < x1 < .. < xn-1, and given values yp1 and ypn for the
// first derivative of the interpolating function at points 0 and n-1,
// this routine returns an array y2[0..n-1] that contains the second
// derivatives of the interpolating function.  If yp1 or ypn > e30
// the rougine is signaled to set the corresponding boundary condition
// for a natural spline, with zero second derivative on that boundary.
//----------------------------------------------------------------------------
void vtkWindBladeReader::spline(
      float* x, float* y,  // arrays
      int n,      // size of arrays
      float yp1, float ypn,  // boundary condition
      float* y2)    // return array
{
  float p, qn, sig, un;
  float* u = new float[n];

  // Lower boundary condition set to natural spline
  if (yp1 > 0.99e30)
    y2[0] = u[0] = 0.0;

  // Lower boundary condition set to specified first derivative
  else {
    y2[0] = -0.5;
    u[0]=(3.0/(x[1]-x[0]))*((y[1]-y[0])/(x[1]-x[0])-yp1);
  }

  // Decomposition loop of tridiagonal algorithm
  for (int i = 1; i < n-1; i++) {
    float sig = (x[i] - x[i-1]) / (x[i+1] - x[i-1]);
    float p = sig * y2[i-1] + 2.0;
    y2[i] = (sig - 1.0) / p;
    u[i] = (y[i+1] - y[i]) / (x[i+1] - x[i]) - 
           (y[i] - y[i-1]) / (x[i] - x[i-1]);
    u[i] = (6.0 * u[i] / (x[i+1] - x[i-1]) - sig * u[i-1]) / p;
  }

  // Upper boundary condition set to natural spline
  if (ypn > 0.99e30)
    qn = un = 0.0;

  // Upper boundary condition set to specified first derivative
  else {  
    qn = 0.5;
    un = (3.0 / (x[n-1] - x[n-2])) * 
         (ypn - (y[n-1] - y[n-2]) / (x[n-1] -x [n-2]));
  }

  // Back substitution loop of tridiagonal algorithm
  y2[n-1] = (un - qn * u[n-2]) / (qn * y2[n-2] + 1.0);
  for (int k = n - 2; k >= 0; k--)
    y2[k] = y2[k] * y2[k+1] + u[k];

  delete [] u;
}

//----------------------------------------------------------------------------
// Cubic spline interpolation from Numerical Recipes
// Called succeeding times after spline is called once
// Given x, y and y2 arrays from spline return cubic spline interpolated
//----------------------------------------------------------------------------
void vtkWindBladeReader::splint(
      float* xa, float* ya,   // arrays sent to spline()
      float* y2a,     // result from spline()
      int n,      // size of arrays
      float x,    // 
      float* y,    // interpolated value
      int kderivative)
{
  // Find the right place in the table by means of bisection
  // Optimal is sequential calls are at random values of x
  int klo = 0;
  int khi = n - 1;
  while (khi - klo > 1) {
    int k = (khi + klo) / 2;
    if (xa[k] > x)
      khi = k;
    else
      klo = k;
  }

  float h = xa[khi] - xa[klo];
  float a = (xa[khi] - x) / h;
  float b = (x - xa[klo]) / h;
  if (kderivative == 0)
    *y = a * ya[klo] + b * ya[khi] + 
         ((a * a * a - a) * y2a[klo] +
         (b * b * b - b) * y2a[khi]) * (h * h) / 6.0;
  else
    *y = ((ya[khi] - ya[klo]) / h) -
         ((((((3.0 * a * a) - 1.0) * y2a[klo]) -
            (((3.0 * b * b) - 1.0) * y2a[khi])) * h) / 6.0);
}

//----------------------------------------------------------------------------
// Build the turbine towers
// Parse a blade file to set the number of cells and points in blades
//----------------------------------------------------------------------------
void vtkWindBladeReader::SetupBladeData()
{
  // Load the tower information
  ostringstream fileName;
  cout << "TurbineDirectory: " << this->TurbineDirectory << endl;
  cout << "TurbineTowerName: " << this->TurbineTowerName << endl;
  fileName << this->RootDirectory << Slash 
           << this->TurbineDirectory << Slash 
           << this->TurbineTowerName; 
  ifstream inStr(fileName.str().c_str());
  if (!inStr)
    cout << "Could not open " << fileName << endl;

  // File is ASCII text so read until EOF
  char inBuf[LINE_SIZE];
  float hubHeight, bladeLength, maxRPM, xPos, yPos, yawAngle;
  float angularVelocity, angleBlade1;
  int numberOfBlades;
  int towerID;

  while (inStr.getline(inBuf, LINE_SIZE)) {

    istringstream line(inBuf);
    line >> towerID >> hubHeight >> bladeLength >> numberOfBlades >> maxRPM;
    line >> xPos >> yPos;
    line >> yawAngle >> angularVelocity >> angleBlade1;

    this->XPosition->InsertNextValue(xPos);
    this->YPosition->InsertNextValue(yPos);
    this->HubHeight->InsertNextValue(hubHeight);
    this->BladeCount->InsertNextValue(numberOfBlades);
  }
  this->NumberOfBladeTowers = XPosition->GetNumberOfTuples();
  inStr.close();

  // Calculate the number of cells in unstructured turbine blades
  ostringstream fileName2;
  cout << "TurbineDirectory: " << this->TurbineDirectory << endl;
  cout << "TurbineBladeName: " << this->TurbineBladeName << endl;
  fileName2 << this->RootDirectory << Slash
            << this->TurbineDirectory << Slash
            << this->TurbineBladeName << this->TimeStepFirst;
  ifstream inStr2(fileName2.str().c_str());
  if (!inStr2)
    cout << "Could not open " << fileName2 << endl;

  this->NumberOfBladeCells = 0;
  while (inStr2.getline(inBuf, LINE_SIZE))
    this-NumberOfBladeCells++;
  inStr2.close();
  this->NumberOfBladePoints = this->NumberOfBladeCells * NUM_PART_SIDES;

  // Points and cells needed for constant towers
  this->NumberOfBladePoints += this->NumberOfBladeTowers * NUM_BASE_SIDES;
  this->NumberOfBladeCells += this->NumberOfBladeTowers;
}

//----------------------------------------------------------------------------
// Build the turbine blades
//----------------------------------------------------------------------------
void vtkWindBladeReader::LoadBladeData(int timeStep)
{
  // Open the file for this time step
  ostringstream fileName;
  fileName << this->TurbineDirectory << Slash << this->TurbineBladeName 
           << this->TimeSteps[timeStep];
  ifstream inStr(fileName.str().c_str());
  char inBuf[LINE_SIZE];

  // Allocate space for points and cells
  this->BPoints->Allocate(this->NumberOfBladePoints, this->NumberOfBladePoints);
  vtkUnstructuredGrid* blade = GetBladeOutput();
  blade->Allocate(this->NumberOfBladeCells, this->NumberOfBladeCells);
  blade->SetPoints(this->BPoints);

  // Allocate space for data
  vtkFloatArray* axialForce = vtkFloatArray::New();
  axialForce->SetName("Axial Force");
  axialForce->SetNumberOfTuples(this->NumberOfBladeCells);
  axialForce->SetNumberOfComponents(1);
  blade->GetCellData()->AddArray(axialForce);
  float* aBlock = axialForce->GetPointer(0);
  
  vtkFloatArray* radialForce = vtkFloatArray::New();
  radialForce->SetName("Radial Force"); 
  radialForce->SetNumberOfTuples(this->NumberOfBladeCells);
  radialForce->SetNumberOfComponents(1);
  blade->GetCellData()->AddArray(radialForce);
  float* rBlock = radialForce->GetPointer(0);

  vtkFloatArray* test = vtkFloatArray::New();
  test->SetName("Test"); 
  test->SetNumberOfTuples(this->NumberOfBladeCells);
  test->SetNumberOfComponents(1);
  blade->GetCellData()->AddArray(test);
  float* tBlock = test->GetPointer(0);
    
  // File is ASCII text so read until EOF
  int index = 0;
  int indx = 0;
  int firstPoint;
  int turbineID, bladeID, partID;
  float x, y, z;
  vtkIdType cell[NUM_BASE_SIDES];

  while (inStr.getline(inBuf, LINE_SIZE)) {

    istringstream line(inBuf);
    line >> turbineID >> bladeID >> partID;
  
    firstPoint = index;
    for (int side = 0; side < NUM_PART_SIDES; side++) {
      line >> x >> y >> z;
      this->BPoints->InsertNextPoint(x, y, z);
    }

    // Polygon points are leading edge then trailing edge so points are 0-1-3-2
    cell[0] = firstPoint;
    cell[1] = firstPoint + 1;
    cell[2] = firstPoint + 3;
    cell[3] = firstPoint + 2;
    index += NUM_PART_SIDES; 
    blade->InsertNextCell(VTK_POLYGON, NUM_PART_SIDES, cell);
  
    line >> aBlock[indx] >> rBlock[indx];
    tBlock[indx] = turbineID * bladeID;
    indx++;
  }
  
  // Add the towers to the geometry
  for (int i = 0; i < this->NumberOfBladeTowers; i++) {
    x = this->XPosition->GetValue(i);
    y = this->YPosition->GetValue(i);
    z = this->HubHeight->GetValue(i);

    this->BPoints->InsertNextPoint(x-2, y-2, 0.0);
    this->BPoints->InsertNextPoint(x+2, y-2, 0.0);
    this->BPoints->InsertNextPoint(x+2, y+2, 0.0);
    this->BPoints->InsertNextPoint(x-2, y+2, 0.0);
    this->BPoints->InsertNextPoint(x, y, z);
    firstPoint = index;
    cell[0] = firstPoint;
    cell[1] = firstPoint + 1;
    cell[2] = firstPoint + 2;
    cell[3] = firstPoint + 3;
    cell[4] = firstPoint + 4;
    index += NUM_BASE_SIDES;
    blade->InsertNextCell(VTK_PYRAMID, NUM_BASE_SIDES, cell);

    aBlock[indx] = 0.0;
    rBlock[indx] = 0.0;
    tBlock[indx] = 0.0;
    indx++;
  }
  axialForce->Delete();
  radialForce->Delete();
  test->Delete();
}

//----------------------------------------------------------------------------
void vtkWindBladeReader::SelectionCallback(
  vtkObject*, unsigned long eventid, void* clientdata, void* calldata)
{
  static_cast<vtkWindBladeReader*>(clientdata)->Modified();
}

//----------------------------------------------------------------------------
vtkStructuredGrid* vtkWindBladeReader::GetFieldOutput()
{
  return vtkStructuredGrid::SafeDownCast(
    this->GetExecutive()->GetOutputData(0));
}

//----------------------------------------------------------------------------
int vtkWindBladeReader::GetNumberOfPointArrays()
{
  return this->PointDataArraySelection->GetNumberOfArrays();
}

//----------------------------------------------------------------------------
void vtkWindBladeReader::EnableAllPointArrays()
{
    this->PointDataArraySelection->EnableAllArrays();
}

//----------------------------------------------------------------------------
void vtkWindBladeReader::DisableAllPointArrays()
{
    this->PointDataArraySelection->DisableAllArrays();
}

//----------------------------------------------------------------------------
const char* vtkWindBladeReader::GetPointArrayName(int index)
{
  return this->VariableName[index].c_str();
}

//----------------------------------------------------------------------------
int vtkWindBladeReader::GetPointArrayStatus(const char* name)
{
  return this->PointDataArraySelection->ArrayIsEnabled(name);
}

//----------------------------------------------------------------------------
void vtkWindBladeReader::SetPointArrayStatus(const char* name, int status)
{
  if (status)
    this->PointDataArraySelection->EnableArray(name);
  else
    this->PointDataArraySelection->DisableArray(name);
}

vtkUnstructuredGrid *vtkWindBladeReader::GetBladeOutput()
{
  if (this->GetNumberOfOutputPorts() < 2)
    {
    return NULL;
    }
  return vtkUnstructuredGrid::SafeDownCast(
    this->GetExecutive()->GetOutputData(1));
}

//----------------------------------------------------------------------------
int vtkWindBladeReader::FillOutputPortInformation(int port,
                                                  vtkInformation* info)
{
  if(port == 0)
    {
    return this->Superclass::FillOutputPortInformation(port, info);
    }
  info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid");
  return 1;
}