WSL/SLF GitLab Repository

A3DIO.cc 32.7 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
/***********************************************************************************/
/*  Copyright 2009 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <meteoio/A3DIO.h>

using namespace std;

namespace mio {
/**
 * @page a3d A3D
 * @section a3d_format Format
 * This plugin reads legacy Alpine3D meteorological input files. It reads the meteo1d.txt file that contains, as measured at one unique location, the following fields:
 * - air temperature in field ta
 * - incoming short wave radiation in field iswr
 * - wind velocity in field vw
 * - relative humidity in field rh
 * - incoming long wave radiation in field ea
 * - precipitations in field nswc
 *
 * and optionally a list of stations with their measurements (meteo2d files) for the following parameters (with YYYY being the 4-digits year):
 * - precipitations (file named precYYYY.txt)
 * - relative humidity (file named rhumYYYY.txt)
 * - air temperature (file named tairYYYY.txt)
 * - wind speed (file named wspdYYYY.txt)
 * - and optionnally wind direction (file named wdirYYYY.txt)
 *
 * @section a3d_units Units
 * The units are assumed to be the following:
 * - temperatures in celsius
 * - relative humidity in %
 * - wind speed in m/s
 * - precipitations in mm/h
 * - radiation in W/m²
 *
 * @section a3d_keywords Keywords
 * This plugin uses the following keywords:
 * - METEOPATH: string containing the path to the meteorological files (ie: where to find meteo1d.txt and meteo2d files)
 * - COORDSYS: input coordinate system (see Coords) specified in the [Input] section
 * - COORDPARAM: extra input coordinates parameters (see Coords) specified in the [Input] section
 * - COORDSYS: output coordinate system (see Coords) specified in the [Output] section
 * - COORDPARAM: extra output coordinates parameters (see Coords) specified in the [Output] section
 * - SPECIALPTSFILE: a path+file name to the a file containing grid coordinates of special points of interest (for special outputs)
 */

const double A3DIO::plugin_nodata = -9999.0; //plugin specific nodata value
60
const unsigned int A3DIO::buffer_reserve = 23*24*2; //kind of average size of a buffer for optimizing vectors
61
62
63
64
65
66
67
68
69
70
71
72
73

//Main constructor
A3DIO::A3DIO(const std::string& configfile) : IOInterface(NULL), cfg(configfile)
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

//Copy constructor
A3DIO::A3DIO(const A3DIO& aio) : IOInterface(NULL), cfg(aio.cfg)
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

74
A3DIO::A3DIO(const Config& cfgreader) : IOInterface(NULL), cfg(cfgreader)
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
{
	IOUtils::getProjectionParameters(cfg, coordin, coordinparam, coordout, coordoutparam);
}

A3DIO::~A3DIO() throw()
{
	cleanup();
}

void A3DIO::cleanup() throw()
{
	if (fin.is_open()) {//close fin if open
		fin.close();
	}
}

void A3DIO::read2DGrid(Grid2DObject&, const std::string&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void A3DIO::readDEM(DEMObject& dem_out)
{
	//Nothing so far
	(void)dem_out;
	throw IOException("Nothing implemented here", AT);
}

void A3DIO::readLanduse(Grid2DObject& landuse_out)
{
	//Nothing so far
	(void)landuse_out;
	throw IOException("Nothing implemented here", AT);
}

void A3DIO::readAssimilationData(const Date& date_in, Grid2DObject& da_out)
{
	//Nothing so far
	(void)date_in;
	(void)da_out;
	throw IOException("Nothing implemented here", AT);
}

void A3DIO::write2DGrid(const Grid2DObject&, const std::string&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void A3DIO::writeMeteoData(const std::vector< std::vector<MeteoData> >& data,
					  const std::vector< std::vector<StationData> >&vec_stations,
					  const std::string&)
{
	if(vec_stations.size()>0) {
		//A3D format does not support stations changing position over time
		create1DFile(data, vec_stations);
		write2DMeteo(data, vec_stations);
	}
}

136
void A3DIO::readStationData(const Date& timestamp, std::vector<StationData>& vecStation)
137
138
{
	//Nothing so far
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
	//throw IOException("Nothing implemented here", AT);
	vecStation.clear();

	//read 1D station and put it into vecStation
	std::string file_1d;
	cfg.getValue("METEOPATH", "Input", file_1d);
	file_1d += "/meteo1d.txt";

	if (!IOUtils::fileExists(file_1d)) {
		throw FileNotFoundException(file_1d, AT);
	}

	fin.clear();
	fin.open (file_1d.c_str(), std::ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(file_1d,AT);
	}

	StationData sd;
	read1DStation(file_1d, sd);
	vecStation.push_back(sd);
	cleanup();

	//read 2D stations and add them to vecStation
	std::vector<StationData> tmpvecS;
	read2DStations(timestamp, tmpvecS);
	cleanup();

	for(unsigned int i=0; i<tmpvecS.size(); i++) {
		vecStation.push_back(tmpvecS[i]);
	}
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
}

void A3DIO::readMeteoData(const Date& dateStart, const Date& dateEnd, std::vector< std::vector<MeteoData> >& vecMeteo)
{
	std::vector< std::vector<StationData> > vecStation;
	readMeteoData(dateStart, dateEnd, vecMeteo, vecStation);
}

void A3DIO::readMeteoData(const Date& dateStart, const Date& dateEnd,
					 std::vector< std::vector<MeteoData> >& vecMeteo,
					 std::vector< std::vector<StationData> >& vecStation,
					 const unsigned int& stationindex)
{
	//if dateStart and dateEnd are the same: return exact match for date
	//if dateStart > dateEnd: return first data set with date > dateStart
	//read in all data starting with dateStart until dateEnd
	//if there is no data at all then the vector will be empty, no exception will be thrown
	(void)stationindex;
	vecMeteo.clear();
	vecStation.clear();

	//first from meteo1d.txt
	read1DMeteo(dateStart, dateEnd, vecMeteo, vecStation);

	//then all corresponding data sets from the 2d meteo files
	//note: they have to be entirely corresponding (for every date)
	try {
		read2DMeteo(vecMeteo, vecStation);
	} catch(std::exception& e){
		std::cerr << "[E] No meteo2d data found or error while reading it, using only Meteo1D data: "
200
		          << std::endl << "\t" << e.what() << std::endl;
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
	}
}

void A3DIO::convertUnits(MeteoData& meteo)
{
	meteo.standardizeNodata(plugin_nodata);

	//converts C to Kelvin, converts RH to [0,1]
	if(meteo.ta!=IOUtils::nodata) {
		meteo.ta=C_TO_K(meteo.ta);
	}
	if(meteo.tsg!=IOUtils::nodata) {
		meteo.tsg=C_TO_K(meteo.tsg);
	}
	if(meteo.rh!=IOUtils::nodata) {
		meteo.rh /= 100.;
	}
}

220
void A3DIO::read1DStation(std::string& file_1d, StationData& sd)
221
222
{
	double latitude=IOUtils::nodata, longitude=IOUtils::nodata,
223
	       xcoord=IOUtils::nodata, ycoord=IOUtils::nodata, altitude=IOUtils::nodata;
224
	std::map<std::string, std::string> header; // A map to save key value pairs of the file header
225
226
	
	//read and parse the header
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
	try {
		//Read in station meta data
		IOUtils::readKeyValueHeader(header, fin, 5, "="); //Read in 5 lines as header
		IOUtils::getValueForKey(header, "Latitude", latitude);
		IOUtils::getValueForKey(header, "Longitude", longitude);
		IOUtils::getValueForKey(header, "X_Coord", xcoord);
		IOUtils::getValueForKey(header, "Y_Coord", ycoord);
		IOUtils::getValueForKey(header, "Altitude", altitude);

		//HACK!! would it be possible for getValueForKey() to do this transparently? (with a user flag)
		latitude = IOUtils::standardizeNodata(latitude, plugin_nodata);
		longitude = IOUtils::standardizeNodata(longitude, plugin_nodata);
		altitude = IOUtils::standardizeNodata(altitude, plugin_nodata);
		xcoord = IOUtils::standardizeNodata(xcoord, plugin_nodata);
		ycoord = IOUtils::standardizeNodata(ycoord, plugin_nodata);

		//compute/check WGS coordinates (considered as the true reference) according to the projection as defined in cfg
		Coords location(coordin, coordinparam);
		location.setXY(xcoord, ycoord, altitude, false);
		location.setLatLon(latitude, longitude, altitude, false);
		try {
			location.check();
		} catch(...) {
250
			std::cerr << "[E] Error in geographic coordinates in file " << file_1d << " trapped at " << AT << std::endl;
251
252
253
			throw;
		}

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
		sd.setStationData(location, "meteo1d", "Meteo1D station");
	} catch(...) {
		std::cout << "[E] " << AT << ": "<< std::endl;
		cleanup();
		throw;
	}
}

void A3DIO::read1DMeteo(const Date& dateStart, const Date& dateEnd,
				std::vector< std::vector<MeteoData> >& vecMeteo,
				std::vector< std::vector<StationData> >& vecStation)
{
	std::string file_1d="", line="";
	Date tmp_date;
	
	MeteoData tmpdata;
	StationData sd;
	bool eofreached = false;

	cfg.getValue("METEOPATH", "Input", file_1d);
	file_1d += "/meteo1d.txt";

	if (!IOUtils::fileExists(file_1d)) {
		throw FileNotFoundException(file_1d, AT);
	}

	fin.clear();
	fin.open (file_1d.c_str(), std::ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(file_1d,AT);
	}

	char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

	//get station metadata
	read1DStation(file_1d, sd);
290

291
292
	//Go through file, save key value pairs
	try {
293
294
295
296
297
298
		//Read one line, construct Date object and see whether date is greater or equal than the date_in object
		IOUtils::skipLines(fin, 1, eoln); //skip rest of line

		//Loop going through the data sequentially until dateStart is found
		do {
			getline(fin, line, eoln); //read complete line
299
			eofreached = readMeteoDataLine(line, tmpdata, file_1d);
300
301
302
303
304
305
306
307
308
309
310
311
312
			//tmpdata.cleanData();
			convertUnits(tmpdata);

		} while((tmpdata.date < dateStart) && (!eofreached));

		if ((dateEnd < dateStart) && (!eofreached)){ //Special case
			vecMeteo.push_back( std::vector<MeteoData>() );
			vecStation.push_back( std::vector<StationData>() );
			vecMeteo[0].push_back(tmpdata);
			vecStation[0].push_back(sd);
		} else if ((tmpdata.date <= dateEnd)  && (!eofreached)) {
			vecMeteo.push_back( std::vector<MeteoData>() );
			vecStation.push_back( std::vector<StationData>() );
313
314
			vecMeteo[0].reserve(buffer_reserve);
			vecStation[0].reserve(buffer_reserve);
315
316
317
318
319
320
321
322
		}

		while ((tmpdata.date <= dateEnd)  && (!eofreached)) {
			//At this point tmpdata.date is >= dateStart
			vecMeteo[0].push_back(tmpdata);
			vecStation[0].push_back(sd);

			getline(fin, line, eoln); //read complete line
323
			eofreached = readMeteoDataLine(line, tmpdata, file_1d);
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
			//tmpdata.cleanData();
			convertUnits(tmpdata);
		}
		//cout << "Size of buffer: " << vecMeteo[0].size() << "   " << tmp_date << endl;
	} catch(...) {
		std::cout << "[E] " << AT << ": "<< std::endl;
		cleanup();
		throw;
	}

	cleanup();
}

bool A3DIO::readMeteoDataLine(std::string& line, MeteoData& tmpdata, std::string filename)
{
	Date tmp_date;
	int tmp_ymdh[4];
	std::vector<std::string> tmpvec;
342
	tmpvec.reserve(6);
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
	double tmp_values[6];

	if (IOUtils::readLineToVec(line, tmpvec) != 10) {
		return true;
		//throw InvalidFormatException("Premature End of Line or no data for date " + date_in + " found in File " + filename, AT);
	}

	for (int ii=0; ii<4; ii++) {
		if (!IOUtils::convertString(tmp_ymdh[ii], tmpvec.at(ii), std::dec))
			throw InvalidFormatException(filename + ": " + line, AT);
	}

	tmp_date.setDate(tmp_ymdh[0],tmp_ymdh[1],tmp_ymdh[2],tmp_ymdh[3], 0);

	//Read rest of line with values ta, iswr, vw, rh, ea, hnw

	for (int ii=0; ii<6; ii++) { //go through the columns
		if (!IOUtils::convertString(tmp_values[ii], tmpvec.at(ii+4), std::dec)) {
			throw InvalidFormatException(filename + ": " + line, AT);
		}
	}

	tmpdata.setDate(tmp_date);
	tmpdata.setData(MeteoData::TA, tmp_values[0]);
	tmpdata.setData(MeteoData::ISWR, tmp_values[1]);
	tmpdata.setData(MeteoData::VW, tmp_values[2]);
	tmpdata.setData(MeteoData::RH, tmp_values[3]);
	tmpdata.setData(MeteoData::ILWR, tmp_values[4]);
	tmpdata.setData(MeteoData::HNW, tmp_values[5]);

	return false;
}


377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
void A3DIO::read2DStations(const Date& timestamp, std::vector<StationData>& vecStation)
{
	unsigned int stations=0;
	std::vector<std::string> filenames = std::vector<std::string>();
	std::map<std::string, unsigned int> hashStations = std::map<std::string, unsigned int>();
	
	constructMeteo2DFilenames(timestamp, timestamp, filenames);
	stations = getNrOfStations(filenames, hashStations);
	vecStation.resize(stations); //we receive an empty vector, so we need to allocate the room it needs

	try {
		for (unsigned int ii=0; ii<filenames.size(); ii++){
			read2DMeteoHeader(filenames[ii], hashStations, vecStation);
		}
	} catch(...) {
		//clear all 2D meteo data if error occurs
		if (vecStation.size() > 1)
			vecStation.erase(vecStation.begin()+1, vecStation.end());
		cleanup();
		throw;
	}
}

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
/*
  Preamble: Files are in METEOFILE directory. 4 types of files:
  prec????.txt == hnw
  rh????.txt == rh
  ta????.txt == ta
  wspd????.txt == vw

  Remarks: The headers of the files may defer - for each unique
  StationData one MeteoData and one StationData object will be created
*/
 void A3DIO::read2DMeteo(std::vector< std::vector<MeteoData> >& vecMeteo, std::vector< std::vector<StationData> >& vecStation)
{

	unsigned int stations=0, bufferindex=0;
	std::map<std::string, unsigned int> hashStations = std::map<std::string, unsigned int>();
	std::vector<std::string> filenames = std::vector<std::string>();

	//Requirement: meteo1D data must exist:
	if ((vecMeteo.size() == 0) || (vecMeteo[0].size() == 0))
		return;

	//1D and 2D data must correspond, that means that if there is 1D data
	//for a certain date (e.g. 1.1.2006) then 2D data must exist (prec2006.txt etc),
	//otherwise throw FileNotFoundException
	Date startDate(vecMeteo[0][0].date);
	Date endDate(vecMeteo[0][vecMeteo[0].size()-1].date);

	constructMeteo2DFilenames(startDate, endDate, filenames);//get all files for all years
	stations = getNrOfStations(filenames, hashStations);

	constructMeteo2DFilenames(startDate, startDate, filenames);//get filenames for current year
	std::cerr << "[I] Number of 2D meteo stations: " << stations << std::endl;

	if (stations < 1) {
		throw InvalidFormatException("[E] No StationData found in 2D Meteo Files", AT);
	}

	std::vector<StationData> tmpvecS = std::vector<StationData>(stations); //stores unique stations

	try {
		for (unsigned int ii=0; ii<filenames.size(); ii++){
			read2DMeteoHeader(filenames[ii], hashStations, tmpvecS);
		}

		//init vecStation with proper StationData, vecMeteo with nodata
		for (unsigned int jj=0; jj<tmpvecS.size(); jj++){
			vecMeteo.push_back( std::vector<MeteoData>() );
			vecStation.push_back( std::vector<StationData>() );
448
449
			vecStation[jj+1].reserve(buffer_reserve);
			vecMeteo[jj+1].reserve(buffer_reserve);
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
			for (unsigned int ii=0; ii<vecMeteo[0].size(); ii++){
				//NOTE: there needs to be the same amount of 1D and 2D data
				vecStation[jj+1].push_back(tmpvecS[jj]);
				vecMeteo[jj+1].push_back(MeteoData());
			}
		}

		do {
			unsigned int currentindex = bufferindex;
			read2DMeteoData(filenames[0], "nswc", hashStations, vecMeteo, bufferindex);
			bufferindex = currentindex;
			read2DMeteoData(filenames[1], "rh", hashStations, vecMeteo, bufferindex);
			bufferindex = currentindex;
			read2DMeteoData(filenames[2], "ta", hashStations, vecMeteo, bufferindex);
			bufferindex = currentindex;
			read2DMeteoData(filenames[3], "vw", hashStations, vecMeteo, bufferindex);

			if(filenames.size() == 5) { //for keeping dw optional
				bufferindex = currentindex;
				read2DMeteoData(filenames.at(4), "dw", hashStations, vecMeteo, bufferindex);
			}
			//cerr << "bufferindex: " << bufferindex << "  Expected size()" << vecMeteo[0].size() << endl;

			if (bufferindex < (vecMeteo[0].size())) { //number of 1D meteo data
				//construct new filenames for the continued buffering
				constructMeteo2DFilenames(vecMeteo[0][bufferindex].date, vecMeteo[0][bufferindex].date, filenames);
			}
		} while(bufferindex < (vecMeteo[0].size()));
	} catch(...) {
		//clear all 2D meteo data if error occurs
		if (vecMeteo.size() > 1)
			vecMeteo.erase(vecMeteo.begin()+1, vecMeteo.end());

		if (vecStation.size() > 1)
			vecStation.erase(vecStation.begin()+1, vecStation.end());

		cleanup();
		throw;
	}

	//clean data and convert the units
	for (unsigned int ii=1; ii<vecMeteo.size(); ii++) { //loop over all stations except 1D Meteo
		for (unsigned int jj=0; jj<vecMeteo[ii].size(); jj++){ //Meteo1D data already cleaned
			//vecMeteo[ii][jj].cleanData();
			convertUnits(vecMeteo[ii][jj]);
		}
	}
}

void A3DIO::constructMeteo2DFilenames(const Date& startDate, const Date& endDate, std::vector<std::string>& filenames)
{
	int startyear=0, endyear=0, dummy=0;
	std::string tmp;

	filenames.clear();

	startDate.getDate(startyear, dummy, dummy, dummy, dummy);
	endDate.getDate(endyear, dummy, dummy, dummy, dummy);
	cfg.getValue("METEOPATH", "Input", tmp);

	for (int yyyy = startyear; yyyy<=endyear; yyyy++){
		std::stringstream ss;
		ss << yyyy;

		std::string precFilename = tmp + "/prec" + ss.str() + ".txt";
		std::string rhFilename = tmp + "/rhum" + ss.str() + ".txt";
		std::string taFilename = tmp + "/tair" + ss.str() + ".txt";
		std::string wspdFilename = tmp + "/wspd" + ss.str() + ".txt";
		std::string wdirFilename = tmp + "/wdir" + ss.str() + ".txt";

		filenames.push_back(precFilename);
		filenames.push_back(rhFilename);
		filenames.push_back(taFilename);
		filenames.push_back(wspdFilename);

		if (IOUtils::fileExists(wdirFilename)) //keeping wdir optional
			filenames.push_back(wdirFilename);
	}

	for (unsigned int ii=0; ii<filenames.size(); ii++) {
		if (!IOUtils::fileExists(filenames[ii])) {
			throw FileNotFoundException(filenames[ii], AT);
		}
	}
}


unsigned int A3DIO::getNrOfStations(std::vector<std::string>& filenames, std::map<std::string, unsigned int>& hashStations)
{
	std::vector<std::string> tmpvec;
	std::string line_in="";

	for (unsigned int ii=0; ii<filenames.size(); ii++) {
		//cout << *it << endl;
		std::string filename = filenames[ii];

		fin.clear();
		fin.open (filename.c_str(), std::ifstream::in);
		if (fin.fail()) throw FileAccessException(filename, AT);

		char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

		IOUtils::skipLines(fin, 4, eoln);
		getline(fin, line_in, eoln); //5th line holds the names of the stations
		unsigned int cols = IOUtils::readLineToVec(line_in, tmpvec);
		if ( cols > 4) { // if there are any stations
			//check each station name and whether it's already hashed, otherwise: hash!
			for (unsigned int ii=4; ii<cols; ii++) {
				unsigned int tmp_int = hashStations.count(tmpvec.at(ii));
				if (tmp_int == 0) {
					//cout << "Found station: " << tmpvec.at(ii) << endl;
					hashStations[tmpvec.at(ii)] = hashStations.size();
				}
			}
		}
		cleanup();
	}

	return (hashStations.size());
}

void A3DIO::read2DMeteoData(const std::string& filename, const std::string& parameter,
					std::map<std::string,unsigned int>& hashStations,
					std::vector< std::vector<MeteoData> >& vecM, unsigned int& bufferindex)
{

	std::string line_in = "";
	unsigned int columns;
	std::vector<std::string> tmpvec, vec_names;
	Date tmp_date;
	int tmp_ymdh[4];

	fin.clear();
	fin.open (filename.c_str(), std::ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(filename, AT);
	}

	char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

	IOUtils::skipLines(fin, 4, eoln); //skip first 4 lines
	getline(fin, line_in, eoln); //line containing UNIQUE station names
	columns = IOUtils::readLineToVec(line_in, vec_names);
	if (columns < 4) {
		throw InvalidFormatException("[E] Premature end of line in file " + filename, AT);
	}

	MeteoData& lastMeteoData = vecM[0][vecM[0].size()-1]; //last time stamp in buffer of 1D meteo

	do {
		getline(fin, line_in, eoln);
		std::string tmpline = line_in;
		IOUtils::trim(tmpline);

		if (tmpline=="") {
			break;
		}

		if (IOUtils::readLineToVec(line_in, tmpvec)!=columns) { //Every station has to have its own column
			throw InvalidFormatException("[E] Premature End of Line or no data for date "
			                             + vecM[0][bufferindex].date.toString(Date::FULL) + " found in File "
			                             + filename, AT);
		}

		for (int ii=0; ii<4; ii++) {
			if (!IOUtils::convertString(tmp_ymdh[ii], tmpvec[ii], std::dec)) {
				throw InvalidFormatException("[E] Check date columns in " + filename, AT);
			}
		}
		tmp_date.setDate(tmp_ymdh[0],tmp_ymdh[1],tmp_ymdh[2],tmp_ymdh[3],0);

		MeteoData& currentMeteoData = vecM[0][bufferindex]; //1D Element to synchronize date
		if (tmp_date == currentMeteoData.date) {
			//Read in data
			for (unsigned int ii=4; ii<columns; ii++) {
				unsigned int stationnr = hashStations[vec_names.at(ii)];
				MeteoData& tmpmd = vecM[stationnr][bufferindex];
				tmpmd.date = tmp_date;

				if (parameter == "nswc") {
					if (!IOUtils::convertString(tmpmd.hnw, tmpvec[ii], std::dec)) {
						throw ConversionFailedException("For hnw value in " + filename + "  for date " + tmpmd.date.toString(Date::FULL), AT);
					}

				} else if (parameter == "rh") {
					if (!IOUtils::convertString(tmpmd.rh, tmpvec[ii], std::dec)) {
						throw ConversionFailedException("For rh value in " + filename + "  for date " + tmpmd.date.toString(Date::FULL), AT);
					}

				} else if (parameter == "ta") {
					if (!IOUtils::convertString(tmpmd.ta, tmpvec[ii], std::dec))
						throw ConversionFailedException("For ta value in " + filename + "  for date " + tmpmd.date.toString(Date::FULL), AT);

				} else if (parameter == "vw") {
					if (!IOUtils::convertString(tmpmd.vw, tmpvec[ii], std::dec)) {
						throw ConversionFailedException("For vw value in " + filename + "  for date " + tmpmd.date.toString(Date::FULL), AT);
					}
				} else if (parameter == "dw") {
					if (!IOUtils::convertString(tmpmd.dw, tmpvec[ii], std::dec)) {
						throw ConversionFailedException("For dw value in " + filename + "  for date " + tmpmd.date.toString(Date::FULL), AT);
					}
				}
			}

			bufferindex++;
		}
	} while((tmp_date<lastMeteoData.date) && (!fin.eof()));

	cleanup();
}

void A3DIO::read2DMeteoHeader(const std::string& filename, std::map<std::string,unsigned int>& hashStations,
				std::vector<StationData>& vecS)
{
	std::string line_in = "";
	unsigned int columns = 0;
	std::vector<std::string> vec_altitude, vec_xcoord, vec_ycoord, vec_names;

	fin.clear();
	fin.open (filename.c_str(), std::ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(filename, AT);
	}

	char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

	IOUtils::skipLines(fin, 1, eoln);

	//Read all relevant lines in
	getline(fin, line_in, eoln); //Altitude
	columns = IOUtils::readLineToVec(line_in, vec_altitude);

	getline(fin, line_in, eoln); //xcoord
	if (IOUtils::readLineToVec(line_in, vec_xcoord) != columns) {
		throw InvalidFormatException("Column count doesn't match from line to line in " + filename, AT);
	}

	getline(fin, line_in, eoln); //ycoord
	if (IOUtils::readLineToVec(line_in, vec_ycoord) != columns) {
		throw InvalidFormatException("Column count doesn't match from line to line in " + filename, AT);
	}

	getline(fin, line_in, eoln); //names
	if (IOUtils::readLineToVec(line_in, vec_names) != columns) {
		throw InvalidFormatException("Column count doesn't match from line to line in " + filename, AT);
	}

	cleanup();

	//Check for duplicate station names within one file ... station names need to be unique!
	vector<string> vec_dup = vec_names;
	for (unsigned int ii=0; ii<vec_names.size(); ii++){
		const string& tmp = vec_names[ii];
		for (unsigned int jj=0; jj<vec_dup.size(); jj++){
			if (jj != ii){
				if (vec_dup[jj] == tmp)
					throw IOException("Duplicate station names detected in " + filename, AT);
			}
		}
	}

	//Build Coords object to convert easting/northing values to lat/long in WGS84
	Coords coordinate(coordin, coordinparam);

	for (unsigned int ii=4; ii<columns; ii++) {
		unsigned int stationnr = hashStations[vec_names.at(ii)];
		double altitude, easting, northing;
		std::string stationName;
		if ((!IOUtils::convertString(altitude, vec_altitude.at(ii), std::dec))
		    || (!IOUtils::convertString(easting, vec_xcoord.at(ii), std::dec))
		    || (!IOUtils::convertString(northing, vec_ycoord.at(ii), std::dec))
		    || (!IOUtils::convertString(stationName, vec_names.at(ii), std::dec))) {
			throw ConversionFailedException("Conversion of station description failed in " + filename, AT);
		}
		coordinate.setXY(easting, northing, altitude);
725
		vecS[stationnr-1].setStationData(coordinate, stationName, stationName);
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
	}
}

void A3DIO::readSpecialPoints(std::vector<Coords>& pts)
{
	std::string filename="", line_in="";
	std::vector<std::string> tmpvec;
	std::vector< std::pair<int,int> > mypts;

	cfg.getValue("SPECIALPTSFILE", "Input", filename); // cout << tmp << endl;
	if (!IOUtils::fileExists(filename)) {
		throw FileNotFoundException(filename, AT);
	}

	fin.clear();
	fin.open (filename.c_str(), std::ifstream::in);
	if (fin.fail()) {
		throw FileAccessException(filename,AT);
	}

	char eoln = IOUtils::getEoln(fin); //get the end of line character for the file

	while (!fin.eof()) {
		getline(fin, line_in, eoln);

		if (IOUtils::readLineToVec(line_in, tmpvec)==2) { //Try to convert
			int x, y;
			if (!IOUtils::convertString(x, tmpvec.at(0), std::dec)) {
				throw ConversionFailedException("Conversion of a value failed in " + filename + " line: " + line_in, AT);
			}

			if (!IOUtils::convertString(y, tmpvec.at(1), std::dec)) {
				throw ConversionFailedException("Conversion of a value failed in " + filename + " line: " + line_in, AT);
			}

			std::pair<int,int> tmppair(x,y);
			mypts.push_back(tmppair);
		}
	}
	cleanup();

	//Now put everything into the output vector TODO: don't do any intermediate steps... copy directly into vector!
	Coords tmp_pts;
	for (unsigned int jj=0; jj<mypts.size(); jj++) {
		tmp_pts.setGridIndex(mypts.at(jj).first, mypts.at(jj).second, IOUtils::inodata, false);
		pts.push_back(tmp_pts);
	}
}

int A3DIO::create1DFile(const std::vector< std::vector<MeteoData> >& data, const std::vector< std::vector<StationData> >& stations)
{//TODO: add check for stations' positions
	std::string tmp_path;
	cfg.getValue("METEOPATH", "Output", tmp_path);
	const unsigned int sta_nr = stations.size();
	if(sta_nr==0) return EXIT_FAILURE;

	for(unsigned int ii=0; ii<sta_nr; ii++) {
		const unsigned int size = data[ii].size();
		if(size>0) {
785
			const std::string filename = tmp_path+"/meteo1D_"+stations[ii][0].getStationID()+".txt";
786
787
788
789
790
			std::ofstream file(filename.c_str(), std::ios::out | std::ios::trunc);
			if(!file) {
				throw FileAccessException("[E] Can not open file "+filename, AT);
			}

791
			file << "Name = " << stations[ii][0].getStationID() << "\n";
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
			file << "Latitude = " << stations[ii][0].position.getLat() << "\n";
			file << "Longitude = " << stations[ii][0].position.getLon() << "\n";
			file << "X_Coord = " << stations[ii][0].position.getEasting() << "\n";
			file << "Y_Coord = " << stations[ii][0].position.getNorthing() << "\n";
			file << "Altitude = " << stations[ii][0].position.getAltitude() << "\n";
			file << "YYYY MM DD HH ta iswr vw rh ea nswc\n";

			file.flags ( std::ios::fixed );
			for(unsigned int j=0; j<size; j++) {
				int yyyy, mm, dd, hh;
				data[ii][j].date.getDate(yyyy, mm, dd, hh);
				file.fill('0');
				file << setw(4) << yyyy << " " << setw(2) << mm << " " << setw(2) << dd << " " << setw(2) << hh << " ";
				file.fill(' ');
				if(data[ii][j].ta == IOUtils::nodata)
					file << setw(6) << setprecision(0) <<  IOUtils::nodata << " ";
				else
					file << setw(6) << setprecision(2) <<  K_TO_C(data[ii][j].ta) << " ";
				if(data[ii][j].iswr == IOUtils::nodata)
					file << setw(6) << setprecision(0) << IOUtils::nodata << " ";
				else
					file << setw(6) << setprecision(2) << data[ii][j].iswr << " ";
				if(data[ii][j].vw == IOUtils::nodata)
					file << setw(6) << setprecision(0) << IOUtils::nodata << " ";
				else
					file << setw(6) << setprecision(2) << data[ii][j].vw << " ";
				if(data[ii][j].rh == IOUtils::nodata)
					file << setw(6) << setprecision(0) << IOUtils::nodata << " ";
				else
					file << setw(6) << setprecision(2) << data[ii][j].rh * 100. << " ";
				if(data[ii][j].ilwr == IOUtils::nodata)
					file << setw(6) << setprecision(0) << IOUtils::nodata << " ";
				else
					file << setw(6) << setprecision(2) << data[ii][j].ilwr << " ";
				if(data[ii][j].hnw == IOUtils::nodata)
					file << setw(6) << setprecision(0) << IOUtils::nodata << "\n";
				else
					file << setw(6) << setprecision(2) << data[ii][j].hnw << "\n";
			}
			file.close();
		}
	}
	return EXIT_SUCCESS;
}

int A3DIO::writeHeader(std::ofstream &file, const std::vector< std::vector<StationData> >& stations, const std::string parameter_name)
{
	std::ostringstream str_altitudes;
	std::ostringstream str_eastings;
	std::ostringstream str_northings;
	const unsigned int sta_nr = stations.size();
	if(sta_nr==0) return EXIT_FAILURE;
	
	file << "X:\\filepath " << parameter_name <<endl;
	for(unsigned int ii=0;ii<sta_nr;ii++) {
		if(stations[ii].size() > 0) {
			str_altitudes << stations[ii][0].position.getAltitude() << " ";
			str_eastings << stations[ii][0].position.getEasting() << " ";
			str_northings << stations[ii][0].position.getNorthing() << " ";
		}
	}
	file << "YY MM DD HH " << str_altitudes.str() << "\n"; //altitudes
	file << "YY MM DD HH " << str_eastings.str() << "\n"; //easting
	file << "YY MM DD HH " << str_northings.str() << "\n"; //northing
	file << "YYYY MM DD HH";
	for(unsigned int ii=0; ii<sta_nr; ii++) {
		if(stations[ii].size() > 0) {
859
			file << " " << stations[ii][0].getStationID();
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
		}
	}
	file << std::endl;
	return EXIT_SUCCESS;
}

void A3DIO::open2DFile(const std::vector< std::vector<StationData> >& stations,
                       const std::string& fileprefix, const std::string& label, const double& year, 
                       std::ofstream& file)
{//creates a meteo2D file according to the specifications
//the header is also written
	std::ostringstream out;
	out << year;

	const std::string filename = fileprefix+out.str()+".txt";

	file.open(filename.c_str(), ios::out | ios::trunc);
	if(!file) {
		throw FileAccessException("Can not create file "+filename, AT);
	}
	writeHeader(file, stations, label);
}

int A3DIO::write2DmeteoFile(const std::vector< std::vector<MeteoData> >& data,
                            const std::vector< std::vector<StationData> >& stations,
                            const unsigned int& parindex, const std::string& fileprefix,
                            const std::string& label)
{//HACK: we assume that all stations have data that is time synchronized...
	const unsigned int sta_nr = stations.size();
	if(sta_nr==0) return EXIT_FAILURE;
	const unsigned int nb_timesteps = data[0].size();
	if(nb_timesteps==0) return EXIT_FAILURE;

	std::ofstream file;
	int startyear, year, month, day, hour;
	data[0][0].date.getDate(startyear, month, day, hour);

	open2DFile(stations, fileprefix, label, startyear, file);
	file.flags ( ios::fixed );

	for(unsigned int ii=0; ii<nb_timesteps; ii++) {
		data[0][ii].date.getDate(year, month, day, hour);
		if(year!=startyear) {
			//if the year has changed, we need to write to a new file
			file.close();
			startyear = year;
			open2DFile(stations, fileprefix, label, year, file);
			file.flags ( ios::fixed );
		}

		file.fill('0');
		file << setw(4) << year << " " << setw(2) << month << " " << setw(2) << day << " " << setw(2) << hour;
		file.fill(' ');
		for(unsigned int j=0; j<sta_nr; j++) {
			double value = data[j][ii].param(parindex);
			if(value==IOUtils::nodata) {
				file << " " << setw(7) << setprecision(0) << IOUtils::nodata;
			} else {
				if(parindex==mio::MeteoData::TA) value = K_TO_C(value);
				if(parindex==mio::MeteoData::RH) value = value*100.;
				file << " " << setw(7) << setprecision(2) << value;
			}
		}
		file << "\n";
	}
	file.close();
	return EXIT_SUCCESS;
}

void A3DIO::write2DMeteo(const std::vector< std::vector<MeteoData> >& data, const std::vector< std::vector<StationData> >& stations)
{
	std::string tmp_path;
	cfg.getValue("METEOPATH", "Output", tmp_path);

	write2DmeteoFile(data, stations, mio::MeteoData::TA, tmp_path+"/tair", "air temperature");
	write2DmeteoFile(data, stations, mio::MeteoData::RH, tmp_path+"/rhum", "relative humidity");
	write2DmeteoFile(data, stations, mio::MeteoData::VW, tmp_path+"/wspd", "wind velocity");
	write2DmeteoFile(data, stations, mio::MeteoData::DW, tmp_path+"/wdir", "wind direction");
	write2DmeteoFile(data, stations, mio::MeteoData::HNW, tmp_path+"/prec", "precipitations");
}

/*extern "C"
{
	void deleteObject(void* obj) {
		delete reinterpret_cast<PluginObject*>(obj);
	}

	void* loadObject(const std::string& classname, const std::string& filename) {
		if(classname == "A3DIO") {
			cerr << "Creating handle to " << classname << endl;
			//return new A3DIO(deleteObject);
			return new A3DIO(deleteObject, filename);
		}
		cerr << "Could not load " << classname << endl;
		return NULL;
	}
}

*/

} //namespace