bool Cihacres_elev::_CreateDialog3()
{
	CSG_String		s;
	CSG_Parameters	P;  // used to add Parameters in the second dialog
	CSG_Parameter	*pNode;

	//	Dialog design
	P.Set_Name(_TL("Choose Time Range"));

	s.Printf(SG_T("Node1"), 1);
	pNode = P.Add_Node(NULL,s,SG_T("Time Range"),_TL(""));

	s.Printf(SG_T("FDAY") , 1-1);
	P.Add_String(pNode,s,_TL("First Day"),_TL(""),
				 m_p_InputTable->Get_Record(0)->asString(m_dateField));

	s.Printf(SG_T("LDAY") , 1-2);
	P.Add_String(pNode,s,_TL("Last Day"),_TL(""),
				 m_p_InputTable->Get_Record(m_p_InputTable->Get_Record_Count()-1)->asString(m_dateField));

	if( SG_UI_Dlg_Parameters(&P, _TL("Choose Time Range")) )
	{
		///////////////////////////////////////////////////////////////
		//
		//                ASSIGN DATA FROM SECOND DIALOG
		//
		///////////////////////////////////////////////////////////////
		m_date1		= P(CSG_String::Format(SG_T("FDAY"),m_dateField).c_str())->asString();
		m_date2		= P(CSG_String::Format(SG_T("LDAY"),m_streamflowField).c_str())->asString();
		return(true);
	}
	return(false);
}
//---------------------------------------------------------
bool CPointcloud_To_Text_File::On_Execute(void)
{
	CSG_PointCloud			*pPoints;
	CSG_String				fileName;
	CSG_File				*pTabStream = NULL;
	bool					bWriteHeader;
	CSG_String				fieldSep;

	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	CSG_String				s;
	std::vector<int>		vCol, vPrecision;


	//-----------------------------------------------------
	pPoints			= Parameters("POINTS")		->asPointCloud();
	fileName		= Parameters("FILE")		->asString();
	bWriteHeader	= Parameters("WRITE_HEADER")->asBool();


	switch (Parameters("FIELDSEP")->asInt())
    {
	default:
    case 0:		fieldSep = "\t";	break;
    case 1:		fieldSep = " ";		break;
    case 2:		fieldSep = ",";		break;
    }


	if( fileName.Length() == 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide an output file name!"));
		return( false );
	}


	if (SG_UI_Get_Window_Main())
	{
		P.Set_Name(_TL("Check the fields to export"));

		for(int iField=0; iField<pPoints->Get_Field_Count(); iField++)
		{
			s.Printf(SG_T("NODE_%03d") , iField + 1);
			pNode	= P.Add_Node(NULL, s, CSG_String::Format(_TL("%d. %s"), iField + 1, _TL("Field")), _TL(""));

			s.Printf(SG_T("FIELD_%03d"), iField);
			P.Add_Value(pNode, s, CSG_String::Format(SG_T("%s"), pPoints->Get_Field_Name(iField)), _TL(""), PARAMETER_TYPE_Bool, false);

			s.Printf(SG_T("PRECISION_%03d"), iField);
			P.Add_Value(pNode, s, _TL("Decimal Precision"), _TL(""), PARAMETER_TYPE_Int, 2.0, 0.0, true);
		}


		//-----------------------------------------------------
		if( Dlg_Parameters(&P, _TL("Field Properties")) )
		{
			vCol.clear();
			vPrecision.clear();

			for(int iField=0; iField<pPoints->Get_Field_Count(); iField++)
			{
				if( P(CSG_String::Format(SG_T("FIELD_%03d" ), iField).c_str())->asBool() )
				{
					vCol.push_back(iField);
					vPrecision.push_back(P(CSG_String::Format(SG_T("PRECISION_%03d" ), iField).c_str())->asInt());
				}
			}
		}
		else
			return( false );
	}
	else // CMD
	{
		CSG_String		sFields, sPrecision;
		CSG_String		token;
		int				iValue;


		sFields		= Parameters("FIELDS")->asString();
		sPrecision	= Parameters("PRECISIONS")->asString();

		CSG_String_Tokenizer   tkz_fields(sFields, ";", SG_TOKEN_STRTOK);

		while( tkz_fields.Has_More_Tokens() )
		{
			token	= tkz_fields.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			if( !token.asInt(iValue) )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: can't convert to number"));
				return( false );
			}

			iValue	-= 1;

			if( iValue < 0 || iValue > pPoints->Get_Field_Count() - 1 )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: field index out of range"));
				return( false );
			}
			else
				vCol.push_back(iValue);
		}

		CSG_String_Tokenizer   tkz_precisons(sPrecision.c_str(), ";", SG_TOKEN_STRTOK);

		while( tkz_precisons.Has_More_Tokens() )
		{
			token	= tkz_precisons.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			if( !token.asInt(iValue) )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: can't convert to number"));
				return( false );
			}

			vPrecision.push_back(iValue);
		}
	}


	if( vCol.size() == 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide at least one column to export!"));
		return( false );
	}

	if( vCol.size() != vPrecision.size() )
	{
		SG_UI_Msg_Add_Error(_TL("Number of fields and precisions must be equal!"));
		return( false );
	}

	//-----------------------------------------------------
	pTabStream = new CSG_File();

	if( !pTabStream->Open(fileName, SG_FILE_W, false) )
	{
		SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open output file %s!"), fileName.c_str()));
		delete (pTabStream);
		return (false);
	}


	if( bWriteHeader )
	{
	    CSG_String  sHeader;

		for(size_t i=0; i<vCol.size(); i++)
		{
		    sHeader += CSG_String::Format(SG_T("%s"), pPoints->Get_Field_Name(vCol.at(i)));

		    if( i < vCol.size()-1 )
                sHeader += fieldSep.c_str();
		}

		sHeader += SG_T("\n");

		pTabStream->Write(sHeader);
	}


	for(int iPoint=0; iPoint<pPoints->Get_Count() && Set_Progress(iPoint, pPoints->Get_Count()); iPoint++)
	{
		CSG_String	sLine;

		for(size_t i=0; i<vCol.size(); i++)
		{
			switch (pPoints->Get_Field_Type(vCol.at(i)))
			{
			case SG_DATATYPE_Double:
			case SG_DATATYPE_Float:
				sLine += SG_Get_String(pPoints->Get_Value(iPoint, vCol.at(i)), vPrecision.at(i), false);
				break;
			default:
				sLine += CSG_String::Format(SG_T("%d"), (int)pPoints->Get_Value(iPoint, vCol.at(i)));
				break;
			}

            if( i < vCol.size()-1 )
                sLine += fieldSep.c_str();
		}

		sLine += SG_T("\n");

		pTabStream->Write(sLine);
	}


	pTabStream->Close();
	delete (pTabStream);

	return( true );
}
bool Cihacres_elev::_CreateDialog2()
{
	int		i;

	//std::ofstream f("_out_elev.txt");

	CSG_Parameters	P;  // used to add Parameters in the second dialog
	CSG_Parameter	*pNode, *pNode1;
	CSG_String		s;
	CSG_String		tmpNode, tmpName;

	P.Set_Name(_TL("IHACRES Elevation Bands (Dialog 2)"));
	// Input file ----------------------------------------------
	pNode = P.Add_Table(
		NULL	, "TABLE"	, _TL("IHACRES Input Table"),
		_TL(""),
		PARAMETER_INPUT
	);

	P.Add_Table_Field(
		pNode	, "DATE_Field"	, _TL("Date Column"),
		SG_T("Select the column containing the Date")
	);

	P.Add_Table_Field(
		pNode	, "DISCHARGE_Field"	, _TL("Streamflow (obs.) Column"),
		SG_T("Select the column containing the observed streamflow time series)")
	);
	
	for (i = 0; i < m_nElevBands; i++)
	{
		tmpNode = convert_sl::Int2String(i+1).c_str();
		//s.Printf(tmpNode.c_str(), i);
		//pNode1 = P.Add_Node(NULL,s,SG_T("Elevation Band Input",_TL(""));

		tmpName = SG_T("PCP Column: Elevation Band: ");
		tmpName+=tmpNode;
		P.Add_Table_Field(
			pNode	, tmpName.c_str(), tmpName.c_str(),
			SG_T("Select Precipitation Column")
		);

		tmpName = SG_T("TMP Column: Elevation Band: ");
		tmpName+=tmpNode;
		P.Add_Table_Field(
			pNode	, tmpName.c_str()	, tmpName.c_str(),
			SG_T("Select Temperature Column")
		);
	}
	// Input file ----------------------------------------------

	for (i = 0; i < m_nElevBands; i++)
	{
		tmpNode = SG_T("Node");
		tmpNode+=convert_sl::Int2String(i+100).c_str();
		tmpName = SG_T("Elevation Band ");
		tmpName+=convert_sl::Int2String(i+1).c_str();

		s.Printf(tmpNode.c_str(), i+100);
		pNode = P.Add_Node(NULL,s,tmpName.c_str(),_TL(""));
		
		tmpName = SG_T("Area [km2] Elev(");
		tmpName += tmpNode;
		tmpName += SG_T(")");
		P.Add_Value(
			pNode,	tmpName, _TL("Area [km2]"),
			_TL(""),
			PARAMETER_TYPE_Double
		);

		tmpName = SG_T("Mean Elevation [m.a.s.l] Elev(");
		tmpName += tmpNode;
		tmpName += _TL(")");
		P.Add_Value(
			pNode,	tmpName, _TL("Mean Elevation [m.a.s.l]"),
			_TL(""),
			PARAMETER_TYPE_Double
		);
	//}

		// Parameters of non-linear module -------------------------
		tmpNode = SG_T("Node");
		tmpNode+=convert_sl::Int2String(i+150).c_str();
		s.Printf(tmpNode.c_str(), i+150);
		pNode1 = P.Add_Node(pNode,s,SG_T("Non-Linear Module"),_TL(""));

		tmpName = SG_T("TwFAC(");
		tmpName += tmpNode;
		tmpName += _TL(")");
		P.Add_Value(
			pNode1,	tmpName,	_TL("Wetness decline time constant (Tw)"),
			_TW("Tw is approximately the time constant, or inversely, "
			"the rate at which the catchment wetness declines in the absence of rainfall"),
			PARAMETER_TYPE_Double,
			1.0, 0.01, true, 150.0, true
		);

		tmpName = SG_T("TFAC(");
		tmpName += tmpNode;
		tmpName += _TL(")");
		P.Add_Value(
			pNode1, tmpName, SG_T("Temperature Modulation Factor (f)"),
			_TL("Temperature Modulation Factor f"),
			PARAMETER_TYPE_Double,
			1.0, 0.0001, true, 10.0, true
		);

		tmpName = SG_T("CFAC(");
		tmpName += tmpNode;
		tmpName += _TL(")");
		P.Add_Value(
			pNode1,tmpName,	_TL("Parameter (c)"),
			_TL("Parameter (c) to fit streamflow volume"),
			PARAMETER_TYPE_Double,
			0.001, 0.0, true, 1.0, true
		);

		switch(m_IHAC_version)
		{
		case 0: // Jakeman & Hornberger (1993)
			break;
		case 1: // Croke et al. (2005)
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+200).c_str();
			s.Printf(tmpNode.c_str(), i+200);
			pNode1 = P.Add_Node(pNode,s,SG_T("Soil Moisture Power Eq."),_TL(""));

			tmpName = SG_T("LFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("Parameter (l)"),
				_TL("Soil moisture index threshold"),
				PARAMETER_TYPE_Double,
				0.0, 0.0, true, 5.0, true
			);

			tmpName = SG_T("PFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("Parameter (p)"),
				_TL("non-linear response term"),
				PARAMETER_TYPE_Double,
				0.0, 0.0, true, 5.0, true
			);
				break;
		}
		// Parameters of non-linear module -------------------------

		// Parameters of linear module -----------------------------
		switch(m_StorConf)
		{
		case 0: // single storage
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+250).c_str();
			s.Printf(tmpNode.c_str(), i+250);
			pNode1 = P.Add_Node(pNode,s,SG_T("Linear Module"),_TL(""));

			tmpName = SG_T("AFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("(a)"),
				_TL(""),
				PARAMETER_TYPE_Double,
				-0.8, -0.99, true, -0.01, true
			);

			tmpName = SG_T("BFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("(b)"),
				_TL(""),
				PARAMETER_TYPE_Double,
				0.2, 0.001, true, 1.0, true
			);
			break;

		case 1: // two parallel storages
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+250).c_str();
			s.Printf(tmpNode.c_str(), i+250);
			pNode1 = P.Add_Node(pNode,s,SG_T("Linear Module"),_TL(""));

			// Parameter a
			tmpName = SG_T("AQ(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,tmpName,	_TL("a(q)"),
				_TL(""),
				PARAMETER_TYPE_Double,
				-0.7, -0.99, true, -0.01, true
			);

			tmpName = SG_T("AS(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("a(s)"),
				_TL(""),
				PARAMETER_TYPE_Double,
				-0.9, -0.99, true, -0.01, true
			);

			// Parameter b
			tmpName = SG_T("BQ(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,	tmpName,	_TL("b(q)"),
				_TL(""),
				PARAMETER_TYPE_Double,
				0.0, 0.0, true, 1.0, true
			);
			break;

		case 2: // two storages in series
			break;
		} // end switch (storconf)
		// Parameters of linear module -----------------------------

		tmpNode = SG_T("Node");
		tmpNode+=convert_sl::Int2String(i+300).c_str();
		s.Printf(tmpNode.c_str(), i+300);
		pNode1 = P.Add_Node(pNode,s,SG_T("Time Delay after Start of Rainfall (INTEGER)"),_TL(""));
						
		tmpName = SG_T("DELAY(");
			tmpName += tmpNode;
			tmpName += _TL(")");
		P.Add_Value(
			pNode1,tmpName,	SG_T("Time Delay (Rain-Runoff)"),
			SG_T("The delay after the start of rainfall, before the discharge starts to rise."),
			PARAMETER_TYPE_Int,
			0, 1, true, 100, true
		);

		// snow module parameters ----------------------------------
		if (m_bSnowModule)
		{
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+350).c_str();
			s.Printf(tmpNode.c_str(), i+350);
			pNode1 = P.Add_Node(pNode,s,SG_T("Snow Module Parameters"),_TL(""));
			
			tmpName = SG_T("T_RAIN(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,tmpName,	SG_T("Temperature Threshold for Rainfall)"),
				SG_T("Below this threshold precipitation will fall as snow"),
				PARAMETER_TYPE_Double,
				-1.0, -10.0, true, 10.0, true
			);

			tmpName = SG_T("T_MELT(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,tmpName,	SG_T("Temperature Threshold for Melting"),
				SG_T("Above this threshold snow will start to melt"),
				PARAMETER_TYPE_Double,
				1.0, -5.0, true, 10.0, true
			);

			tmpName = SG_T("DD_FAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			P.Add_Value(
				pNode1,tmpName,	SG_T("Day-Degree Factor"),
				SG_T("Day-Degree Factor depends on catchment characteristics"),
				PARAMETER_TYPE_Double,
				0.7, 0.7, true, 9.2, true
			);
		}
		// snow module parameters ----------------------------------
	}
	
	
	if( SG_UI_Dlg_Parameters(&P, _TL("IHACRES Distributed Input Dialog 2")) )
	{
		// input table
		m_p_InputTable		= P("TABLE")				->asTable();
		// field numbers
		m_dateField			= P("DATE_Field")			->asInt();
		m_streamflowField	= P("DISCHARGE_Field")		->asInt();
		for (int i = 0; i < m_nElevBands; i++)
		{
			tmpNode = convert_sl::Int2String(i+1).c_str();
			
			// get precipitation column of Elevation Band[i]
			tmpName = SG_T("PCP Column: Elevation Band: ");
			tmpName+=tmpNode;
			m_p_pcpField[i]			= P(tmpName)		->asInt();

			// get temperature column of Elevation Band[i]
			tmpName = SG_T("TMP Column: Elevation Band: ");
			tmpName+=tmpNode;
			m_p_tmpField[i]			= P(tmpName)		->asInt();

			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+100).c_str();

			// get area[km2] of Elevation Band[i]
			tmpName = SG_T("Area [km2] Elev(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_p_elevbands[i].m_area	= P(tmpName)		->asDouble();

			// get mean elevation of Elevation Band[i]
			tmpName = SG_T("Mean Elevation [m.a.s.l] Elev(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_p_elevbands[i].m_mean_elev =P(tmpName)	->asDouble();
		

			// non-linear module parameters
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+150).c_str();
			// get Tw
			tmpName = SG_T("TwFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_p_nonlinparms->mp_tw[i]	= P(tmpName)		->asDouble();

			// get f
			tmpName = SG_T("TFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_p_nonlinparms->mp_f[i]	= P(tmpName)		->asDouble();

			// get c
			tmpName = SG_T("CFAC(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_p_nonlinparms->mp_c[i]	= P(tmpName)		->asDouble();

			switch(m_IHAC_version)
			{
			case 0: // Jakeman & Hornberger (1993)
				break;
			case 1: // Croke et al. (2005)
				// get l
				tmpName = SG_T("LFAC(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_nonlinparms->mp_l[i]= P(tmpName)		->asDouble();

				// get p
				tmpName = SG_T("PFAC(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_nonlinparms->mp_p[i]= P(tmpName)		->asDouble();
			}

			// linear module parameters
			switch(m_nStorages)
			{
			case 1: // single storage
				tmpNode = SG_T("Node");
				tmpNode+=convert_sl::Int2String(i+250).c_str();
				// get a
				tmpName = SG_T("AFAC(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_linparms->a[i]		= P(tmpName)		->asDouble();

				// get b
				tmpName = SG_T("BFAC(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_linparms->b[i]		= P(tmpName)		->asDouble();
				break;
			case 2: // two storages
				tmpNode = SG_T("Node");
				tmpNode+=convert_sl::Int2String(i+250).c_str();
				// get aq
				tmpName = SG_T("AQ(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_linparms->aq[i]		= P(tmpName)		->asDouble();

				// get bq
				tmpName = SG_T("BQ(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_linparms->bq[i]		= P(tmpName)		->asDouble();

				// get as
				tmpName = SG_T("AS(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_p_linparms->as[i]		= P(tmpName)		->asDouble();

				// get bs
				m_p_linparms->bs[i] = ihacres.Calc_Parm_BS(m_p_linparms->aq[i],m_p_linparms->as[i],m_p_linparms->bq[i]);
				break;
			}

			// get delay
			tmpNode = SG_T("Node");
			tmpNode+=convert_sl::Int2String(i+300).c_str();

			tmpName = SG_T("DELAY(");
			tmpName += tmpNode;
			tmpName += _TL(")");
			m_delay						= P(tmpName)		->asInt();	

			if (m_bSnowModule)
			{
				tmpNode = SG_T("Node");
				tmpNode+=convert_sl::Int2String(i+350).c_str();

				// get T_RAIN
				tmpName = SG_T("T_RAIN(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_pSnowparms[i].T_Rain		= P(tmpName)		->asDouble();

				// get T_MELT
				tmpName = SG_T("T_MELT(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_pSnowparms[i].T_Melt		= P(tmpName)		->asDouble();

				// get DD_FAC
				tmpName = SG_T("DD_FAC(");
				tmpName += tmpNode;
				tmpName += _TL(")");
				m_pSnowparms[i].DD_FAC		= P(tmpName)		->asDouble();
			}
		}

		return(true);
	}
	return(false);
}
//---------------------------------------------------------
bool CPolygonStatisticsFromPoints::On_Execute(void)
{
	int						i, j, n, Offset, *bAttribute;
	CSG_Simple_Statistics	*Statistics;
	CSG_Parameters			*pParameters;
	CSG_Shapes				*pPolygons, *pPoints;

	//-----------------------------------------------------
	pPoints		= Parameters("POINTS")		->asShapes();
	pPolygons	= Parameters("POLYGONS")	->asShapes();

	if( pPolygons->Get_Count() <= 0 || pPoints->Get_Count() <= 0 )
	{
		return( false );
	}

	//-----------------------------------------------------
	pParameters	= Get_Parameters("ATTRIBUTES");

	pParameters->Del_Parameters();

	for(i=0; i<pPoints->Get_Field_Count(); i++)
	{
		if( SG_Data_Type_is_Numeric(pPoints->Get_Field_Type(i)) )
		{
			CSG_Parameter	*pNode	= pParameters->Add_Node(NULL, CSG_String::Format(SG_T("%d"), i), pPoints->Get_Field_Name(i), _TL(""));

			for(j=0; j<STAT_Count; j++)
			{
				pParameters->Add_Value(pNode,
					CSG_String::Format(SG_T("%d|%d"), i, j),
					CSG_String::Format(SG_T("[%s]"), STAT_Name[j].c_str()),
					_TL(""), PARAMETER_TYPE_Bool, false
				);
			}
		}
	}

	if( !Dlg_Parameters("ATTRIBUTES") )
	{
		return( false );
	}

	//-----------------------------------------------------
	if( Parameters("STATISTICS")->asShapes() == NULL )
	{
		Parameters("STATISTICS")->Set_Value(pPolygons);
	}
	else if( pPolygons != Parameters("STATISTICS")->asShapes() )
	{
		Parameters("STATISTICS")->asShapes()->Assign(pPolygons);

		pPolygons	= Parameters("STATISTICS")->asShapes();
	}

	//-----------------------------------------------------
	bAttribute	= new int[pPoints->Get_Field_Count()];
	Offset		= pPolygons->Get_Field_Count();

	for(i=0, n=0; i<pPoints->Get_Field_Count(); i++)
	{
		bAttribute[i]	= 0;

		if( SG_Data_Type_is_Numeric(pPoints->Get_Field_Type(i)) )
		{
			for(j=0; j<STAT_Count; j++)
			{
				CSG_Parameter	*pParameter	= pParameters->Get_Parameter(CSG_String::Format(SG_T("%d|%d"), i, j));

				if( pParameter && pParameter->asBool() )
				{
					bAttribute[i]	|= STAT_Flag[j];

					pPolygons->Add_Field(CSG_String::Format(SG_T("%s_%s"), pPoints->Get_Field_Name(i), STAT_Name[j].c_str()), SG_DATATYPE_Double);

					n++;
				}
			}
		}
	}

	if( n == 0 )
	{
		delete[](bAttribute);

		return( false );
	}

	//-----------------------------------------------------
	Statistics	= new CSG_Simple_Statistics[pPoints->Get_Field_Count()];

	for(int iPolygon=0; iPolygon<pPolygons->Get_Count() && Set_Progress(iPolygon, pPolygons->Get_Count()); iPolygon++)
	{
		CSG_Shape_Polygon	*pPolygon	= (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);

		//-------------------------------------------------
		for(i=0; i<pPoints->Get_Field_Count(); i++)
		{
			Statistics[i].Invalidate();
		}

		//-------------------------------------------------
		for(int iPoint=0; iPoint<pPoints->Get_Count() && Process_Get_Okay(); iPoint++)
		{
			CSG_Shape	*pPoint	= pPoints->Get_Shape(iPoint);

			if( pPolygon->is_Containing(pPoint->Get_Point(0)) )
			{
				for(i=0; i<pPoints->Get_Field_Count(); i++)
				{
					if( bAttribute[i] )
					{
						Statistics[i].Add_Value(pPoint->asDouble(i));
					}
				}
			}
		}

		//-------------------------------------------------
		for(i=0, n=Offset; i<pPoints->Get_Field_Count(); i++)
		{
			if( bAttribute[i] )
			{
				if( Statistics[i].Get_Count() > 0 )
				{
					if( bAttribute[i] & STAT_Flag[STAT_Sum] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Sum());		}
					if( bAttribute[i] & STAT_Flag[STAT_Avg] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Mean());		}
					if( bAttribute[i] & STAT_Flag[STAT_Var] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Variance());	}
					if( bAttribute[i] & STAT_Flag[STAT_Dev] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_StdDev());	}
					if( bAttribute[i] & STAT_Flag[STAT_Min] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Minimum());	}
					if( bAttribute[i] & STAT_Flag[STAT_Max] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Maximum());	}
					if( bAttribute[i] & STAT_Flag[STAT_Num] )	{	pPolygon->Set_Value(n++, Statistics[i].Get_Count());	}
				}
				else
				{
					if( bAttribute[i] & STAT_Flag[STAT_Sum] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Avg] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Var] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Dev] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Min] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Max] )	{	pPolygon->Set_NoData(n++);	}
					if( bAttribute[i] & STAT_Flag[STAT_Num] )	{	pPolygon->Set_NoData(n++);	}
				}
			}
		}
	}

	//-----------------------------------------------------
	delete[](Statistics);
	delete[](bAttribute);

	DataObject_Update(pPolygons);

	return( true );
}
//---------------------------------------------------------
bool CPointCloud_From_Text_File::On_Execute(void)
{
	CSG_String				fileName;
	int						iField, iType;
	TSG_Data_Type			Type;
	CSG_String				Name, Types, s;
	CSG_PointCloud			*pPoints;
	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	int						xField, yField, zField, nAttribs, max_iField;
	bool					bSkipHeader;
	char					fieldSep;
	std::vector<int>		vCol;
	std::ifstream			tabStream;
    std::string				tabLine;
	double					lines;
	long					cntPt, cntInvalid;
	double					x, y, z, value;


	//-----------------------------------------------------
	fileName	= Parameters("FILE")		->asString();
	xField		= Parameters("XFIELD")		->asInt() - 1;
	yField		= Parameters("YFIELD")		->asInt() - 1;
	zField		= Parameters("ZFIELD")		->asInt() - 1;
	nAttribs	= Parameters("ATTRIBS")		->asInt();
	bSkipHeader	= Parameters("SKIP_HEADER")	->asBool();

	switch (Parameters("FIELDSEP")->asInt())
    {
	default:
    case 0: fieldSep = '\t';	break;
    case 1: fieldSep = ' ';		break;
    case 2: fieldSep = ',';		break;
    }

	Types.Printf(SG_T("%s|%s|%s|%s|%s|"),
		_TL("1 byte integer"),
		_TL("2 byte integer"),
		_TL("4 byte integer"),
		_TL("4 byte floating point"),
		_TL("8 byte floating point")
	);

	P.Set_Name(_TL("Attribute Field Properties"));

	for(iField=1; iField<=nAttribs; iField++)
	{
		s.Printf(SG_T("NODE_%03d") , iField);
		pNode	= P.Add_Node(NULL, s, CSG_String::Format(SG_T("%d. %s"), iField, _TL("Field")), _TL(""));

		s.Printf(SG_T("FIELD_%03d"), iField);
		P.Add_String(pNode, s, _TL("Name"), _TL(""), s);

		s.Printf(SG_T("COLUMN_%03d"), iField);
		P.Add_Value(pNode, s, _TL("Attribute is Column ..."), _TL(""), PARAMETER_TYPE_Int, iField+3, 1, true);

		s.Printf(SG_T("TYPE_%03d") , iField);
		P.Add_Choice(pNode, s, _TL("Type"), _TL(""), Types, 3);
	}

	//-----------------------------------------------------
	if( nAttribs > 0 )
	{
		if( Dlg_Parameters(&P, _TL("Field Properties")) )
		{
			pPoints	= SG_Create_PointCloud();
			pPoints->Set_Name(SG_File_Get_Name(fileName, false));
			Parameters("POINTS")->Set_Value(pPoints);

			for(iField=0; iField<nAttribs; iField++)
			{

				Name		 = P(CSG_String::Format(SG_T("FIELD_%03d" ), iField + 1).c_str())->asString();
				iType		 = P(CSG_String::Format(SG_T("TYPE_%03d"  ), iField + 1).c_str())->asInt();
				vCol.push_back(P(CSG_String::Format(SG_T("COLUMN_%03d"), iField + 1).c_str())->asInt() - 1);

				switch( iType )
				{
				default:
				case 0:	Type	= SG_DATATYPE_Char;		break;
				case 1:	Type	= SG_DATATYPE_Short;	break;
				case 2:	Type	= SG_DATATYPE_Int;		break;
				case 3:	Type	= SG_DATATYPE_Float;	break;
				case 4:	Type	= SG_DATATYPE_Double;	break;
				}

				pPoints->Add_Field(Name, Type);
			}
		}
		else
			return( false );
	}
	else
	{
		pPoints	= SG_Create_PointCloud();
		pPoints->Create();
		pPoints->Set_Name(SG_File_Get_Name(fileName, false));
		Parameters("POINTS")->Set_Value(pPoints);
	}

	max_iField = M_GET_MAX(xField, yField);
    max_iField = M_GET_MAX(max_iField, zField);
	for( unsigned int i=0; i<vCol.size(); i++ )
	{
		if( max_iField < vCol.at(i) )
			max_iField = vCol.at(i);
	}

	// open input stream
    //---------------------------------------------------------
    tabStream.open(fileName.b_str(), std::ifstream::in);
    if( !tabStream )
    {
        SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open input file!")));
        return (false);
    }

	tabStream.seekg(0, std::ios::end);	// get length of file
    lines = (double)tabStream.tellg();
    tabStream.seekg(0, std::ios::beg);

    std::getline(tabStream, tabLine);	// as a workaround we assume the number of lines from the length of the first line
    lines = lines / (double)tabStream.tellg();

	if( !bSkipHeader )
    {
        tabStream.clear();                      // let's forget we may have reached the EOF
        tabStream.seekg(0, std::ios::beg);      // and rewind to the beginning
    }

    
	// import
    //---------------------------------------------------------
	cntPt = cntInvalid = 0;

	SG_UI_Process_Set_Text(CSG_String::Format(_TL("Importing data ...")));

    while( std::getline(tabStream, tabLine) )
    {
        std::istringstream stream(tabLine);
        std::vector<std::string> tabCols;
        std::string tabEntry;

        if( cntPt%10000 == 0 )
            SG_UI_Process_Set_Progress((double)cntPt, lines);

        cntPt++;

        while( std::getline(stream, tabEntry, fieldSep) )      // read every column in this line and fill vector
        {
            if (tabEntry.length() == 0)
                continue;
            tabCols.push_back(tabEntry);
        }

        if ((int)tabCols.size() < max_iField - 1 )
        {
            SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipping misformatted line (%.0f)!"), cntPt), true);
            cntInvalid++;
            continue;
        }

		x = strtod(tabCols[xField].c_str(), NULL);
        y = strtod(tabCols[yField].c_str(), NULL);
        z = strtod(tabCols[zField].c_str(), NULL);

		pPoints->Add_Point(x, y, z);

		for( int i=0; i<nAttribs; i++ )
		{
			value = strtod(tabCols.at(vCol.at(i)).c_str(), NULL);
			pPoints->Set_Attribute(i, value);
		}
	}

	// finalize
    //---------------------------------------------------------
	tabStream.close();

	CSG_Parameters	sParms;
	DataObject_Get_Parameters(pPoints, sParms);
	if (sParms("COLORS_ATTRIB")	&& sParms("COLORS_TYPE") && sParms("METRIC_COLORS")
		&& sParms("METRIC_ZRANGE") && sParms("COLORS_AGGREGATE"))
		{
			sParms("COLORS_AGGREGATE")->Set_Value(3);				// highest z
			sParms("COLORS_TYPE")->Set_Value(2);                    // graduated color
			sParms("METRIC_COLORS")->asColors()->Set_Count(255);    // number of colors
			sParms("COLORS_ATTRIB")->Set_Value(2);					// z attrib
			sParms("METRIC_ZRANGE")->asRange()->Set_Range(pPoints->Get_Minimum(2),pPoints->Get_Maximum(2));
			DataObject_Set_Parameters(pPoints, sParms);
			DataObject_Update(pPoints);
		}

	if (cntInvalid > 0)
        SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipped %d invalid points!"), cntInvalid), true);

    SG_UI_Msg_Add(CSG_String::Format(_TL("%d points sucessfully imported."), (cntPt-cntInvalid)), true);

	return( true );
}
//---------------------------------------------------------
bool CSG_Direct_Georeferencer::Add_Parameters(CSG_Parameters &Parameters)
{
	CSG_Parameter	*pNode;

	//-----------------------------------------------------
	pNode	= Parameters.Add_Node(
		NULL	, "NODE_POS"	, _TL("Position"),
		_TL("")
	);

	Parameters.Add_Value(
		pNode	, "X"			, _TL("X"),
		_TL(""),
		PARAMETER_TYPE_Double	, 0.0
	);

	Parameters.Add_Value(
		pNode	, "Y"			, _TL("Y"),
		_TL(""),
		PARAMETER_TYPE_Double	, 0.0
	);

	Parameters.Add_Value(
		pNode	, "Z"			, _TL("Flying Height"),
		_TL(""),
		PARAMETER_TYPE_Double	, 1000.0
	);

	//-----------------------------------------------------
	pNode	= Parameters.Add_Node(
		NULL	, "NODE_DIR"	, _TL("Orientation"),
		_TL("")
	);

	Parameters.Add_Choice(
		pNode	, "ORIENTATION"	, _TL("Orientation"),
		_TL(""),
		CSG_String::Format(SG_T("%s|%s|"),
			_TL("BLUH"),
			_TL("PATB")
		), 0
	);

	Parameters.Add_Value(
		pNode	, "OMEGA"		, _TL("Omega [degree]"),
		_TL("rotation around the X axis (roll)"),
		PARAMETER_TYPE_Double	, 0.0
	);

	Parameters.Add_Value(
		pNode	, "PHI"			, _TL("Phi [degree]"),
		_TL("rotation around the Y axis (pitch)"),
		PARAMETER_TYPE_Double	, 0.0
	);

	Parameters.Add_Value(
		pNode	, "KAPPA"		, _TL("Kappa [degree]"),
		_TL("rotation around the Z axis (heading)"),
		PARAMETER_TYPE_Double	, 0.0
	);

	Parameters.Add_Value(
		pNode	, "KAPPA_OFF"	, _TL("Kappa Offset [degree]"),
		_TL("origin adjustment for Z axis (heading)"),
		PARAMETER_TYPE_Double	, 90.0
	);

	//-----------------------------------------------------
	pNode	= Parameters.Add_Node(
		NULL	, "NODE_CAMERA"	, _TL("Camera"),
		_TL("")
	);

	Parameters.Add_Value(
		pNode	, "CFL"			, _TL("Focal Length [mm]"),
		_TL(""),
		PARAMETER_TYPE_Double	, 80, 0.0, true
	);

	Parameters.Add_Value(
		pNode	, "PXSIZE"		, _TL("CCD Physical Pixel Size [micron]"),
		_TL(""),
		PARAMETER_TYPE_Double	, 5.2, 0.0, true
	);

	//-----------------------------------------------------
	return( true );
}
//---------------------------------------------------------
bool CPointCloud_From_Text_File::On_Execute(void)
{
	CSG_String				fileName;
	int						iField, iType;
	CSG_String				Name, Types, s;
	CSG_PointCloud			*pPoints;
	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	int						xField, yField, zField, nAttribs;
	bool					bSkipHeader;
	char					fieldSep;
	std::vector<int>		vCol;
	std::ifstream			tabStream;
    std::string				tabLine;
	double					lines;
	long					cntPt, cntInvalid;
	double					x, y, z;


	//-----------------------------------------------------
	fileName	= Parameters("FILE")		->asString();
	xField		= Parameters("XFIELD")		->asInt() - 1;
	yField		= Parameters("YFIELD")		->asInt() - 1;
	zField		= Parameters("ZFIELD")		->asInt() - 1;
	bSkipHeader	= Parameters("SKIP_HEADER")	->asBool();

	switch (Parameters("FIELDSEP")->asInt())
    {
	default:
    case 0: fieldSep = '\t';	break;
    case 1: fieldSep = ' ';		break;
    case 2: fieldSep = ',';		break;
    }

    pPoints	= SG_Create_PointCloud();
    pPoints->Create();
    pPoints->Set_Name(SG_File_Get_Name(fileName, false));
    Parameters("POINTS")->Set_Value(pPoints);
    DataObject_Add(pPoints);


    //-----------------------------------------------------
    if (SG_UI_Get_Window_Main())
    {
        nAttribs	= Parameters("ATTRIBS")		->asInt();

        Types.Printf(SG_T("%s|%s|%s|%s|%s|"),
            _TL("1 byte integer"),
            _TL("2 byte integer"),
            _TL("4 byte integer"),
            _TL("4 byte floating point"),
            _TL("8 byte floating point")
        );

        P.Set_Name(_TL("Attribute Field Properties"));

        for(iField=1; iField<=nAttribs; iField++)
        {
            s.Printf(SG_T("NODE_%03d") , iField);
            pNode	= P.Add_Node(NULL, s, CSG_String::Format(SG_T("%d. %s"), iField, _TL("Field")), _TL(""));

            s.Printf(SG_T("FIELD_%03d"), iField);
            P.Add_String(pNode, s, _TL("Name"), _TL(""), s);

            s.Printf(SG_T("COLUMN_%03d"), iField);
            P.Add_Value(pNode, s, _TL("Attribute is Column ..."), _TL(""), PARAMETER_TYPE_Int, iField+3, 1, true);

            s.Printf(SG_T("TYPE_%03d") , iField);
            P.Add_Choice(pNode, s, _TL("Type"), _TL(""), Types, 3);
        }

        //-----------------------------------------------------
        if( nAttribs > 0 )
        {
            if( Dlg_Parameters(&P, _TL("Field Properties")) )
            {
                for(iField=0; iField<nAttribs; iField++)
                {

                    Name		 = P(CSG_String::Format(SG_T("FIELD_%03d" ), iField + 1).c_str())->asString();
                    iType		 = P(CSG_String::Format(SG_T("TYPE_%03d"  ), iField + 1).c_str())->asInt();
                    vCol.push_back(P(CSG_String::Format(SG_T("COLUMN_%03d"), iField + 1).c_str())->asInt() - 1);

                    pPoints->Add_Field(Name, Get_Data_Type(iType));
                }
            }
            else
                return( false );
        }
    }
    else // CMD
	{
		CSG_String		    sFields, sNames, sTypes;
		CSG_String		    token;
		int				    iValue;
		std::vector<int>	vTypes;


		sFields		= Parameters("FIELDS")->asString();
		sNames		= Parameters("FIELDNAMES")->asString();
		sTypes	    = Parameters("FIELDTYPES")->asString();

		CSG_String_Tokenizer   tkz_fields(sFields, ";", SG_TOKEN_STRTOK);

		while( tkz_fields.Has_More_Tokens() )
		{
			token	= tkz_fields.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			if( !token.asInt(iValue) )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: can't convert to number"));
				return( false );
			}

			iValue	-= 1;

			if( iValue < 1)
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: field index out of range"));
				return( false );
			}
			else
				vCol.push_back(iValue);
		}

		CSG_String_Tokenizer   tkz_datatypes(sTypes, ";", SG_TOKEN_STRTOK);

		while( tkz_datatypes.Has_More_Tokens() )
		{
			token	= tkz_datatypes.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			if( !token.asInt(iValue) )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing field type: can't convert to number"));
				return( false );
			}

			vTypes.push_back(iValue);
		}

		CSG_String_Tokenizer   tkz_datanames(sNames, ";", SG_TOKEN_STRTOK);

        int                 iter = 0;

		while( tkz_datanames.Has_More_Tokens() )
		{
			token	= tkz_datanames.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			pPoints->Add_Field(token, Get_Data_Type(vTypes.at(iter)));

			iter++;
		}

		if( vCol.size() != vTypes.size() || (int)vCol.size() != iter )
		{
		    SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Number of arguments for attribute fields (%d), names (%d) and types (%d) do not match!"), vCol.size(), iter, vTypes.size()));
            return( false );
		}
	}


	// open input stream
    //---------------------------------------------------------
    tabStream.open(fileName.b_str(), std::ifstream::in);
    if( !tabStream )
    {
        SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open input file!")));
        return (false);
    }

	tabStream.seekg(0, std::ios::end);	// get length of file
    lines = (double)tabStream.tellg();
    tabStream.seekg(0, std::ios::beg);

    std::getline(tabStream, tabLine);	// as a workaround we assume the number of lines from the length of the first line
    lines = lines / (double)tabStream.tellg();

	if( !bSkipHeader )
    {
        tabStream.clear();                      // let's forget we may have reached the EOF
        tabStream.seekg(0, std::ios::beg);      // and rewind to the beginning
    }


	// import
    //---------------------------------------------------------
	cntPt = cntInvalid = 0;

	SG_UI_Process_Set_Text(CSG_String::Format(_TL("Importing data ...")));

    while( std::getline(tabStream, tabLine) )
    {
        std::istringstream stream(tabLine);
        std::vector<std::string> tabCols;
        std::string tabEntry;

        if( cntPt%10000 == 0 )
		{
            SG_UI_Process_Set_Progress((double)cntPt, lines);
		}
        cntPt++;

        while( std::getline(stream, tabEntry, fieldSep) )      // read every column in this line and fill vector
        {
            if (tabEntry.length() == 0)
                continue;
            tabCols.push_back(tabEntry);
        }

        if ((int)tabCols.size() < (vCol.size() + 3) )
        {
            SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipping misformatted line: %d!"), cntPt), true);
            cntInvalid++;
            continue;
        }

        //parse line tokens
		std::vector<double> fieldValues;
		fieldValues.resize(vCol.size());

		x = strtod(tabCols[xField].c_str(), NULL);
        y = strtod(tabCols[yField].c_str(), NULL);
        z = strtod(tabCols[zField].c_str(), NULL);

		for( int i=0; i<(int)vCol.size(); i++ )
		{
			fieldValues[i] = strtod(tabCols.at(vCol.at(i)).c_str(), NULL);
		}

		pPoints->Add_Point(x, y, z);

		for( int i=0; i<(int)vCol.size(); i++ )
		{
			pPoints->Set_Attribute(i, fieldValues[i]);
		}
    }

	// finalize
    //---------------------------------------------------------
	tabStream.close();

	CSG_Parameters	sParms;
	DataObject_Get_Parameters(pPoints, sParms);
	if (sParms("METRIC_ATTRIB")	&& sParms("COLORS_TYPE") && sParms("METRIC_COLORS")
		&& sParms("METRIC_ZRANGE") && sParms("DISPLAY_VALUE_AGGREGATE"))
	{
		sParms("DISPLAY_VALUE_AGGREGATE")->Set_Value(3);		// highest z
		sParms("COLORS_TYPE")->Set_Value(2);                    // graduated color
		sParms("METRIC_COLORS")->asColors()->Set_Count(255);    // number of colors
		sParms("METRIC_ATTRIB")->Set_Value(2);					// z attrib
		sParms("METRIC_ZRANGE")->asRange()->Set_Range(pPoints->Get_Minimum(2),pPoints->Get_Maximum(2));
		DataObject_Set_Parameters(pPoints, sParms);
		DataObject_Update(pPoints);
	}

	if (cntInvalid > 0)
        SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %d %s"), _TL("WARNING"), cntInvalid, _TL("invalid points have been skipped")), true);

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%d %s"), (cntPt-cntInvalid), _TL("points have been imported with success")), true);

	return( true );
}
//---------------------------------------------------------
bool CTable_Text_Import_Fixed_Cols::On_Execute(void)
{
    bool			bHeader;
    int				i, nChars, iField, nFields, *iFirst, *iLength;
    CSG_String		sLine;
    CSG_File		Stream;
    CSG_Table		*pTable;

    //-----------------------------------------------------
    pTable	= Parameters("TABLE")		->asTable();
    bHeader	= Parameters("HEADLINE")	->asBool();

    //-----------------------------------------------------
    if( !Stream.Open(Parameters("FILENAME")->asString(), SG_FILE_R, true) )
    {
        Message_Add(_TL("file could not be opened"));

        return( false );
    }

    if( !Stream.Read_Line(sLine) || (nChars = (int)sLine.Length()) <= 0 )
    {
        Message_Add(_TL("empty or corrupted file"));

        return( false );
    }

    //-----------------------------------------------------
    pTable->Destroy();
    pTable->Set_Name(SG_File_Get_Name(Parameters("FILENAME")->asString(), false));

    switch( Parameters("FIELDDEF")->asInt() )
    {
    //-----------------------------------------------------
    case 0:
    {
        CSG_Parameters	*pBreaks	= Get_Parameters("BREAKS");

        pBreaks->Del_Parameters();

        for(i=0; i<nChars; i++)
        {
            pBreaks->Add_Value(NULL,
                               CSG_String::Format(SG_T("%03d"), i),
                               CSG_String::Format(SG_T("%03d %c"), i + 1, sLine[i]),
                               _TL(""), PARAMETER_TYPE_Bool, false
                              );
        }

        if( !Dlg_Parameters("BREAKS") )
        {
            return( false );
        }

        //-------------------------------------------------
        for(i=0, nFields=1; i<pBreaks->Get_Count(); i++)
        {
            if( pBreaks->Get_Parameter(i)->asBool() )
            {
                nFields++;
            }
        }

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(i=0, iField=1; i<pBreaks->Get_Count() && iField<nFields; i++)
        {
            if( pBreaks->Get_Parameter(i)->asBool() )
            {
                iFirst[iField++]	= i + 1;
            }
        }

        //-------------------------------------------------
        for(iField=0; iField<nFields; iField++)
        {
            iLength[iField]	= (iField < nFields - 1 ? iFirst[iField + 1] : (int)sLine.Length()) - iFirst[iField];

            pTable->Add_Field(bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String::Format(SG_T("FIELD%03d"), iField + 1), SG_DATATYPE_String);
        }
    }
    break;

    //-----------------------------------------------------
    case 1:
    {
        CSG_Parameters	*pFields	= Get_Parameters("FIELDS");

        pFields->Del_Parameters();

        nFields	= Parameters("NFIELDS")->asInt();

        for(iField=0; iField<nFields; iField++)
        {
            CSG_String		s		= CSG_String::Format(SG_T("%03d"), iField);
            CSG_Parameter	*pNode	= pFields->Add_Node(NULL, SG_T("NODE") + s, _TL("Field") + s, _TL(""));
            pFields->Add_Value	(pNode, SG_T("LENGTH") + s, _TL("Length"), _TL(""), PARAMETER_TYPE_Int, 1, 1, true);
            //	pFields->Add_Value	(pNode, SG_T("IMPORT") + s, _TL("Import"), _TL(""), PARAMETER_TYPE_Bool, true);
            pFields->Add_Choice	(pNode, SG_T("TYPE")   + s, _TL("Type")  , _TL(""), CSG_String::Format(SG_T("%s|%s|%s|%s|%s|"),
                                 _TL("text"),
                                 _TL("2 byte integer"),
                                 _TL("4 byte integer"),
                                 _TL("4 byte float"),
                                 _TL("8 byte float"))
                                );
        }

        if( !Dlg_Parameters("FIELDS") )
        {
            return( false );
        }

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(iField=0, i=0; iField<nFields && i<nChars; iField++)
        {
            CSG_String		s		= CSG_String::Format(SG_T("%03d"), iField);

            iFirst [iField]	= i;
            iLength[iField]	= pFields->Get_Parameter(SG_T("LENGTH") + s)->asInt();

            i	+= iLength[iField];

            CSG_String		Name	= bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String::Format(SG_T("FIELD%03d"), iField + 1);

            switch( pFields->Get_Parameter(SG_T("TYPE") + s)->asInt() )
            {
            default:
            case 0:
                pTable->Add_Field(Name, SG_DATATYPE_String);
                break;
            case 1:
                pTable->Add_Field(Name, SG_DATATYPE_Short);
                break;
            case 2:
                pTable->Add_Field(Name, SG_DATATYPE_Int);
                break;
            case 3:
                pTable->Add_Field(Name, SG_DATATYPE_Float);
                break;
            case 4:
                pTable->Add_Field(Name, SG_DATATYPE_Double);
                break;
            }
        }
    }
    break;

    //-----------------------------------------------------
    case 2:
    {
        CSG_Table	*pList	= Parameters("LIST")->asTable();

        nFields	= pList->Get_Count();

        //-------------------------------------------------
        iFirst		= new int[nFields];
        iLength		= new int[nFields];

        iFirst[0]	= 0;

        for(iField=0, i=0; iField<nFields && i<nChars; iField++)
        {
            iFirst [iField]	= i;
            iLength[iField]	= pList->Get_Record(iField)->asInt(1);

            i	+= iLength[iField];

            CSG_String		Name	= bHeader ? sLine.Mid(iFirst[iField], iLength[iField]) : CSG_String(pList->Get_Record(iField)->asString(0));

            switch( pList->Get_Record(iField)->asInt(2) )
            {
            case 0:
                pTable->Add_Field(Name, SG_DATATYPE_String);
                break;
            case 1:
                pTable->Add_Field(Name, SG_DATATYPE_Short);
                break;
            case 2:
                pTable->Add_Field(Name, SG_DATATYPE_Int);
                break;
            case 3:
                pTable->Add_Field(Name, SG_DATATYPE_Float);
                break;
            default:
            case 4:
                pTable->Add_Field(Name, SG_DATATYPE_Double);
                break;
            }
        }
    }
    break;
    }

    //-----------------------------------------------------
    if( bHeader )
    {
        Stream.Read_Line(sLine);
    }

    //-----------------------------------------------------
    int		fLength	= Stream.Length();

    do
    {
        if( sLine.Length() == nChars )
        {
            CSG_Table_Record	*pRecord	= pTable->Add_Record();

            for(iField=0; iField<nFields; iField++)
            {
                pRecord->Set_Value(iField, sLine.Mid(iFirst[iField], iLength[iField]));
            }
        }
    }
    while( Stream.Read_Line(sLine) && Set_Progress(Stream.Tell(), fLength) );

    //-----------------------------------------------------
    delete[](iFirst);
    delete[](iLength);

    //-----------------------------------------------------
    return( true );
}