REM  *****  BASIC  *****
Option Explicit

Const FieldOperationLimit = 10

Type SondageOperation
	OpName as String
	OpLocation as String
End Type

Type SondageStatement
	Cond as Integer
	Operand as String
	OpIds() as Integer
End Type

Type SondageField
		Field as String
		ImportFormat as Integer
		Width as Long
		Statements() as SondageStatement
		Values() as String
End Type

Type SondageReport
	Title as String
	Settings() as com.sun.star.PropertyValue
	Fields() as SondageField
End Type

Type SondageConfiguration
	Reports() as SondageReport
	Headers() as String
End Type

' FIXME Remove the 100 hard limit later
Dim OperationTable(100) as SondageOperation
Dim OperationTableLen%

Function ColorRow(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function ColumnOperation(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function ColorCell(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function Delete(ByRef oSheet as Object, oRanges as Variant, sArgs() as String)
	Dim oRange
	For Each oRange In oRanges
		oSheet.removeByIndex(oRange.RangeAddress.StartRow)
	Next oRange
End Function

Sub SondageRegisterFunction(macroLocation$, macroName$)
	OperationTable(OperationTableLen).OpLocation = macroLocation
	OperationTable(OperationTableLen).OpName = macroName
	OperationTableLen = OperationTableLen + 1
End Sub

Function _ReadUntilEndOrCharacter(ByRef sCell$, startIndex%, expect$, ByRef endIndex as Variant) as String
	Dim c$, i%
	c = Left(sCell, startIndex)

	For i = startIndex To Len(sCell)
		If c = expect Then
			_ReadUntilEndOrCharacter = Mid(sCell, startIndex,  i - startIndex - 1)
			endIndex = i
			Exit Function
		End If

		If c = "\n" Or c = ";" Then
			ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'"
			Exit Function
		End If
		c = Mid(sCell, i, 1)
	Next
	_ReadUntilEndOrCharacter = Mid(sCell, startIndex,  i - startIndex)
	endIndex = i - 1
End Function

Function _ReadUntilCharacters(ByRef sCell$, startIndex%, expects() as Variant, ByRef endIndex&) as String
	Dim c$, expect$

	For endIndex = startIndex To Len(sCell)
		c = Mid(sCell, endIndex, 1)
		For Each expect In expects
			If c = expect Then
				_ReadUntilCharacters = Mid(sCell, startIndex,  endIndex - startIndex)
				Exit Function
			End If
			If c = "\n" Or c = ";" Then
				ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'"
				Exit Function
			End If
		Next
	Next
	ErrorLocal$ = "Expected '" & expect & "' but reached end of cell"
End Function

Sub TestSub
	Dim sCell$, colName$
	Dim iCell%
	sCell = "${variable with space} " & CHR(34) & "quoted string" & CHR(34)
	colName = _ReadUntilCharacters(sCell, 3, Array("}"), iCell)
	Print colName
	If ErrorLocal$ <> "" Then
		Print "Some error occurred: " & ErrorLocal
		Exit Sub
	End If
	colName = _ReadUntilCharacters(sCell, iCell +3 , Array(CHR(34)), iCell)
	If ErrorLocal$ <> "" Then
		Print "Some error occurred: " & ErrorLocal
		Exit Sub
	End If
	Print colName
	'If ErrorLocal$ <> "" Then
	'	Print "Some error occurred: " & ErrorLocal
	'	Exit Sub
	'End If
End Sub

Function FunctionCall(colName$, actions)
	Dim action$
	For Each action in actions
		Print colName & " acts on " & action
	Next 'action
End Function

Function TokenDriver(Optional sCell)
	Dim sonVars: sonVars = SondageReadSettings()
	Dim si%: si = 1
	Dim tok$
	Dim tokType$ 'mode
	If IsMissing(sCell) Then sCell = "${OrgCode}_Portln then @Area(.BadStyle @SomeOther Sort-ASCENDING)"
	sCell = SondageExpandVariables(sCell, sonVars)

	Dim sCellLen: sCellLen = Len(sCell)
	tok = GetToken(sCell, si, tokType)
	While tok <> ""
			Select Case tokType
				Case "@"
					Print "Some column types: "& tok
				Case "("
					Print "Open Bracket: " & tok
					Dim fi%: fi = 1
					Dim ftok$, ftokType$
					ftok = GetToken(tok, fi, ftokType)
					While ftok <> ""
						Print ftok
						ftok = GetToken(tok, fi, ftokType)
					Wend
				Case "m"
					Print "mode"
			End Select
			tok = GetToken(sCell, si, tokType)
	Wend
End Function

Function GetToken(sCell$, ByRef si%, ByRef m$) as String
	Dim sonVars: sonVars = SondageReadSettings()
	Dim sonState: SondageStatement: sonState = new SondageStatement
	sCell = SondageExpandVariables(sCell, sonVars)
	Dim sCellLen: sCellLen = Len(sCell)
	Dim c$ 'current char
	Dim endIndex&
	Dim extract$
	Dim func$

	For si = si To sCellLen
		c = Mid(sCell, si, 1)
		If c = "(" Then
			extract = _ReadUntilCharacters(sCell, si + 1, Array(")"), endIndex)
			si = endIndex
			m = "("
			GetToken = extract
		ElseIf c = "@" Or c = "." Then
			m = c
			If si + 1 < sCellLen Then
				si = si + 1
				c = Mid(sCell, si, 1)
				If c = "{" Then
					extract = _ReadUntilCharacter(sCell,  si + 1, "}", endIndex)
				Else
					extract = _ReadUntilCharacters(sCell, si, Array(" ", "(", ""), endIndex)
				EndIf
				If ErrorLocal$ <> "" Or endIndex > sCellLen Then
					Print ErrorLocal$
					Exit Function
				End If
				If m = "@" Then 'Column mode
					Print "Column is '" & extract & "'"
				ElseIf m = "." Then
					Print "Style is '" & extract & "'"
				Else
					Print "Probably a function: " & extract
				End If
				si = endIndex
				GetToken = extract
				Exit Function
			End If
		Else
			m = ""
		End If
	Next 'si
End Function

Function SondageGetOpId(macroName$) as Integer
	Dim i%
	SondageGetOpId = -1
	For i = 0 To OperationTableLen
		If OperationTable(i).OpName = macroName Then
			SondageGetOpId = i
			Exit Function
		End If
	Next
End Function

Function SondageValidateDoc(oDoc as Object, docType$) as String
	Dim _err$ : _err = ""
	If Not oDoc.supportsService(docType) Then
		_err = oDoc.Title & " is not a valid Spreadsheet Document"
	ElseIf oDoc.CurrentController.ViewControllerName = "PrintPreview" Then
		_err = "Cannot run this macro in 'Print Preview', please close it and try again"
	End If
	SondageValidateDoc = _err
End Function

Sub SondageCall(opId%, oSheet, Ranges)
	Dim sonOp as SondageOperation: sonOp = OperationTable(opId)
	Dim script
	script=ThisComponent.scriptProvider.getScript("vnd.sun.star.script:" & sonOp.OpLocation & "."  & sonOp.OpName & "?language=Basic&location=document")
	script.invoke(Array(oSheet, Ranges), Array(), Array())
End Sub

Function SondageInferDocumentType(sonReports, aInputFiles as Variant) as SondageReport
	Dim sonReport as SondageReport
	Dim aMatch, used() as Boolean
	Dim iMatch%, iInputFile%, matched as Boolean, allMatched as Boolean

	For Each sonReport In sonReports
		Dim sMatch$: sMatch = SondageGetPropVal(sonReport.Settings, "Match")
		If sMatch <> "" Then
			aMatch = Split(sMatch, ";")
			If UBound(aMatch) = UBound(aInputFiles) Then
				ReDim used(UBound(aInputFiles))
				allMatched = True
				For iMatch = 0 To UBound(aMatch)
					matched = False
					For iInputFile = 0 To UBound(aInputFiles)
						If Not used(iInputFile) And Trim(aMatch(iMatch)) <> "" Then
							If InStr(LCase(aInputFiles(iInputFile)), LCase(Trim(aMatch(iMatch)))) > 0 Then
								used(iInputFile) = True
								matched = True
								Exit For
							End If
						End If
					Next iInputFile
					If Not matched Then
						allMatched = False
						Exit For
					End If
				Next iMatch
				If allMatched Then
					SondageInferDocumentType = sonReport
					Exit Function
				End If
			End If
		End If
	Next sonReport
End Function

Function SondageImportFiles(sondageReport as SondageReport, aInputFile as Variant, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean) as Variant
	Dim oDocs(0) as Variant
	Dim iInputFile%, sInputFile$
	ReDim oDocs(0 To UBound(aInputFile)) as Variant

	For iInputFile = 0 To UBound(aInputFile)
		sInputFile = aInputFile(iInputFile)
		oDocs(iInputFile) = SondageImportFile(sondageReport, sInputFile, sDocType, returnAlreadyOpenDoc, isHidden)
		If ErrorLocal$ <> "" Then Exit Function
	Next iInputFile
	SondageImportFiles = oDocs
End Function

Function SondageCSVHeader(sLine$) as Variant
	Dim fields() as String, value$, i&, n&, c$
	Dim quoted as Boolean
	ReDim fields(0)
	For i = 1 To Len(sLine)
		c = Mid(sLine, i, 1)
		If c = """" Then
			If quoted And Mid(sLine, i + 1, 1) = """" Then
				value = value & c
				i = i + 1
			Else
				quoted = Not quoted
			End If
		ElseIf c = "," And Not quoted Then
			fields(n) = value
			value = ""
			n = n + 1
			ReDim Preserve fields(n)
		Else
			value = value & c
		End If
	Next i
	fields(n) = value
	SondageCSVHeader = fields
End Function

Function SondageImportOptions(sondageReport as SondageReport, sInputFile$, Optional importAll as Boolean) as String
	Dim firstRow%, fileNum%, i%, j%, formatCode%
	Dim header$, headers, fieldName$, options$
	Dim reportField as SondageField
	Dim onlyConfigured as Boolean
	onlyConfigured = Not importAll And UCase(SondageGetPropVal(sondageReport.Settings, "ImportOnlyConfiguredFields")) <> "FALSE"
	firstRow = 1
	Select Case sondageReport.Title
	Case "INSPECTION", "TUBE", "CONSUMERS", "REFILL": firstRow = 4
	End Select
	Dim configuredRow$: configuredRow = SondageGetPropVal(sondageReport.Settings, "ImportStartRow")
	If configuredRow <> "" Then firstRow = CInt(configuredRow)
	If firstRow < 1 Then
		ErrorLocal$ = "ImportStartRow must be at least 1"
		Exit Function
	End If
	fileNum = FreeFile
	Open sInputFile For Input As #fileNum
	For i = 1 To firstRow
		Line Input #fileNum, header
	Next i
	Close #fileNum
	headers = SondageCSVHeader(header)
	options = "44,34,76," & firstRow & ","
	For i = LBound(headers) To UBound(headers)
		fieldName = UserFriendlyName(headers(i))
		formatCode = 1 ' Calc automatic selection when explicitly opted out
		If onlyConfigured Then formatCode = 9 ' Ignore unlisted CSV fields
		For j = LBound(sondageReport.Fields) To UBound(sondageReport.Fields)
			reportField = sondageReport.Fields(j)
			If reportField.Field = fieldName Then
				formatCode = 1 ' Listed field without a type: automatic selection
				If reportField.ImportFormat <> 0 Then formatCode = reportField.ImportFormat
				Exit For
			End If
		Next j
		If i > LBound(headers) Then options = options & "/"
		options = options & (i + 1) & "/" & formatCode
	Next i
	SondageImportOptions = options
End Function

Function SondageImportFile(sondageReport as SondageReport, sInputFile$, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean, Optional importAll as Boolean) as Variant
	Dim oDoc
	Dim fileUrl
	Dim p(3) as new com.sun.star.beans.PropertyValue
	If IsMissing(isHidden) Then isHidden = True
	
	If returnAlreadyOpenDoc Then
		oDoc = ReturnComponentIfOpen(sInputFile)
		If Not IsNull(oDoc) Then
			If Not oDoc.isReadonly() Then
				SondageImportFile = oDoc
				Exit Function
			End If
		End If
	End If

	p(0).Name = "FilterName"
	p(0).Value = CSV_FILTER_NAME
	p(1).Name = "Hidden"
	p(1).Value = isHidden
	p(2).Name = "FilterOptions"
	' CSV sources may be open read-only; work in a writable, unnamed copy.
	p(3).Name = "AsTemplate"
	p(3).Value = True
	fileUrl = ConvertToUrl(sInputFile)
	If Not FileExists(fileUrl) Then
		ErrorLocal = "Cannot open file '" & fileUrl & "'"
		Exit Function
	End If
	p(2).Value = SondageImportOptions(sondageReport, sInputFile, importAll)
	oDoc = StarDesktop.loadComponentFromURL(fileUrl, "_blank", 0, p())
	' We may check if imported the correct file, by checking the number of columns
	'If oDoc.Sheets(0).Columns.Count = 2 Then
	'	MsgBox "Single column psv"
	'End If

	if IsEmpty(oDoc)Then
		ErrorLocal = "Failed to get Document for " & sInputFile
		Exit Function
	End If
	
	ErrorLocal = SondageValidateDoc(oDoc, sDocType)
	If ErrorLocal <> "" Then
		Exit Function
	End If
	SondageImportFile = oDoc
End Function

Sub SondageGenerateReport(sondageReport, oDoc)
	Print sondageReport.Title
End Sub

Function SondageReadSettings() as Variant
	Dim oDoc
	Dim oSheet
	Dim rangeAddress
	Dim oRange
	Dim iCell%, sKey$, sVal$
	Dim sonVars: sonVars = new Collection
	
	oSheet = ThisComponent.Sheets.getByName("Settings")
	If IsNull(oSheet) Then
		ErrorLocal$ = "Cannot find 'Settings' sheet"
		Exit Function
	End If
	oRange = UsedRangeCursor(oSheet)'.RangeAddress
	rangeAddress = oRange.RangeAddress
	
	For iCell = rangeAddress.StartRow To rangeAddress.EndRow
		sKey = oRange.getCellByPosition(0, iCell).String
		If sKey <> "" Then
			sVal = oRange.getCellByPosition(1, iCell).String
			sonVars.Add(item := sVal, key := sKey)
		End If
	Next 'iCell
	SondageReadSettings = sonVars
End Function

Sub SondageMain()
	Dim sonReports() as Variant
	Dim sonFields() as Variant
	Dim sonReport, sonField, sonStatement
	Dim iOpsLen%, iOp%, opId%
	Dim sInputFile$: sInputFile = "C:\Users\bhara\Desktop\GetPendingOrderConsumerDetailsDateRange(36).csv"
	Dim oDoc, oSheet, oUsedRange

	sonConf = SondageParseFieldConfiguration()
	If ErrorLocal$ <> "" Then
		MsgBox ErrorLocal$, 16
		Exit Sub
	End If
	
	sonReports = sonConf.Reports
	sonReport = SondageInferDocumentType(sonReports, sInputFile)
	oDoc = SondageImportFile(sonReport, sInputFile, True, False)
	
	' Copy the first, sheet if there is only one sheet in document
	If oDoc.Sheets.Count = 1 Then
			oDoc.Sheets.copyByName(oOrigSheet.Name, reportType & "WorkingCopy", 1)
	End If
	oSheet = oDoc.Sheets(1)
	'oSheet = oDoc.getSheets().getByIndex(0)
	oUsedRange = UsedRangeCursor(oSheet)
	If IsNull(oSheet) Then
		MsgBox "Input file is null", 16
		Exit Sub
	End If

	sonFields = sonReport.Fields
	Dim str$

	For Each sonField In sonFields
		'If Not IsEmpty(sonField) Then
		str = sonReport.Title & ": Field Variables: " & sonField.Field & ", with width: " &  sonField.Width & " with " & UBound(sonField.Statements) & " statements"
		For Each sonStatement In sonField.Statements
			iOpsLen = UBound(sonStatement.OpIds)
			str = str & " has condition " & sonStatement.Cond & " for " & sonStatement.Operand & "                  " & "Operations: " & "              " 
			Call SondageFilterColumn(oSheet, endColumn, endRow, "Area", orgCode & "_PortIn", sonStatement.Cond)
			For iOp = 0 To iOpsLen
				opId = sonStatement.OpIds(iOp)
				str = str & opId
				SondageCall(opId, oSheet, oRange)
			Next
			Print str
		Next
	Next
End Sub

Sub SondageFilterColumns(oSheet)
	Dim oFilterDesc
	Dim filterRange, oRange
	Dim oCursor, o, oColumnHeader, oDescriptor
	Dim newColumn : newColumn = endColumn + 1
	Dim oFields(0) as new com.sun.star.sheet.TableFilterField
	Dim filterCount as Long
	Dim filterColumnName as String
	Dim endRow&
	Dim filterContent as Variant, filterOperator as Variant

	If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL
	Print filterOperator

	On Error Goto ErrorHandler

	oRange = oSheet.getCellRangeByPosition(newColumn, 0, newColumn, endRow)
	oColumnHeader = oRange.getCellByPosition(0, 0)
	oColumnHeader.setString("0")	

	oDescriptor = oSheet.createReplaceDescriptor()

	filterRange = GetColumnRange(oSheet, endColumn, endRow, filterColumnName)
	oFilterDesc = filterRange.createFilterDescriptor(True)

	With oFields(0)
		.Field = filterRange.RangeAddress.StartColumn
		.IsNumeric = IsNumeric(filterContent)
		.Operator = filterOperator
		.StringValue = filterContent
		.NumericValue = filterContent
	End With

	oFilterDesc.setFilterFields(oFields())
	oFilterDesc.ContainsHeader = True
	oFilterDesc.UseRegularExpressions = False
	oSheet.filter(oFilterDesc)

	' TODO Check if there is a way to remove the 50,000 limit
	oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 1, 50000)
	SortColumn(oSheet, 0, 1, newColumn, endRow, "0")

ErrorHandler:
	oSheet.filter(oSheet.createFilterDescriptor(True))
	oSheet.Columns.removeByIndex(newColumn, 1)
	Reset
End Sub

Function SondageExpandVariables(sCell$, sonVars as Variant, Optional varType$) as String
	Dim sCellLen: sCellLen = Len(sCell)
	Dim c$
	Dim si%, endIndex as Long
	Dim extract$, varState as Boolean
	
	If IsMissing(varType) Then varType = "$"

	For si = 1 To sCellLen
		c = Mid(sCell, si, 1)
		If c = varType Then
			varState = True
		ElseIf varState = True Then
			c = Mid(sCell, si, 1)
			If c = "{" Then
				extract = _ReadUntilCharacters(sCell,  si + 1, Array("}"), endIndex)
			Else
				extract = _ReadUntilEndOrCharacter(sCell, si, " ", endIndex)
			EndIf
			If ErrorLocal$ <> "" Or endIndex > sCellLen Then
				Print ErrorLocal$
				Exit Function
			End If
			SondageExpandVariables = SondageExpandVariables & sonVars.Item(extract)
			si = endIndex
			varState = False
		Else
			SondageExpandVariables = SondageExpandVariables & c
		End If
	Next 'si
End Function

Function SondageGetCondTypeFromString(opCond$) as Integer
		Dim condType%
		condType = com.sun.star.sheet.ConditionOperator.EQUAL
		SondageGetCondTypeFromString = condType

		If TypeName(opCond) <> "String" or Len(opCond) = 0Then
			condType = com.sun.star.sheet.ConditionOperator.NONE
			Exit Function
		End If

		Select Case opCond
			Case "<="
				condType = com.sun.star.sheet.ConditionOperator.LESS_EQUAL
			Case ">="
				condType = com.sun.star.sheet.ConditionOperator.GREATER_EQUAL
			Case "<>"
				condType = com.sun.star.sheet.ConditionOperator.NOT_EQUAL
			Case "><"
				condType = com.sun.star.sheet.ConditionOperator.BETWEEN
			Case "=="
				condType = com.sun.star.sheet.ConditionOperator.EQUAL
			Case Else
				' Check the first letter
				Select Case Left(opCond, 1)
					Case "<"
						condType = com.sun.star.sheet.ConditionOperator.LESS
					Case ">"
						condType = com.sun.star.sheet.ConditionOperator.GREATER
					Case "+"
						condType = com.sun.star.sheet.ConditionOperator.FORMULA
				End Select
		End Select
		 SondageGetCondTypeFromString = condType
End Function

Function _RemoveAllPrivateNamedRanges()
	Dim aNamedRanges, sNamedRange, i%
	aNamedRanges = ThisComponent.NamedRanges
	For i = 0 To aNamedRanges.getCount() - 1
		sNamedRange = aNamedRanges.getByIndex(i).Name
		If  InStr(1, sNamedRange, "Sondage_", 0) = 1 Then  ' sNamedRange starts with Sondage
			aNamedRanges.removeByName(sNamedRange)
		End If
	Next i
End Function

Function SondageParseFieldConfiguration() as SondageConfiguration
	Dim reportNames, aValues
	Dim oDoc, oSheet, oRange, oSearchRange
	Dim startRow&, endRow&, endColumn&, iRow&, iCol&
	Dim sCell, oCell
	
	' Used for ReDim Statements and Fields
	Dim sonConf as SondageConfiguration
	Dim sonReports() as SondageReport
	Dim sonStatements() as Variant
	Dim sonFields() as Variant
	Dim sonSettings() as Variant
	Dim opIds() as Integer

	' Remove OperationLimit later
	Dim stTokens(200) as String

	Dim sonReport as new SondageReport
	Dim sonField as new SondageField
	Dim sonStatement as new SondageStatement

	Dim iWidth
	Dim sStatements() as String, aHeaders() as String, sStatement$, sWidth$, opCond$
	Dim opTokens() as String

	SondageRegisterFunction("Standard.Sondage", "Select")
	' TODO Stub operation delete later
	' This is probably the modern verision of VLOOKUP that is based on column name
	' If something exists like this in Excel or Calc, just use its name
	SondageRegisterFunction("Standard.Sondage", "ColumnOperation")
	SondageRegisterFunction("Standard.Sondage", "ColorCell")
	SondageRegisterFunction("Standard.Sondage", "ColorRow")
	SondageRegisterFunction("Standard.Sondage", "Delete")

	oDoc = ThisComponent
	oSheet = oDoc.getSheets().getByName("FieldConfiguration")

	oRange = UsedRangeCursor(oSheet)
	startRow = 0
	endRow = oRange.RangeAddress.EndRow
	endColumn = oRange.RangeAddress.EndColumn

	ReDim Preserve aHeaders(endColumn) as String
   	For iCol = 0 To endColumn
   		aHeaders(iCol) = oSheet.getCellByPosition(iCol, iRow).getString()
   	Next iCol

	For iRow = startRow To endRow
		oCell = oSheet.getCellByPosition(0, iRow)
		sCell = oCell.getText().String
		If Left(sCell, 1) = "[" Then
			ReDim Preserve sonReports(UBound(sonReports) + 1) as SondageReport
			sonReport = sonReports(UBound(sonReports))
			sonReport.Fields = Array()
			sonReport.Settings = Array()
			' TODO Restrict the Title to certain values
			sonReport.Title = Mid(sCell, 2, Len(sCell) - 2)
			oCell.CellStyle = "Heading1"
			'Print sonReport.Title
		ElseIf Len(sonReport.Title) <> 0 Then
			If Left(sCell, 1) = "@" Then
				sonField = new SondageField
				Dim fieldSpec$, typePos&
				fieldSpec = Mid(sCell, 2)
				typePos = InStr(fieldSpec, ":")
				If typePos > 0 Then
					sonField.Field = Left(fieldSpec, typePos - 1)
					Select Case UCase(Mid(fieldSpec, typePos + 1))
					Case "TEXT": sonField.ImportFormat = 2
					Case "NUMBER", "AUTO": sonField.ImportFormat = 1
					Case "MM/DD/YY": sonField.ImportFormat = 3
					Case "DD/MM/YY": sonField.ImportFormat = 4
					Case "YY/MM/DD": sonField.ImportFormat = 5
					Case Else
						ErrorLocal$ = "Unknown import type in " & sCell
						Exit Function
					End Select
				Else
					sonField.Field = fieldSpec
				End If

				aValues = sonField.Values
				ReDim aValues(endColumn)
			   	For iCol = 0 To endColumn
			   		aValues(iCol) = oSheet.getCellByPosition(iCol, iRow).getString()
			   	Next iCol
			   	sonField.Values = aValues

				sonField.Statements = Array()
				sStatements = Split( _
					Trim(oSheet.getCellByPosition(1, iRow).getText().String), _
					CHR(13) _
				)
				sWidth = oSheet.getCellByPosition(2, iRow).getText().String
				If sWidth = "0" Then
					iWidth = 0
				ElseIf sWidth = "-1" or Len(sWidth) = 0 Then
					' Mark for deletion
					iWidth = -1
				Else
					iWidth = CLng(sWidth)
				End If
				sonField.Width = iWidth
				For Each sStatement In sStatements
						Dim ci: ci = 0
						Dim c$, pc$
						
						For ci = 1 To Len(sStatement)
							c = Mid(sStatement, ci, 1)
							If c = "$" Then
								' Read the rest of the word and store in a variable
								' This variable should be replaced with content from a collection above
								' Essentially implementing a variable like function
							End If
						Next
					stTokens = Split(sStatement, " then ")
					sonStatement = new SondageStatement

					Dim stToken
					Dim opToken$

					If UBound(stTokens) = 0 Then
						' Operand Only
						sonStatement.Operand = Trim(stTokens(0))
						'Print sonReport.Title & "Operand Only: " & stTokens(0)
						opTokens = Array()
					ElseIf UBound(stTokens) > 0 Then
						' Cond then Op
						opCond = Left(stTokens(0), 2)
	
						sonStatement.Cond = SondageGetCondTypeFromString(opCond)

						If sonStatement.Cond = com.sun.star.sheet.ConditionOperator.EQUAL Then
							sonStatement.Operand = Trim(stTokens(0))
						Else
							sonStatement.Operand = Trim(Right(stTokens(0),  Len(stTokens(0)) - 2) )
						End If
					End If 'UBound(stTokens)

					' After Reading the condition, save the operation after finding the Id
					If UBound(stTokens) > 0 Then
						opTokens = Split(stTokens(1), ",")
						For Each opToken In opTokens
							Dim opPureTokens() as String
							Dim opPureToken$
							Dim sonOpId%: sonOpId = -1
							opPureTokens = Split(Trim(opToken), "(")
							If UBound(opPureTokens) = -1 Then
								ErrorLocal$ = "FATAL: Error in row: " & iRow & ",  Operation is malformed"
								Exit Function
							End If
							opPureToken = Trim(opPureTokens(0))
							If Left(opPureToken, 1) = "@" Then
								Print "This is a @ column thing: " & opPureToken
								' TODO Construct optoken and id and push the instructions to list
								' FIXME This does not do much now
								sonOpId = SondageGetOpId("ColumnOperation")
							Else
								sonOpId = SondageGetOpId(opPureToken)
							End If
							If sonOpId = -1 Then
								ErrorLocal$ = "FATAL: Cannot retrieve the operation " & opPureToken & " in row " & iRow
								Exit Function
							End If
							opIds = sonStatement.OpIds
							ReDim Preserve opIds(UBound(sonStatement.OpIds) + 1) as Integer
							sonStatement.OpIds = opIds
							sonStatement.OpIds(UBound(sonStatement.OpIds)) = sonOpId
						Next 'opToken
					Else
						opTokens = Array(0)
					End If

					sonStatements = sonField.Statements
					ReDim Preserve sonStatements(UBound(sonField.Statements) + 1) as Variant
					sonField.Statements = sonStatements
					sonField.Statements(UBound(sonField.Statements)) = sonStatement
				Next	 'sOp

				sonFields = sonReport.Fields
				ReDim Preserve sonFields(UBound(sonFields) +  1) as Variant
				sonReport.Fields = sonFields
				sonReport.Fields(UBound(sonReport.Fields)) = sonField
			Else ' If != [ and != @
				sonSettings = sonReport.Settings
				ReDim Preserve sonSettings(UBound(sonSettings) + 1) as Variant
				sonSettings(UBound(sonSettings)) = CreateObject("com.sun.star.beans.PropertyValue")
				sonSettings(UBound(sonSettings)).Name = sCell
				sonSettings(UBound(sonSettings)).Value = oSheet.getCellByPosition(1, iRow).getText().String
				oCell.CellStyle = "Card"
				sonReport.Settings = sonSettings
			End If
		Else
			MsgBox "Syntax Error: should start with [HEADER] element", 16
			Exit Function
		End If
	Next 'iRow
	sonConf.Reports = sonReports
	sonConf.Headers = aHeaders
	SondageParseFieldConfiguration = sonConf
End Function

