: bharatvaj/lobasic-macros

LibreOffice macros I use often

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

'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

'1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

'2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
'disclaimer in the documentation and/or other materials provided with the distribution.

'3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
'products derived from this software without specific prior written permission.

'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
'ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
'DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
'FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
'DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
'SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
'AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Option VBASupport 1
Option Explicit

Type SondageSettings
	oFieldAliasesRange as Variant
End Type

Type SondageContext
	oDoc as Variant
	oSheet as Variant
	oRange as Variant
	headerRow&
	startColumn&
	startRow&
	endColumn&
	endRow&
End Type

Private GlobalSondageSettings as New SondageSettings

' Options read from sheet

Private orgCode As String
Private exportPrefix As String
' Allowed values,
' EKYC, PENDING, INSPECTION,  SBC, POPULATE
'The number of columns that are copied and the column size will be affected
Private reportType As String
Private inputType As String
'Holds filter information such as ONLINE
Private reportFilter As String
' The days below 'thorgCodee maximum date in report' to show as bad
Private priorityThreshold As Integer
Private highlightColor As Long
Private priorityColor As Long
Private isHeadless As Boolean
Private isDBRequired as Boolean
' True if you want to create sheets with Area specific data
Private enableGroupReports As Boolean
Private organizeInputsFolder as String
Private removeInputFileAfterSuccess as Boolean
Private gvtSoftwareFolder$
Private debugInputFile$
Private customerDBFile$
Private shouldSyncWithGVT as Boolean
Private ErrorLocal$
Private pendingRemarksValidateList$
Private ekycRemarksList$

Private stateName As String
Private cityName As String

Global Const highlightBasedOn = "Payment Option" ' A yellow background is drawn that matches this column and 'highlightSearchString'
Global Const highlightSearchString = "Online" ' Does partial match
Global Const highlightRemoveColumn = True ' True if you want remove the column once the highlight is done
Global Const shouldRunSubtotals = True
Global Const shouldExportPDF = True ' If True this will export all the created sheets with Area specific data individually TODO change name to easily understand
Global Const shouldExportSummaryEditable = True ' If True this will export summary editable
'Private shouldExportSummaryPDF as Boolean' If True the first page will be exported as PDF
Global Const shouldCreateDataPivot = False
Global Const CURRENCY_UNIT = ""

Global Const CSV_FILTER_NAME = "Text - txt - csv (StarCalc)"

' Refer https://help.libreoffice.org/latest/en-US/text/shared/guide/csv_params.html
Global Const PENDING_CSV_FILTER_OPTIONS = "44,34,76,1,5/9/6/4/7/1/8/9/9/9/10/9"
' Values are loaded from the document
' Move all these to SondageContext? Which contain sheet, {start,end}{Column,Row} and others common things
Private tillDate As Date
Private tillDateStr As String
Private fromDate As Date
Private fromDateStr As String
Private sheetNameSuffix As String
Private exportDestDir As String

Sub CleanupProductCode(oSheet as Object, endColumn as Long, endRow as Long)
	MsgBox "Not implemented: productNames"
End Sub

Sub IterateTableAndAct()
	' Call it Sub-table in Sondage
	' Segregate Sondage as sondage-basic, sondage-db, etc?
	Dim oDoc, oSheet, oCell
	Dim iRow&, startColumn%
    Dim oCursor As Object
    Dim oTableRange As Object
    Dim nLastRow As Long
    Dim nRow As Long
    Dim tableCount As Integer
    
    oDoc = ReturnComponentIfOpen("C:\Users\bhara\Downloads\ViewTransactionDetail.csv")
    If IsNull(oDoc) Then
    	Print "Error opening Transaction Details"
    	Exit Sub
    End If
    oSheet = oDoc.getSheets().getByIndex(0)
    
    ' 1. Find the final used row on the entire sheet to know when to stop looping
    oCursor = oSheet.createCursor()
    oCursor.gotoEndOfUsedArea(False)
    nLastRow = oCursor.RangeAddress.EndRow
    
    tableCount = 0
    nRow = 0
    
    ' 2. Loop down Column A to find individual tables
    Do While nRow <= nLastRow
        oCell = oSheet.getCellByPosition(0, nRow)

        If oCell.Type <> com.sun.star.table.CellContentType.EMPTY Then
            tableCount = tableCount + 1
            oCursor = oSheet.createCursorByRange(oCell)
            oCursor.collapseToCurrentRegion() 
			oTableRange = oCursor.RangeAddress

            'MsgBox "Found Table " & tableCount & " at Range: " & oTableRange.StartRow

            Dim oCurrentCell, sCurrentCell
            oCurrentCell = oSheet.getCellByPosition(oTableRange.startColumn, oTableRange.startRow)
            sCurrentCell = oCurrentCell.getString()
            If InStr(sCurrentCell, "ConsumerNumber") Then
            	Act1(oSheet, oTableRange)
            End If

            nRow = oCursor.RangeAddress.EndRow + 1
        Else
            ' Move to the next row if this one is empty
            nRow = nRow + 1
        End If
    Loop
    
    MsgBox "Finished! Total tables found: " & tableCount
End Sub

Function SondageContextSetRange(ByRef ctx as SondageContext, oRangeAddr, Optional hasHeader as Boolean)
	If IsMissing(hasHeader) Then hasHeader = True
	ctx.headerRow = oRangeAddr.StartRow
	ctx.startColumn = oRangeAddr.startColumn
	ctx.startRow = IIf(hasHeader, oRangeAddr.StartRow + 1, oRangeAddr.StartRow)
	ctx.endColumn = oRangeAddr.endColumn
	ctx.endRow = oRangeAddr.endRow
End Function

Function Act1(oSheet, oRangeAddr)
	Dim ctx as SondageContext
	Dim iRow&
	Dim iMainColumn%
	ctx.oSheet = oSheet
	SondageContextSetRange(ctx, oRangeAddr)
	' TODO Make this more flexible with regex, so this can
	' be set easily in the sheet
	iMainColumn = GetHeaderPosition(ctx, "ConsumerNumber", True)

	If iMainColumn = -1 Then Exit Function
	For iRow = ctx.startRow To ctx.endRow
		Print ctx.oSheet.getCellByPosition(iMainColumn, iRow).getString()
	Next iRow
End Function

Function CreatePivotForRefill(ByRef ctx as SondageContext, ByRef sonConf as SondageConfiguration, oDestSheet)
	Dim oTables, oTDescriptor, oFields, oField, iField%
	Dim oCellAddress as new com.sun.star.table.CellAddress

	oCellAddress.Sheet = oDestSheet
	oCellAddress.Column = 0
	oCellAddress.Row = 0
	
	oTables = ctx.oSheet.getDataPilotTables()
	oTDescriptor = oTables.createDataPilotDescriptor()
	oTDescriptor.setSourceRange(ctx.oRange.getRangeAddress())

	oFields = oTDescriptor.getDataPilotFields()
	
	iField = GetHeaderPosition("Operator Name")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.ROW
	
	iField = GetHeaderPosition("Type")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.COLUMN

	iField = GetHeaderPosition("Cylinder Qty")
	oField = oFields.getByIndex(iField)
	oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.DATA
	oField.Function = com.sun.star.sheet.GeneralFunction.SUM
	
	oTables.insertNewByName("REFILLDataPilot", oCellAddress, OTDescriptor)
End Function

Function ReadSettings() as Boolean	
	Dim oDoc
	Dim oSheet
	Dim rangeAddress
	Dim oRange
	ReadSettings = False
	
	oSheet = ThisComponent.Sheets.getByName("Settings")
	rangeAddress = UsedRangeCursor(oSheet).RangeAddress
	oRange = oSheet.getCellRangeByPosition(0, 0, rangeAddress.EndColumn, rangeAddress.EndRow)

	isHeadless = True
	' Organization Details
	orgCode = GetValueForKey(oRange, "OrgCode").String
	stateName = GetValueForKey(oRange, "StateName").String
	cityName = GetValueForKey(oRange, "CityName").String
	highlightColor = GetValueForKey(oRange, "HighlightColor").CellBackColor
	reportType = GetValueForKey(oRange, "ReportType").String
	reportFilter = GetValueForKey(oRange, "ReportFilter").String
	exportPrefix = GetValueForKey(oRange, "ExportFolder").String
	priorityThreshold = CInt(GetValueForKey(oRange, "PriorityThreshold").String)
	priorityColor = GetValueForKey(oRange, "PriorityColor").CellBackColor
	enableGroupReports = CBool(GetValueForKey(oRange, "EnableGroupReports").String)
	organizeInputsFolder = GetValueForKey(oRange, "OrganizeInputsFolder").String
	removeInputFileAfterSuccess = CBool(GetValueForKey(oRange, "RemoveInputFileAfterSuccess").String)
	gvtSoftwareFolder = GetValueForKey(oRange, "GVTSoftwareFolder").String
	debugInputFile = GetValueForKey(oRange, "DebugInputFile").String
	customerDBFile = GetValueForKey(oRange, "CustomerDBFile").String
	shouldSyncWithGVT = GetValueForKey(oRange, "ShouldSyncWithGVT").String
	pendingRemarksValidateList = GetValueForKey(oRange, "PendingRemarksValidateList").String
	ekycRemarksList = GetValueForKey(oRange, "EkycRemarksList").String
	' Skip check if the path is not given
	If shouldSyncWithGVT Then
		If Not FileExists(gvtSoftwareFolder) Then
			MsgBox "Please enter correct one and rerun the macro", 16, "Given GVT Advance Path does not exist"
			Exit Function
		End If
	End If

	'If IsNull(oCell) Then
	'	MsgBox "Setting not found, throw error"
	'	Exit Sub
	'End If
	ReadSettings = True
End Function

Function CreateValidationList(ctx as SondageContext, columnName$, sValidationList)
	Dim oValidation, oRange, oCell
	Dim aItems, sFirstItem$,finalFormula$
	oRange = GetColumnRange(ctx, columnName)

	Dim listDelim: listDelim = CHR(10)

	oValidation = oRange.Validation
	oValidation.Type =  com.sun.star.sheet.ValidationType.LIST
	aItems = Split(sValidationList, listDelim)

	If LBound(aItems) <> -1 Then
		sFirstItem = aItems(LBound(aItems))
	Else
		sFirstItem = sValidationList
	End If

	oCell = oRange.getCellByPosition(0, 0)
	oCell.setString(sFirstItem)
	
	oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 0, ctx.endRow)

    finalFormula = """" & Join(Split(sValidationList, listDelim), """;""") & """"
	oValidation.setFormula1(finalFormula)
	oRange.Validation = oValidation
End Function

Function ValidateDoc(oDoc as Object, docType$) as String
	Dim _err$ : _err = ""
	if IsEmpty(oDoc)Then
		_err = "Failed to get Document for " & sInputFile
	ElseIf Not oDoc.supportsService(docType) Then
		_err = sInputFile & " 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
	ValidateDoc = _err
End Function

Function AssertColumn(ctx as SondageContext, sCol$) as Boolean
	Dim iCol%
	AssertColumn = True
	iCol =  GetHeaderPosition(ctx, sCol)
	If iCol = -1 Then
		ErrorLocal$ = "Cannot proceed, " & sCol & " column is " & iCol
		AssertColumn = False
	End If
End Function

Function SondageAppendColumn(ByRef ctx as SondageCtx, sColumnName$)
		Dim oCell
		Dim oRange
		ctx.endColumn = ctx.endColumn + 1
		'ctx.oSheet.getColumns().insertByIndex(ctx.endColumn, 1)
		oCell = ctx.oSheet.getCellByPosition(ctx.endColumn, 0)
		oCell.setString(sColumnName)
		oRange = GetColumnRange(ctx, sColumnName)
		oCell.CellStyle = "Heading 1"
End Function

Function GetColumnSettings(sheetName$) as Boolean
	Dim oDoc, oSheet
	GetColumnSettings = False
	oDoc = ThisComponent
	oSheet = oDoc.getSheets().getByName(sheetName)
	If IsNull(oSheet) Then Exit Function
End Function

Function SondageGetContext(oSheet as Variant) as SondageContext
	Dim ctx as New SondageContext
	ctx.oSheet = oSheet
	ctx.oDoc = oSheet.DrawPage.Forms.Parent
	ctx.oRange = UsedRangeCursor(oSheet)
	ctx.headerRow = 0
	ctx.startColumn = 0
	ctx.startRow = 1
	ctx.endRow = ctx.oRange.RangeAddress.EndRow
	ctx.endColumn = ctx.oRange.RangeAddress.EndColumn
	SondageGetContext = ctx
End Function

Function SondageJoinVertical(ctx as SondageContext, sIdColumn$)
    Dim i&: i = 1
    Dim iIdColumn%: iIdColumn = GetHeaderPosition(ctx, sIdColumn)
    ' TODO Add mismatching content as array, rather than discarding them entirely
    For i = ctx.startRow To ctx.endRow
        With ctx.oSheet
            If .getCellByPosition(iIdColumn, i).String = .getCellByPosition(iIdColumn, i + 1).String Then
                .getRows().removeByIndex(i + 1, 1)
                ctx.endRow = ctx.endRow - 1
            End If
        End With
    Next
End Function

Function RemoveRows(ByRef ctx as SondageContext, rowsToRemove&)
	If rowsToRemove <> 0 Then
		ctx.oSheet.getRows().removeByIndex(0, rowsToRemove + 1)
		' FIXME Check this calculation again, this could be reason, West Mambalam is
		' not appearing on the list sometimes
		ctx.endRow = ctx.endRow - (rowsToRemove + 1)
	End If
End Function

Function SondageConditionalHorizontalCopy(ctx as SondageContext, sDstColumn$, sSrcColumn$)
    iSrcColumn = GetHeaderPosition(ctx, sSrcColumn)
    iDstColumn = GetHeaderPosition(ctx, sDstColumn)

    Dim i&: i = 1
    ' Remove duplicates, Move value from 'Phone' if "Mobile' has no value
    For i = ctx.startRow To ctx.endRow
    With ctx.oSheet
        If .getCellByPosition(iDstColumn, i).Value = 0 Then
            .getCellByPosition(iDstColumn, i).Value = .getCellByPosition(iSrcColumn, i).Value
        End If
    End With
    Next i
End Function

Function SondageInit(oDoc)
	Dim oFieldAliasesSheet as Variant
	oFieldAliasesSheet = oDoc.getSheets().getByName("FieldAliases")

	GlobalSondageSettings.oFieldAliasesRange = UsedRangeCursor(oFieldAliasesSheet)
End Function

Function SondageGetPropVal(aContainer, sProp$, Optional sDefaultValue) as String
	Dim oParent
	On Error Goto ErrorHandler
	For Each oParent In aContainer
		     If oParent.Name = sProp Then
		     	SondageGetPropVal = oParent.Value
		     	Exit Function
		     End If
	Next oParent
	ErrorHandler:
	If Not IsMissing(sDefaultValue) then SondageGetPropVal = sDefaultValue
End Function

Function SondageReflectionQuickAccess(aContainer, sProp$, oVal, Optional callByNameArg%) as Variant
	Dim oParent
	If IsMissing(callByNameArg) Then callByNameArg = 2 ' 2 = Get operation	
	On Error Goto ErrorHandler
	For Each oParent In aContainer
	        Dim propertyValue
		    propertyValue = CallByName(oParent, sProp, callByNameArg)  
		     If propertyValue = oVal Then
		     	SondageReflectionQuickAccess = oParent
		     	Exit Function
		     End If
	Next oParent
	ErrorHandler:
End Function

Function GetHeaderIndex(aHeader, sProperty$) as Long
	Dim i%
	GetHeaderIndex = -1
	For i = LBound(aHeader) To UBound(aHeader)
		If aHeader(i) = sProperty Then
			GetHeaderIndex = i
			Exit Function
		End If
	Next i
End Function

Function SondageTransformSheet(ctx, sonConf, reportType, sWidthColumn$)
	Dim i%, iWidthColumn%, sWidth$
	Dim sField$
	Dim aReports, oReport

	aReports = sonConf.Reports
	oReport = SondageReflectionQuickAccess(aReports, "Title", reportType)

	' TODO Throw error
	If IsEmpty(sonConf) Then Exit Function

	iWidthColumn = GetHeaderIndex(sonConf.Headers, sWidthColumn)

	Dim aColumns2D(UBound(oReport.Fields), 1)
	For i = 0 To UBound(oReport.Fields)
		sField = oReport.Fields(i).Field
		aColumns2D(i, 0) = oReport.Fields(i).Field
		sWidth = oReport.Fields(i).Values(iWidthColumn)
		If sWidth <> "" Then
			aColumns2D(i, 1) = CLng(sWidth)
		End If
	Next i
	SondageRestructureColumns(ctx, aColumns2D)
End Function

Sub _SondageTransformSheet(ctx, reportType$)
	Dim oDoc
	'TODO This should be set through GroupHeader logic
	oDoc = ctx.oDoc

	If reportType = "PENDING" Then
		ApplyTheme(oDoc, "millennium.ots")
		RemoveColumnsExcept(ctx, Array( _
			"Area", _
			"Address", _	
			"ID", _
			"Name", _
			"Mobile", _
			"Book", _
			"Payment Option", _
			"Code" _
		))

		SetWidths(ctx, Array( _
				Array("Area", 0), _
				Array("ID", 0), _
				Array("Code", 1000), _
				Array("Name", 7000), _
				Array("Mobile", 0), _
				Array("Book", 0) _
		))
	ElseIf reportType = "INSPECTION" Then
			ApplyTheme(oDoc, "green_grapes.ots")
			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
	ElseIf reportType = "TUBE" Then
			ApplyTheme(oDoc, "pumpkin.ots")
			endColumn = RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
	))
	ElseIf reportType = "REFILL" Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"ID", _
				"Name", _
				"Code", _
				"Operator Name" _
			))
			'"Block Reason" _
		SetWidths(ctx, Array( _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Code", 2000), _
				Array("Operator Name", 4000) _
		))
	ElseIf reportType = "DORMANT" Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			'"Block Reason" _
			SetWidths(ctx, Array( _
				Array("Area", 1000), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 2000) _
			))
	ElseIf reportType = "SBC"Then
		ApplyTheme(oDoc, "pumpkin.ots")
		RemoveColumnsExcept(ctx, Array( _
				"ID", _
				"Name", _
				"Address", _
				"Mobile", _
				"Area", _
				"No Of Cylinder" _
			))
			SetWidths(ctx, Array( _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 0), _
				Array("Area", 0) _
			))
		ElseIf reportType = "EKYC" Then
			ApplyTheme(oDoc, "nature.ots")
			enableGroupReports = True

			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			SetWidths(ctx, Array( _
				Array("Area", 2000), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8500), _
				Array("Mobile", 2000) _
			))
		ElseIf reportType = "VIP" Then
			ApplyTheme(oDoc, "green_grapes.ots")
			RemoveColumnsExcept(ctx, Array( _
				"Area", _
				"ID", _
				"Name", _
				"Address", _
				"Mobile" _
			))
			SetWidths(ctx, Array( _
				Array("Area", 0), _
				Array("ID", 0), _
				Array("Name", 3000), _
				Array("Address", 8000), _
				Array("Mobile", 0) _
			))
		Else
			ErrorLocal$ = "Unknown reportType: '" & reportType & "'"
			Exit Sub
	End If
End Sub

Function SegregateEKYCDoneOnline()
	' Array
End Function

Sub Main(Optional sInputFiles as Variant)
	Dim aInputFiles, sInputFile$
	Dim aDoc as Variant, oDoc, oDBDoc, oDispatcher
	Dim oOrigSheet, oSheet, oDBSheet, oSheets as Object
	Dim oCursor, oTextCursor
	Dim sonConf, sonReport, aSettings

	Dim sTheme$, badStyleName$
	Dim idColumn%, mobileColumn%, phoneColumn%, addressColumn%, nameColumn%
	Dim groupByColumn%, areaNames as New Collection
	Dim rowsToRemove%
	Dim highlightedCount as Integer, formatNum as Integer
	Dim idRange, bookRange, nameRange
	Dim dColumns as Object
	Dim headerRange as Object
	Dim statusBar as Variant
	Dim ctx as New SondageContext
	Dim dbCtx as New SondageContext
	Dim sGroupBy$, iGroupByColumn%

	Dim cellRangeToCopy as Object
	Dim pageStyle as Object
	Dim oLocale as new com.sun.star.lang.Locale
	
	' Setup args
	aInputFiles = Split(sInputFiles, ";")

	' Initialize Globals
	SondageInit(ThisComponent)
	If Not ReadSettings() Then Exit Sub
	' TODO Move this to read settings?
	sonConf = SondageParseFieldConfiguration()
	If ErrorLocal$ <> "" Then Goto ErrorHandler

	' Use today's date without rounding the time into tomorrow.
	tillDate = Date()
	badStyleName = "T4"
	enableGroupReports = True

	For Each sInputFile in aInputFiles
		If IsMissing(sInputFile) Or TypeName(sInputFile) <> "String" Then
			If debugInputFile <> "" Then
				sInputFile = debugInputFile
				isHeadless = False
			Else
				MsgBox "Please give an input file", 16, "No input given"
				GoTo FinalFallback
			End If
		End If
	Next sInputFile
	
	sInputFile = aInputFiles(0)

	sonReport = SondageInferDocumentType(sonConf.Reports, aInputFiles)
	If IsEmpty(sonReport) Then
		ErrorLocal = "Cannot infer report configuration for '" & sInputFile & "'"
		Goto ErrorHandler
	End If
	inputType = sonReport.Title

	If reportType = "AUTO" Then
		reportType = inputType
	End If

	aSettings = sonReport.Settings
	sGroupBy = SondageGetPropVal(aSettings, "GroupBy")

	'If reportType = "PENDING" Then
	'	isDBRequired = True
	'End If

	If isDBRequired Then
		oDBDoc = SondageImportFile(sonReport, customerDBFile, "com.sun.star.sheet.SpreadsheetDocument", True, False, True)
		If ErrorLocal$ <> "" Then Goto ErrorHandler
	End If
	
	' FIXME The isHidden = False value is hardcoded, but use value from settings
    aDoc = SondageImportFiles(sonReport, aInputFiles, "com.sun.star.sheet.SpreadsheetDocument", True, False)
	If ErrorLocal$ <> "" Then Goto ErrorHandler
	oDoc = aDoc(0)
	statusBar = oDoc.CurrentController.StatusIndicator

	If oDoc.CurrentController.hasFrozenPanes() Then
		Call UnFreezeSelection(oDoc)
	End If

	ctx = SondageGetContext(oDoc.Sheets(0))

	If ctx.oSheet.IsProtected Then
		ctx.oSheet.Unprotect(reportType)
	End If

	' EKYC starts with its header on line 1; never discard it as a preamble.
	If reportType <> "EKYC" Then
		rowsToRemove = NaiveLastTable(ctx)
		RemoveRows(ctx, rowsToRemove)
	End If

	'If oDoc.Sheets.Count <> 1 Then oDoc.Sheets.removeByName("CONSUMERSWorkingCopy")

	' Copy the first, sheet if there is only one sheet in document
	If oDoc.Sheets.Count = 1 Then
		If shouldCreateDataPivot = False Then
			oDoc.Sheets.copyByName(ctx.oSheet.Name, reportType & "WorkingCopy", 1)
		End If
	End If

	oDoc.lockControllers()
	' Register Styles
	SetCustomBadStyle(oDoc, oLocale, badStyleName) : If ErrorLocal$ <> "" Then Goto ErrorHandler

	ctx.oSheet.Protect(reportType)

	If isDBRequired Then
		dbCtx = SondageGetContext(oDBDoc.Sheets(0))
		Call CleanColumnHeaders(dbCtx)
	End If

	ctx = SondageGetContext(oDoc.Sheets(1))

	If ctx.oSheet.Name = reportType & "WorkingCopy" Then
		' It's not possible to create a style even if only one sheet is blocked
		Call CleanColumnHeaders(ctx)
	End If

	iGroupByColumn = GetHeaderPosition(ctx, sGroupBy)
	If iGroupByColumn = -1 Then
		ErrorLocal$ = "Cannot proceed, '" & sGroupBy & "' column not found"
		Goto ErrorHandler
	End If
	If iGroupByColumn > 0 Then
		ctx.oSheet.getColumns().insertByIndex(0, 1)
		ctx.oSheet.moveRange(ctx.oSheet.getCellByPosition(0, 0).CellAddress, _
			ctx.oSheet.getCellRangeByPosition(iGroupByColumn + 1, 0, iGroupByColumn + 1, ctx.endRow).RangeAddress)
		ctx.oSheet.getColumns().removeByIndex(iGroupByColumn + 1, 1)
		ctx = SondageGetContext(ctx.oSheet)
	End If

	' FIXME Enable normal Consumer List Generation Later
	 If shouldSyncWithGVT Then
		ReducedPopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet)
		'PopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet)
		GoTo FinalFallback
	End If

	'Call CleanupProductCode(ctx, endRow)

	' Filter - Remove unrequired fields
	If reportType = "INSPECTION" Then
		Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
		Call FilterColumn(ctx, "Inspection Due Now", "Over Due")
		Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	ElseIf reportType = "TUBE" Then
		Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
		Call FilterColumn(ctx, "Tube Change Due Now", "Over Due")
		Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	ElseIf reportType = "VIP" Then
		Call FilterColumn(ctx, "Category", "VIP")
	ElseIf reportType = "DORMANT" Then
		Call FilterColumn(ctx, "Block Reason", "Dormant")
	ElseIf reportType = "REFILL" Then
		Call FilterColumn(ctx, "Type", "Domestic", com.sun.star.sheet.FilterOperator.NOT_EQUAL)
	End If

	' Expensive Operation, run after filter
	If inputType = "CONSUMERS" Then
		' TODO Sort will not lose it character after filter. This should be above filter
        Call SortColumn(ctx, "ID")
        SondageJoinVertical(ctx, "ID")
        SondageConditionalHorizontalCopy(ctx, "Mobile", "Phone")
    End If

	' TODO Should this be automatic and obtained from ctx?
	oCursor = UsedRangeCursor(ctx.oSheet)

	If reportType = "PENDING" Then
		' If the reportFilter is ONLINE, filter it, else highlight
		' TODO Add this feature to Sondage
		If reportFilter = "ONLINE" Then
			Call FilterColumn(ctx, "Payment Option", "Online Payment", com.sun.star.sheet.FilterOperator.EQUAL)
		Else
			highlightedCount = HighlightRowWithColumn(ctx, _
				"Payment Option", "Online Payment", RGB(255, 255, 0))
		End If

		' Justify Leftmost cells to left and Rightmost cells to right
		bookRange = GetColumnRange(ctx, "Book")
		bookRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.RIGHT)

		FormatRangeAsNumber(oLocale, oDoc.getNumberFormats(), bookRange, "DD/MM")

		tillDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MAX)
		fromDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MIN)

		SetupConditionalForHighPriority(ctx.oDoc, oLocale, bookRange,  badStyleName, "><", 1000, tillDate - priorityThreshold)
	ElseIf reportType = "EKYC" Then
		highlightedCount = HighlightRowWithColumn(ctx, _
			"Consumer Type", "PMUY", RGB(175, 255,  175))
	End If

	SondageTransformSheet(ctx, sonConf, reportType, "Group Width")

	If ErrorLocal$ <> "" Then Goto ErrorHandler
	oCursor = UsedRangeCursor(ctx.oSheet)

	If inputType = "PENDING" Then
		if isDBRequired Then
			If Not AssertColumn(dbCtx, "Address") Then GoTo ErrorHandler
		End If
	End If

	Call ShortenDirections(ctx, groupByColumn)
	Dim sSortBy$: sSortBy = SondageGetPropVal(aSettings, "SortBy")
	If sSortBy <> "" Then
		Call SortColumn(ctx, sGroupBy, sSortBy)
	Else
		Call SortColumn(ctx, sGroupBy)
	End If

	If reportType = "PENDING" and isDBRequired Then
		Call ColumnJoin(CHR(10), "ID", ctx, "Name", dbCtx, 	"Address")
	End If

	sTheme = SondageGetPropVal(aSettings , "Theme")
	If Not IsEmpty(sTheme) Then ApplyTheme(ctx.oDoc, sTheme)

	idRange = GetColumnRange(ctx, "ID")
	idRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.LEFT)

	' Setup exportPrefix and sheetName
	tillDateStr = Format(tillDate, "yyyy-mm-dd")
	sheetNameSuffix = " - " & reportType & " " & tillDateStr
	exportDestDir = tillDateStr & " " & reportType

	headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0)
	headerRange.CellStyle = "Heading 1"

	pageStyle = ctx.oDoc.StyleFamilies.getByName("PageStyles").getByName("Default")
	pageStyle.setPropertyValue("PrintGrid", True)
	pageStyle.setPropertyValue("CenterHorizontally", True)

	pageStyle.HeaderIsOn = True
	pageStyle.HeaderShared = True
	pageStyle.FirstPageHeaderIsShared = True

	' TODO simplify this logic, recalculate everytime
	If highlightedCount <> 0 Then
		If reportType = "PENDING" Then
			Call SetHeader(pageStyle,  Date() & " | FROM: " & fromDate, ,  "ONLINE: " & CStr(highlightedCount))
		ElseIf reportType ="EKYC" Then
			Call SetHeader(pageStyle, "GENERATED ON: " & Date(), ,  "PMUY: " & CStr(highlightedCount))
		End If
	End if

	pageStyle.setPropertyValue("LeftMargin", 0.2 * 2540)
	pageStyle.setPropertyValue("RightMargin", 0.2 * 2540)

	' Change original sheet name
	ctx.oSheet.Name = "ALL" & sheetNameSuffix

	' Clear subtotals if any before exporting area wise
	If shouldRunSubtotals Then oCursor.removeSubtotals()

	If enableGroupReports Then
		iGroupByColumn =  GetHeaderPosition(ctx, sGroupBy)
		If iGroupByColumn = -1 Then Goto ErrorHandler
		If GenerateIndividualSheets(ctx, sonConf, reportType, sGroupBy, statusBar, False) = False Then
			Goto ErrorHandler
		End If
	End If

	Dim summaryCtx as SondageContext: summaryCtx = ctx
	summaryCtx.oSheet = oDoc.getSheets().getByIndex(1)

	Dim sValidationList$
	If reportType = "PENDING" Then
		sValidationList = pendingRemarksValidateList
	ElseIf reportType = "EKYC" Then
		sValidationList = ekycRemarksList
	End If
	
	If sValidationList <> "" Then
		' FIXME Add this check dynamically from config sheet
		CreateValidationList(ctx, "Remarks", sValidationList)
	End If

	If shouldRunSubtotals Then
		Call RunSubtotals(oCursor, groupByColumn, statusBar)
		Call ReArrangeResultToHeader(summaryCtx)
	End If

	If statusBar Then statusBar.end()

	' Export summary
	If shouldExportPDF Then
		ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "pdf")
	End If

	if shouldExportSummaryEditable Then
		ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "ods")
	End If

	FinalFallback:
		If Not IsEmpty(organizeInputsFolder) Then
			If Not FileExists(organizeInputsFolder) Then MkDir(organizeInputsFolder)

			Dim sBackupInputFile: sBackupInputFile = organizeInputsFolder & GetPathSeparator()  & tillDateStr & " " & reportType & ".csv"
			If sBackupInputFile <> sInputFile Then
				FileCopy(sInputFile, sBackupInputFile)
			End If
		End If

		If Environ("USERPROFILE") <> "" Then
			' Assume this is windows
			Shell(Environ("COMSPEC"), 1, "/c start "" " & QS(QS(exportPrefix & GetPathSeparator() & exportDestDir)))
		End If
		If isHeadless Then
			' ThisComponent.Close(True) will close all open documents, we don't want that
			ThisComponent.CurrentController.Frame.Close(True)
		End If

	ErrorHandler:
		If statusBar Then statusBar.end()

		' This is the target document, so we close it everytime when not debugging
		If Not IsNull(oDBDoc) and debugInputFile = False Then
			oDoc.unlockControllers()
			oDoc.Close(True)
		End If

		' Only close the DB file, when we are not debugging
		If Not IsNull(oDBDoc) and debugInputFile = False Then
			oDBDoc.unlockControllers()
			oDBDoc.Close(True)
		End If

		If ErrorLocal$ <> "" Then
			MsgBox ErrorLocal$, 16, "FATAL Subfunction Error"
			Exit Sub
		End If

		If Erl <> 0 Then
			MsgBox "Line " & Erl & ": "&  Error$, 16, "FATAL Main Error"
			On Error GoTo 0
			Exit Sub
		End If

		If removeInputFileAfterSuccess Then
			Kill(sInputFile)
		End If
End Sub

Function CopyRange(dstCtx as SondageContext, srcCtx as SondageContext, startRow&, endRow&)
    ' Calculation for selecting the proper range
    ' start                     end
    '1 :                           endColumn          0 4
    'groupByColumn + 1 : endColumn           2  4
    '0 :                           endColumn - 1     4  4

    ' Copy Header
    srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A1").CellAddress, _
        srcCtx.oSheet.getCellRangeByPosition( _
        srcCtx.startColumn, _
        0, srcCtx.endColumn, 0).RangeAddress)

    ' Copy Contents
    srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A2").CellAddress, _
        srcCtx.oSheet.getCellRangeByPosition(_
        srcCtx.startColumn, _
        startRow, _
        srcCtx.endColumn, _
        endRow).RangeAddress)
End Function

Function GenerateIndividualSheets(ctx as SondageContext, sonConf as SondageConfiguration, reportType, sGroupByColumn$, statusBar as Variant, Optional sortColumn as Boolean) as Boolean
	' WARNING: This function requires a sorted column, unless specied as False in sortColumn
    ' In that case, the column is assumed sorted
	Dim dstSheet as Variant
	Dim startRow&
	Dim a$, sheetName$
	Dim iRow&, iGroupBy%
    Dim dstCtx as New SondageContext
    GenerateIndividualSheets = False
    
    statusBar.start("Creating " & sGroupByColumn & " Wise", 100)

	iGroupBy = GetHeaderPosition(ctx, sGroupByColumn)
	If iGroupBy <> 0 Then
		ErrorLocal$ = "Cannot generate group reports: '" & sGroupByColumn & "' must be the first column"
		Exit Function
	End If

	ctx.startColumn = 1

	If IsMissing(sortColumn) Then sortColumn = True
	iRow = ctx.startRow
	Do While iRow <= ctx.endRow
		a = ctx.oSheet.getCellByPosition(iGroupBy, iRow).getString()
		If a = "" Then Exit Do
		startRow = iRow

		Do While iRow <= ctx.endRow
			If ctx.oSheet.getCellByPosition(iGroupBy, iRow).getString() <> a Then Exit Do
			iRow = iRow + 1
		Loop

		statusBar.setText("Generating report for " & a)
		statusBar.setValue((iRow / ctx.endRow) * 100)
		sheetName = a & sheetNameSuffix

		' Prepare Destination sheet
		dstSheet = NewSheet(ctx.oDoc, sheetName)
        dstCtx = SondageGetContext(dstSheet)
		dstCtx.endRow = ctx.endRow
		dstCtx.endColumn = ctx.endColumn
        CopyRange(dstCtx, ctx, startRow, iRow - 1)

		' TODO Copy only required cells, instead of copying and deleting for GroupBys
		Dim testAreaColumn: testAreaColumn = GetHeaderPosition(dstCtx, sGroupByColumn)
		if testAreaColumn > 0 Then
			dstSheet.getColumns().removeByIndex(testAreaColumn, 1)
		End If

	    SondageTransformSheet(dstCtx, sonConf, reportType, "Width")

		If shouldExportPDF Then
			if ExportAs(dstCtx.oDoc, dstCtx.oSheet, exportPrefix, exportDestDir, "pdf") = False Then Exit Function
		End If
	Loop
	GenerateIndividualSheets = True
End Function

Function RunSubtotals(oCursor, iColumn, Optional statusBar as Variant)
    If Not IsMissing(statusBar) Then statusBar.setText("Running subtotals")
    Dim oSubtotalDesc : oSubtotalDesc = oCursor.createSubTotalDescriptor(true)
    Dim oSubtotalColumn(0) as new com.sun.star.sheet.SubTotalColumn

    With oSubtotalColumn(0)
        .Column = iColumn
        .Function = com.sun.star.sheet.GeneralFunction.COUNT
    End With
    oSubtotalDesc.addNew(oSubtotalColumn, iColumn)
    oCursor.applySubtotals(oSubtotalDesc, true)
End Function

Sub SubstituteContent(oDoc, oShape, oProduct)
	' TODO Maybe change from If Not to If and show error?
	If oShape.getName() = "" Then
		Exit Sub
	End If
	If oShape.getName() = "StovePrice" Then
		If oProduct.Price <> 0 Then
		oShape.setString(CURRENCY_UNIT & CStr(oProduct.Price))
		End If
	ElseIf oShape.getName() = "ProductBlurb" Then
		If oProduct.Description <> "" Then
			oShape.setString(oProduct.Description)
		End If
	ElseIf oShape.getName() = "ProductTitle" Then
		If IsEmpty(oProduct.Title) Then
			oShape.setString(oProduct.Title)
		End If
	End If
End Sub

Function GetFirstOpenDocument(docType as String)
	Dim oComponents: oComponents = StarDesktop.getComponents()
	Dim oDoc
	Dim oDocs: oDocs = oComponents.createEnumeration()
	Do While oDocs.hasMoreElements()
		oDoc = oDocs.nextElement()
		If  oDoc.supportsService(docType) Then
			GetFirstOpenDocument = oDoc
			Exit Function
		End If
	Loop
End Function

Sub Dialog1Show
    With GlobalScope.BasicLibraries
       If Not .IsLibraryLoaded("Tools") Then .LoadLibrary("Tools")
    End With
    Dim oAddBtn
    Dim oDialog1
    Dim oColorTbl, oHeaders, oColumn1, oColumn2, oColumn3, oComboBox, oDataModel
    oDialog1 = Tools.ModuleControls.LoadDialog("Standard", "Dialog1")
    oAddBtn = oDialog1.getControl("AddBtn").getModel()
    oColorTbl = oDialog1.getControl("ColorTable").getModel()
    oColorTbl.Width = 150 ' TODO get width value from column

	oColumn1 = createUnoService( "com.sun.star.awt.grid.GridColumn")
    oColumn2 = createUnoService( "com.sun.star.awt.grid.GridColumn")
    oColumn3 = createUnoService( "com.sun.star.awt.grid.GridColumn")

	oColumn1.Title = "Condition"
	oColumn1.MaxWidth = 30
	oColumn2.Title = "Value"
	oColumn2.MaxWidth = 30
	oColumn3.Title = "Color"

	'	Print oColumn3.dbg_properties()
    oHeaders = createUnoService("com.sun.star.awt.grid.DefaultGridColumnModel")
    oDataModel = createUnoService( "com.sun.star.awt.grid.DefaultGridDataModel")

    oHeaders.addColumn(oColumn1)
    oHeaders.addColumn(oColumn2)
    oHeaders.addColumn(oColumn3)
    
    oColorTbl.GridDataModel = oDataModel
	
    oColorTbl.ColumnModel = oHeaders
    oDataModel.addRow("1", Array(">", "45", "#ff0000"))
    oDialog1.Execute()
End Sub

Sub SetCustomBadStyle(oDoc, oLocale, styleName as String)
	Dim oCellStyles
	Dim oStyle
	Dim formatNum%
	oCellStyles = oDoc.StyleFamilies("CellStyles")
	If oCellStyles.hasByName(styleName) Then
		oCellStyles.removeByName(styleName)
	End If
	oStyle = oDoc.createInstance("com.sun.star.style.CellStyle")
	oCellStyles.insertByName(styleName, oStyle)
	oStyle = oCellStyles.getByName(styleName)
	oStyle.CellBackColor = RGB(255, 0, 0)
	formatNum = GetNumberFormatNumber(oLocale, oDoc.getNumberFormats(), "DD/MM")
	If formatNum = -1 Then
		ErrorLocal$ = "WARNING: Cannot add '" & formatStr & "' as NumberFormat"
		Exit Sub
	End If
	oStyle.NumberFormat = formatNum
End Sub

Sub SetupConditionalForHighPriority(oDoc, oLocale, oRange, styleName$, _
		opCond$, formula1 as Variant, Optional formula2 as Variant)
		
	' TODO Rework this function to automagically handle dates
	Dim oConFormat
	Dim oCondition(3) as new com.sun.star.beans.PropertyValue

	'BasicLibraries.LoadLibrary("Sondage")

	' FIXME This may very well crash on some operations, I have no idea, because
	' I have not tested it
	If IsMissing(formula2) Then formula2 = "0"
	
	If TypeName(formula1) = "Date" Then
		formula1 = CStr(CLng(formula1))
	End If
	
	If TypeName(formula2) = "Date" Then
		formula2 = CStr(CLng(formula2))
	End If

	With oCondition(0)
		.Name = "Operator"
		.Value = SondageGetCondTypeFromString(opCond)
	End With
	With oCondition(1)
		.Name = "Formula1" 
		.Value =  formula1
	End With
	With oCondition(2)
		.Name = "Formula2"
		.Value = formula2
	End With
    With oCondition(3)
    	.Name = "StyleName"
    	.Value = styleName
    End With
    
	oConFormat = oRange.ConditionalFormat
	oConFormat.clear()
	oConFormat.addNew(oCondition)
	oRange.ConditionalFormat = oConFormat
End Sub

Sub ShowFilterOptions()
	Dim args(), i%
	args() = StarDesktop.CurrentComponent.getArgs()
	For i = 0 to uBound(Args())
	   If args(i).Name = "FilterOptions" then inputbox args(i).Name,"",cStr(args(i).value)
	Next
End Sub