# wb2.awk

#/*
#*************************************************************************
#**									*
#**	Copyright (C) 1992-2010 Trans-Mit Pty. Ltd. Melbourne Australia	*
#**	This software may not be loaned, resold, changed or copied	*
#**	in any way without the express written permission of author	*
#**	and Trans-Mit Pty. Ltd., Australia.				*
#**									*
#*************************************************************************
#**
#**	$Header: /usr/local/lib/cake/RCS/rcshead,v 1.11 2005/11/15 01:44:38 root Exp $
#**	$Author: root $
#**	$Date: 2005/11/15 01:44:38 $
#**	$Locker:  $
#**
#*************************************************************************
#*/

#######################################################

function fixdate(dt)
{
	# change /'s to -'s in  dd/mm/yyyy
	sub("/","-",dt)
	sub("/","-",dt)
	return dt
}

#----------------------------------------------------------
# needed because of rounding bug in awk (see tround1 script)

function mround2(cst)
{
	if ( match(cst,"\...5$") > 0 )
		cst += 0.001
	return sprintf("%0.2f", cst)
}

function mround4(cst)
{
	if ( match(cst,"\.....5$") > 0 )
		cst += 0.00001
	return sprintf("%0.4f", cst)
}


#----------------------------------------------------------

function sanetrim(s)
{
	sub(/^[ \t]*/,"",s)
	sub(/[ \t]*$/,"",s)
	gsub(/\047/,"`",s)
	gsub(/\"/,"",s)
	return s
}

function trim(s)
{
	sub(/^[ \t]*/,"",s)
	sub(/[ \t]*$/,"",s)
	return s
}

function clip(s)
{
	sub(/[ \t]*$/,"",s)
	return s
}

function fixforfname(s)
{
	gsub(/\//,"+",s)
	return s
}

#----------------------------------------------------------

# convert MMYYYY MMM_YYYY
function MMYYYY_to_billperiod(MMYYYY,sep)
{
	mnthstr[1]  = "January"
	mnthstr[2]  = "February"
	mnthstr[3]  = "March"
	mnthstr[4]  = "April"
	mnthstr[5]  = "May"
	mnthstr[6]  = "June"
	mnthstr[7]  = "July"
	mnthstr[8]  = "August"
	mnthstr[9]  = "September"
	mnthstr[10] = "October"
	mnthstr[11] = "November"
	mnthstr[12] = "December"

	billmm = 0 + substr(MMYYYY,1,2)
	billyyyy = 0 + substr(MMYYYY,3,4)
	billsdd = 0 + substr(sdate,1,2)
	billedd = 0 + substr(edate,1,2)

	# for back billing output
	syyyymmdd = sprintf("%03s%02s%02s", billyyyy, billmm, billsdd)
	eyyyymmdd = sprintf("%03s%02s%02s", billyyyy, billmm, billedd)

	if ( sep != "" )
		sepchar = substr(sep,1,1)
	else
		sepchar = " "

	# create monthtag/billperiod
	billperiod = substr(mnthstr[billmm],1,3) sepchar billyyyy
	monthtag = substr(mnthstr[billmm],1,3) "_" billyyyy

	#for ( billmm = 1; billmm < 12; ++billmm ) {
	#	if ( substr(mnthstr[billmm],1,3) == substr(billperiod,1,3) )
	#		break
	#}
	if ( billmm > 12 ) {
		printf("FATAL ERROR: BAD billperiod [%s]\n", billperiod)
		exit 1
	}
	#billyyyy = 0 + substr(billperiod,5,4)
	#monthtag = sprintf("%s_%d", substr(mnthstr[billmm],1,3), billyyyy)

	print "MMYYYY = " MMYYYY "  billperiod = " billperiod

	# expanded bill period
	exbillperiod = sprintf("%s %d", mnthstr[billmm], billyyyy)
	printf("exbillperiod = %s\n", exbillperiod)

}



function get_weekday_arr(adate) {
	print "get_weekday_arr(" adate ")"
	mm = substr(adate,4,2)
	yyyy = substr(adate,7,4)
	calcmd = "cal " mm " " yyyy
	wdlncnt = 0
	while ( (calcmd | getline aline) > 0 ) {
		++wdlncnt
		if ( wdlncnt <= 2 )
			continue
		sun = sprintf("%d", substr(aline,1,2))
		mon = sprintf("%d", substr(aline,4,2))
		tue = sprintf("%d", substr(aline,7,2))
		wed = sprintf("%d", substr(aline,10,2))
		thu = sprintf("%d", substr(aline,13,2))
		fri = sprintf("%d", substr(aline,16,2))
		sat = sprintf("%d", substr(aline,19,2))
		if ( sun > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", sun, mm, yyyy)
			weekday_arr[aweekday] = "Sunday"
		}
		if ( mon > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", mon, mm, yyyy)
			weekday_arr[aweekday] = "Monday"
		}
		if ( tue > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", tue, mm, yyyy)
			weekday_arr[aweekday] = "Tuesday"
		}
		if ( wed > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", wed, mm, yyyy)
			weekday_arr[aweekday] = "Wednesday"
		}
		if ( thu > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", thu, mm, yyyy)
			weekday_arr[aweekday] = "Thursday"
		}
		if ( fri > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", fri, mm, yyyy)
			weekday_arr[aweekday] = "Friday"
		}
		if ( sat > 0 ) {
			aweekday = sprintf("%02d-%02d-%04d", sat, mm, yyyy)
			weekday_arr[aweekday] = "Saturday"
		}
	}
	close(calcmd)

	for ( adate in weekday_arr ) {
		print "get weekday_arr[" adate "] = " weekday_arr[adate]
	}
}


function weekday(adate) {
	aweekday = weekday_arr[adate]
	if ( aweekday == "" ) {
		# create weekday array for days in month
		get_weekday_arr(adate)
		aweekday = weekday_arr[adate]
	}
	return aweekday
}


function is_weekday(adate) {
	aweekday = weekday(adate)
	if ( aweekday == "Sunday" || aweekday == "Saturday" )
		return 0
	return 1
}


#####################################################
#####################################################
#rjs9
# Victrack custom

#--------------------------
# new tbsdata database


function ld_tbsdata_customer(customerfile) {
	printf("ld_tbsdata_customer(%s)\n", customerfile)

	#1|NXS|NEGA (SWANSTON TRAMS) PTY LTD|V6050884|
	# NATIONAL EXPRESS (SWANSTON) PTY LTD|
	# C/O MCGRATH NICOL - ATT: D PIENING|LEVEL 1; 161 COLLINS STREET|
	# MELBOURNE|VIC|3000||0|1|1|Dec 07 2004 12:00AM||robynd|1|

	while ( (getline aline < customerfile) > 0 ) {
		split(aline, a_arr, "|")
		##printf("aline=%s\n", aline)
		CustomerID = trim(a_arr[1])
		ShipTo = trim(a_arr[2])
		ShipToDesc = trim(a_arr[3])
		ShipToCode = trim(a_arr[4])
		ShipToFullDesc = trim(a_arr[5])

		CustomerDesc = ShipToFullDesc
		if ( ShipTo == substr(ShipToFullDesc,1,length(ShipTo)) )
			CustomerDesc = substr(ShipToFullDesc,length(ShipTo)+1)
		if ( CustomerDesc != "" )
			CustomerDesc = ShipTo " - " CustomerDesc
		else
			CustomerDesc = ShipTo

		ShipTo = toupper(ShipTo)
		ShipTo_to_ShipToDesc_arr[ShipTo] = ShipToDesc
		ShipTo_to_ShipToCode_arr[ShipTo] = ShipToCode
		ShipTo_to_CustomerDesc_arr[ShipTo] = CustomerDesc

		CustomerID_to_ShipTo_arr[CustomerID] = ShipTo

		print "    ShipTo = " ShipTo
		print "    ShipTo_to_ShipToDesc_arr[" ShipTo "] = " ShipTo_to_ShipToDesc_arr[ShipTo]
		print "    ShipTo_to_ShipToCode_arr[" ShipTo "] = " ShipTo_to_ShipToCode_arr[ShipTo]
		print "    CustomerID_to_ShipTo_arr[" CustomerID "] = " CustomerID_to_ShipTo_arr[CustomerID]
		print "    ShipTo_to_CustomerDesc_arr[" ShipTo "] = " ShipTo_to_CustomerDesc_arr[ShipTo]
	}
	close(customerfile)
}


function ld_tbsdata_servicetype(servicetypefile) {
	printf("ld_tbsdata_servicetype(%s)\n", servicetypefile)

	#99|XA|SMS MESSAGES|194|140|140|0||0|1|Dec 07 2004 12:00AM|
	# |1|0|0|0.0000|0|

	while ( (getline aline < servicetypefile) > 0 ) {
		split(aline, a_arr, "|")
		ServiceTypeID = trim(a_arr[1])
		ServiceTypeCode = trim(a_arr[2])
		SupplierID = trim(a_arr[4])
		RevenueElementID = trim(a_arr[5])
		SystemID = trim(a_arr[8])

		tascode = ServiceTypeCode
		tascode_to_SystemID_arr[tascode] = SystemID
		tascode_to_ElementID_arr[tascode] = RevenueElementID
		tascode_to_orgElementID_arr[tascode] = RevenueElementID
		tascode_to_SupplierID_arr[tascode] = SupplierID

		print "    tascode = " tascode
		print "    tascode_to_SystemID_arr[" tascode "] = " tascode_to_SystemID_arr[tascode]
		print "    tascode_to_ElementID_arr[" tascode "] = " tascode_to_ElementID_arr[tascode]
		print "    tascode_to_SupplierID_arr[" tascode "] = " tascode_to_SupplierID_arr[tascode]
	}
	close(servicetypefile)
}


function ld_tbsdata_element(elementfile) {
	printf("ld_tbsdata_element(%s)\n", elementfile)

      #1|1046|Telco Account Processing Fee||1|1|May 10 2005 12:00AM||499|10|0|

	while ( (getline aline < elementfile) > 0 ) {
		split(aline, a_arr, "|")
		##printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 3=%s 4=%s\n", a_arr[1], a_arr[3], a_arr[4])
		ElementID = trim(a_arr[1])
		ElementCode = trim(a_arr[2])
		ElementCodeDesc = trim(a_arr[3])
		CustomerID = trim(a_arr[9])

		if ( CustomerID != "499" )	# only look at VRT entries
			continue

		SGID = 0
		SGIDdesc = "All"

		SEID = ElementCode
		SEIDdesc = ElementCodeDesc

		SGID_to_SGIDdesc_arr[SGID] = SGIDdesc

		SEID_to_SEIDdesc_arr[SEID] = SEIDdesc
		SEID_to_SGID_arr[SEID] = SGID

		ElementID_to_SEID_arr[ElementID] = SEID
		SEID_to_orgElementID_arr[SEID] = ElementID

		print "    SGID = " SGID "  SEID = " SEID
		print "    SEID_to_SGID_arr[" SEID "] = " SEID_to_SGID_arr[SEID]

		print "    SGID_to_SGIDdesc_arr[" SGID "] = " SGID_to_SGIDdesc_arr[SGID]
		print "    SEID_to_SEIDdesc_arr[" SEID "] = " SEID_to_SEIDdesc_arr[SEID]

		print "    ElementID_to_SEID_arr[" ElementID "] = " ElementID_to_SEID_arr[ElementID]
	}
	close(elementfile)
}


function ld_tbsdata_supplier(supplierfile) {
	printf("ld_tbsdata_supplier(%s)\n", supplierfile)

	#1|OPTUS COMMUNICATIONS|1||robynd|OPT001|1|OPTUS COMMUNICATIONS|
	# LEVEL 6|50 MILLER STREET|NORTH SYDNEY|NSW|2060|

	while ( (getline aline < supplierfile) > 0 ) {
		split(aline, a_arr, "|")
		##printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 7=%s\n", a_arr[1], a_arr[7])

		SupplierID = trim(a_arr[1])
		SupplierName = trim(a_arr[2])

		split(SupplierName, SupplierName_arr, " ")
		supplier = toupper(SupplierName_arr[1])

		SupplierID_to_supplier_arr[SupplierID] = supplier

		print "      SupplierID = " SupplierID
		print "    SupplierName = " SupplierName
		print "        supplier = " supplier
		print "    SupplierID_to_supplier_arr[" SupplierID "] = " SupplierID_to_supplier_arr[SupplierID]
	}
	close(supplierfile)
}


#-----------------------------------------------------------------
# to replace info from Telmax21 Directory

function ld_tbsdata_personservicelist(personservicelistfile) {
	printf("ld_tbsdata_personservicelist(%s)\n", personservicelistfile)

	while ( (getline aline < personservicelistfile) > 0 ) {
		split(aline, a_arr, "|")
		#printf("aline=%s\n", aline)

		f = 0
		PersonID = sanetrim(a_arr[++f])
		Person = sanetrim(a_arr[++f])
		ServiceIDID = sanetrim(a_arr[++f])
		ServiceID = sanetrim(a_arr[++f])
		ShipTo = sanetrim(a_arr[++f])
		FullName = sanetrim(a_arr[++f])

		dirID = "Person" PersonID

#rjs9-
		recordno = dirID
		master = "Y"
		t21surname = Person
		t21firstname = ""
		staffid = emailaddress
		emailaddress = "ToBeSet"

		t21location = "ToBeSet"
		t21division = "ToBeSet"
		t21department = "ToBeSet"

		if ( t21surname == "" )
			t21surname = "_blank_"
		if ( t21firstname == "" )
			t21firstname = "_blank_"

		if ( t21location == "" )
			t21location = "_blank_"

		t21name = t21surname
		if ( t21firstname != "_blank_")
			t21name = sprintf("%s %s", t21firstname, t21name)

		recordno_to_master_arr[recordno] = master

		recordno_to_t21name_arr[recordno] = t21name
		print " tbs  recordno_to_t21name_arr[" recordno "] = [" recordno_to_t21name_arr[recordno] "]"

		recordno_to_staffid_arr[recordno] = staffid
		print " tbs  recordno_to_staffid_arr[" recordno "] = [" recordno_to_staffid_arr[recordno] "]"

		#recordno_to_extn_arr[recordno] = extn

		#recordno_to_eggrid_arr[recordno] = extgroupunique
		recordno_to_eggrid_arr[recordno] = ServiceID
		print " tbs  recordno_to_eggrid_arr[" recordno "] = [" recordno_to_eggrid_arr[recordno] "]"

		#recordno_to_t21site_arr[recordno] = t21site

		recordno_to_t21location_arr[recordno] = t21location

		recordno_to_t21surname_arr[recordno] = t21surname
		recordno_to_t21firstname_arr[recordno] = t21firstname
		recordno_to_t21division_arr[recordno] = t21division
		recordno_to_t21department_arr[recordno] = t21department


		# (mobile to person done in gettbsmobconf script)
		#if ( match(ServiceID,/^04..-......$/) <= 0 ) 
		#	mobile = ""
		#else
		#	mobile = substr(ServiceID,1,2) substr(ServiceID,4)
		#mobile_to_dirID_arr[mobile] = dirID
		#print "    mobile_to_dirID_arr[" mobile "] = " mobile_to_dirID_arr[mobile]
#-rjs9

	}
	close(personservicelistfile)
}


#-----------------------------------------------------------------

#rjs9
#function ld_seidtranslate(seidtranslatefile) {
#	printf("ld_seidtranslate(%s)\n", seidtranslatefile)
#	while ( (getline aline < seidtranslatefile) > 0 ) {
#		split(aline, a_arr, ",")
#		##printf("aline=%s\n", aline)
#		#printf("a_arr 1=%s 7=%s\n", a_arr[1], a_arr[7])
#
#		systemid = trim(a_arr[1])
#		seid = trim(a_arr[2])
#
#		systemid_to_seid[systemid] = seid
#
#		print "systemid_to_seid[" systemid "] = " systemid_to_seid[systemid]
#	}
#	close(seidtranslatefile)
#}



#-----------------------------------------------------------------

function ld_cde(cdefile) {
	printf("ld_cde(%s)\n", cdefile)
	while ( (getline aline < cdefile) > 0 ) {
		gsub("\r","",aline)
		i = split(aline, a_arr, "|")
		if ( i != 22 ) {
			print "WARNING: bad cde record in file " cdefile " [" aline "]" " i=" i
			continue
		}
		print cdefile ": " aline
		##printf("aline=[%s]\n", aline)
		#printf("a_arr 1=%s\n", a_arr[1])
		f = 0
		DIVID = trim(a_arr[++f])
		sundry = trim(a_arr[++f])
		rentcost = trim(a_arr[++f])
		callcost = trim(a_arr[++f])
		othercost = trim(a_arr[++f])
		totalcost = trim(a_arr[++f])
		tascode = trim(a_arr[++f])
		SID = trim(a_arr[++f])
		location = trim(a_arr[++f])
		user = trim(a_arr[++f])

		tbscentreid = trim(a_arr[++f])
		tbscentre = trim(a_arr[++f])
		activity = trim(a_arr[++f])
		element = trim(a_arr[++f])
		subledger = trim(a_arr[++f])
		paytype = trim(a_arr[++f])

		deptid = trim(a_arr[++f])
		department = trim(a_arr[++f])
		servicedesc = trim(a_arr[++f])
		installdate = trim(a_arr[++f])
		std = trim(a_arr[++f])

		# Testing
	        if ( Testing >= 2 && ! (DIVID == "ANN" || DIVID == "VLP") ) {
			#print "CDE TESTING... SKIP  DIVID = " DIVID "  SID = " SID
			continue
		}

		############################
		costcentre = sprintf("%-6.6s %-2.2s %-6.6s %-6.6s %-1.1s", centre, activity, element, subledger, paytype)

		ElementID = tascode_to_ElementID_arr[tascode]
		print "        tascode_to_ElementID_arr[" tascode "] = [" tascode_to_ElementID_arr[tascode] "]"

		DIVID = toupper(DIVID)

		# cant have "/" in SID (re: filenames)
		gsub("/",".",SID)

		#itag = DIVID "|" sundry
		orgElementID = ElementID = tascode_to_orgElementID_arr[tascode]
		itag = DIVID "|" sundry "|" orgElementID

 		platinv_batch = parent_sundry_to_platinv_batch_arr[itag]

		print "         itag=" itag "  platinv_batch = " platinv_batch

		if ( platinv_batch == "" ) {
			print "WARNING: Can't get Platinum Invoice batch for DIVID = " DIVID "  sundry = " sundry
		}

		# if ShipTo code in tbs Customer is blank then set DIVID to VRT
		if ( ShipTo_to_ShipToCode_arr[DIVID] == "" ) {
			print "WARNING: blank ShiptoCode, setting DIVID to VRT"
			DIVID = "VRT"
			#itag = DIVID "|" sundry
			itag = DIVID "|" sundry "|" orgElementID
			platinv_batch = "VRTBATCHFILENAME"
			parent_sundry_to_platinv_batch_arr[itag] = platinv_batch
			invoiceno = "VRT999999"
			parent_sundry_to_platinv_invoicenumber_arr[itag] = invoiceno
		}
		# if ShipTo code in tbs Customer is VRT
		if ( ShipTo_to_ShipToCode_arr[DIVID] == "VRT" ) {
			print "ShiptoCode = VRT, setting dummy platinv_batch"
			DIVID = "VRT"
			#itag = DIVID "|" sundry
			itag = DIVID "|" sundry "|" orgElementID
			platinv_batch = "VRTBATCHFILENAME"
			parent_sundry_to_platinv_batch_arr[itag] = platinv_batch
			invoiceno = "VRT999999"
			parent_sundry_to_platinv_invoicenumber_arr[itag] = invoiceno
		}

		SupplierID = tascode_to_SupplierID_arr[tascode]
		#old tassemap supplier = tascode_to_supplier_arr[tascode]
		supplier = SupplierID_to_supplier_arr[SupplierID]

		#old tassemap SEID = tascode_to_SEID_arr[tascode]
		SEID = ElementID_to_SEID_arr[ElementID]
		print "        ElementID_to_SEID_arr[" ElementID "] = [" ElementID_to_SEID_arr[ElementID] "]"

		# 05/12/2007
		# all internal and external network services for VRT
		# are now set to seid 2399 in tbsdata
		seidchange = 0
		actualSEID = SEID
		#if ( SEID == 2399 ) {
		# do for all (for VoiceMail in non VRT and future)

			# rjs9-
			## for mobile - translate seid using systemid
			#systemid = tascode_to_SystemID_arr[tascode]
			#newseid = systemid_to_seid[systemid]
			#if ( newseid != "" ) {
			#	print " translate SEID=" SEID "   translate newseid=" newseid "  systemid=" systemid
			#	SEID = newseid
			#	seidchange = 1
			#}	
			#else {
			#	# use SID to determine Telmax21 data
			#	newseid = 101043
			#	if ( grid_to_grtype_arr[tmpsid] == "E" ) {
			#		print " SEID=" SEID "   newseid=" newseid "  SID=" SID
			#		SEID = newseid 
			#		seidchange = 1
			#	}
			#	else { # test for Switchboard or Voicemail
			#		if ( substr(SID,1,2) == "SW" ) {
			#			tmpsid = substr(SID,3)
			#			newseid = 101030
			#		}
			#		if ( substr(SID,1,2) == "VM" ) {
			#			tmpsid = substr(SID,3)
			#			newseid = 101047
			#		}
			#		if (grid_to_grtype_arr[tmpsid] == "E") {
			#			print " SEID=" SEID "   newseid=" newseid "  SID=" SID "  tmpsid=" tmpsid
			#			SEID = newseid
			#			seidchange = 1
			#		}
			#	}
			#}

			# for mobile - match SID with 04..-......
			if ( seidchange == 0 && match(SID, "04[0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]") ) {
				print " mobile - SEID=" SEID "  newseid=" newseid "  SID=" SID
				SEID = 101044
				seidchange = 1
			}	

			# for T21 calls/switchboard/voicemail use tascode & SID
			if ( seidchange == 0 && index("|TQ|TQ1|TQD|TQQ|TQS|VOI|VS1|VSW|VV1|", "|" tascode "|") > 0 ) {
				# T21 calls
				newseid = 101043

				# T21 switchboard
				if ( substr(SID,1,2) == "SW" )
					newseid = 101030

				# T21 voicemail
				if ( substr(SID,1,2) == "VM" )
					newseid = 101047

				SEID = newseid
				seidchange = 1
				print " T21 - SEID=" SEID "  newseid=" newseid "  SID=" SID "  tascode=" tascode
			}
			# -rjs9

		#}
		## SEID is still 2399 so,
		## this is to prevent hardcodes in reports from
		## creating drill down to t21 call/rent for
		## non drilldown services
		#if ( SEID == 2399 ) {
		#	SEID = 102399
		#	SEID_to_SEIDdesc_arr[SEID] = SEID_to_SEIDdesc_arr[2399]
		#	print " no translate for SEID=2399   setto=" SEID "  systemid=" systemid
		#	seidchange = 1
		#}

		# set elementid to seid lookup for replaced VRT 2399 seid
		if ( seidchange == 1 ) {
			# use replaced SEID+100000 as elementid
			newelementid = SEID + 100000
			tascode_to_ElementID_arr[tascode] = newelementid
			ElementID_to_SEID_arr[newelementid] = SEID

			SEID_to_orgElementID_arr[SEID] = ElementID

			print "new ElementID_to_SEID_arr[" newelementid "] = " ElementID_to_SEID_arr[newelementid]
			SEID_to_SGID_arr[SEID] = 0

			# create seid desc for new seid's set here
			# preserve switchboard seid desc
			SEID_to_SEIDdesc_arr[101030] = SEID_to_SEIDdesc_arr[1030]

			# VOICEMAIL has no entry in tElement
			SEID_to_SEIDdesc_arr[101047] = "Telco VoiceMail"

			# preserve mobile seid desc
			SEID_to_SEIDdesc_arr[101044] = SEID_to_SEIDdesc_arr[1044]

			# preserve T21 Rent and Calls seid desc
			SEID_to_SEIDdesc_arr[101043] = SEID_to_SEIDdesc_arr[1043]
		}

		print "     use SEID = " SEID "  tascode=" tascode "  supplier=" supplier

		# store sundry for T21 calls
		#if (supplier == t21_supplier && SEID == 1043)
		# seid now set here in ld_cde()
		if (supplier == t21_supplier && SEID == 101043) {
			if ( t21_sundry != "" ) {
				if ( t21_sundry != sundry ) {
					print "FATAL ERROR: multiple TIMS calls Sundrys t21_sundry = " t21_sundry " next sundry = " sundry
					exit 1
				}
			}
			else {
				# save TIMS calls sundry
				t21_sundry = sundry
				t21_elementid = ElementID
				print "           t21_sundry = " t21_sundry
			}
			if ( platinv_batch != "VRTBATCHFILENAME" ) {
				# save TIMS calls platinv_batch
				t21_platinv_batch[platinv_batch] = 1
				print "           t21 platinv_batch = " platinv_batch
			}
		}

		sundrySID_to_tascode_arr[sundry "|" SID] = tascode

		# only doing thisDIVID
		if ( thisDIVID != "all" && thisDIVID != DIVID )
			continue

		## rjs
		#if ( platinv_batch == "TBSAUG2004001134" ) {
		#	print "Warning 1 Skipping platinv_batch = " platinv_batch
		#	continue
		#}
		# only doing this platinumbatch
		if (platinumBATCH != "all" && platinumBATCH != platinv_batch)
			continue

		invoiceno = parent_sundry_to_platinv_invoicenumber_arr[itag]

		print "         itag=" itag "  invoiceno = " invoiceno

		if ( invoiceno == "" ) {
			print "WARNING: NO INVOICE for shipto = " DIVID " and sundry = " sundry "  SID = " SID "  tascode_to_orgElementID_arr[" tascode "] = " tascode_to_orgElementID_arr[tascode]
			#print "WARNING: NO INVOICE for shipto = " DIVID " and sundry = " sundry "  SID = " SID
			#platinv_batch = DIVID monthtag "NOINV"
			#parent_sundry_to_platinv_batch_arr[itag] = platinv_batch
			#invoiceno = DIVID "_" "NOINV"
			#parent_sundry_to_platinv_invoicenumber_arr[itag] = invoiceno
			continue
		}

		# flag parent / sundry in cde
		cde_parent_sundry_arr[itag] = 1
		print "cde_parent_sundry_arr[" itag "]=[" cde_parent_sundry_arr[itag] "]"

		ElementID = tascode_to_ElementID_arr[tascode]
		#old tassemap SEID = tascode_to_SEID_arr[tascode]
		SEID = ElementID_to_SEID_arr[ElementID]

		SGID = SEID_to_SGID_arr[SEID]

		# rjs9 - deptid added to getcde script
		## assign unique DEPTID
		#DEPTID = department_to_DEPTID_arr[department]
		#if ( DEPTID == 0 ) {
		#    department_to_DEPTID_arr[department] = ++MAXDEPTID
		#    DEPTID = MAXDEPTID
		#    DEPTID_to_department_arr[DEPTID] = department
		#    #printf("NEW   DIVID = %s department = (%d)%s    MAXDEPTID = %d\n", DIVID, DEPTID, department, MAXDEPTID)
		#    pipecmd = "sort >" logdir "/" "DEPTID_" batchtag ".lst"
		#    print DIVID "|" DEPTID "|" department | pipecmd
		#}
		DEPTID = "DEPT" deptid
		DEPTID_to_department_arr[DEPTID] = department

		tbsCENTREID = "CENTRE" tbscentreid

		# set servtype to match standrd bilmax21
		SERVTYPE = 100000 + SEID
		if ( SEID == 101043 )	# t21 cdr
			SERVTYPE = 1
		if ( SEID == 101044 ) 	# mobile
			SERVTYPE = 10
		#if ( SEID == 101047 )	# voicemail
		#if ( SEID == 101030 )	# switchboard
		if ( SERVTYPE >= 100000 )
			SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE] = SEIDdesc

		# moved from ld_t21groups()
		CENTRE = DEPTID
		PROJECT = tbsCENTREID
	
		grid_to_ccp_arr[SID] = tbscentre
		grid_to_centre_arr[SID] = CENTRE
		grid_to_project_arr[SID] = PROJECT

                print "grid_to_centre_arr[" SID "]  = [" grid_to_centre_arr[SID] "]"
                print "grid_to_project_arr[" SID "]  = [" grid_to_project_arr[SID] "]"

		CENTRE_to_ShipTo_arr[CENTRE] = DIVID
		CENTREPROJECT_to_ShipTo_arr[CENTRE "|" PROJECT] = DIVID
		print "CENTREPROJECT_to_ShipTo_arr[" CENTRE "|" PROJECT "] = [" CENTREPROJECT_to_ShipTo_arr[CENTRE "|" PROJECT] "]"

		CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] = SID
		print "CENTREPROJECTSID_to_EGRID_arr[" CENTRE "|" PROJECT "|" SID "] = [" CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] "]"

		#-rjs9

		# deptid lookup (used to get deptid fronm t21 dir entries)
		itag = DIVID "|" SID
		# rjs. 22/11/2007
		#if ( parentSID_to_DEPTID_arr[itag] != "" && parentSID_to_DEPTID_arr[itag] != DEPTID ) {
		#	# rjs skip multiple
		#	if ( SID == "INV 2253177" )
		#		continue
		#	if ( SID == "INV 2257030" )
		#		continue
		#	printf("FATAL ERROR: SID=[%s] has multile deptid's for parent = %s\n", SID, DIVID)
		#	exit 1
		#}
		parentSID_to_DEPTID_arr[itag] = DEPTID

		#------------------------
		# chech values for building HIERIDx
		if (SERVTYPE == "" || DIVID == "" || SGID == "" || SEID == "" || DEPTID == "" || tbsCENTREID == "" || SID == "" || supplier == "" || tascode == "" || sundry == "" || invoiceno == "") {
			print "FATAL ERROR: BAD for HIERIDx (1 or more blank fields)"
			print "           SERVTYPE = " SERVTYPE
			print "              DIVID = " DIVID
			print "               SGID = " SGID
			print "               SEID = " SEID "     (ElementID = " ElementID ")"
			print "             DEPTID = " DEPTID
			print "        tbsCENTREID = " tbsCENTREID
			print "                SID = " SID
			print "           supplier = " supplier
			print "             tascode = " tascode
			print "            location = " location
			print "                user = " user
			print "          costcentre = " costcentre
			print "              sundry = " sundry
			print "           invoiceno = " invoiceno
			exit 1
		}

		got_cde_data = 1

		#------------------------

		rec_type = "CHARGE_DESC"

		chg_cat = tascode "~" location "~" user "~" costcentre "~" sundry "~" invoiceno

		# called also in ldt21detail code
		set_HIERIDx(SERVTYPE,CENTRE,PROJECT,SID,supplier,rec_type,chg_cat)

		print "HIERIDx = " HIERIDx

		#rjs9
		#HIERID = DIVID "|" SGID "|" SEID "|" DEPTID "|" SID
		#HIERID = HIERID "|" supplier "|" tascode "|" location "|" user "|" costcentre
		#HIERID = HIERID "|" sundry
		#HIERID = HIERID "|" invoiceno

		#HIERIDxDUPcount = ++HIERIDxcount[HIERID]
		#HIERID = HIERID "|" HIERIDxDUPcount
		#HIERIDx = HIERID "|"

		#HIERIDx_to_sundry_arr[HIERIDx] = sundry
		
		#HIERIDx_to_supplier_arr[HIERIDx] = supplier
		#HIERIDx_to_tascode_arr[HIERIDx] = tascode
		#HIERIDx_to_location_arr[HIERIDx] = location
		#HIERIDx_to_user_arr[HIERIDx] = user
		#HIERIDx_to_costcentre_arr[HIERIDx] = costcentre

		HIERIDx_to_rentcost_arr[HIERIDx] = rentcost
		HIERIDx_to_callcost_arr[HIERIDx] = callcost
		HIERIDx_to_othercost_arr[HIERIDx] = othercost
		HIERIDx_to_totalcost_arr[HIERIDx] = totalcost

		chg_count = 0
		chg_duration = 0
		chg_cost = totalcost

		add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID, supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

		pipecmd = "sort -u >" logdir "/" "sundrys_" batchtag ".uniq"
		print sundry " " supplier | pipecmd

		pipecmd = "sort | uniq -d >" logdir "/" "SID_" batchtag ".dup"
		print SID | pipecmd
	}
	close(cdefile)
}


function is_t21_platinv_batch(platinvbatchfilename)
{
	for ( t21batchfilename in t21_platinv_batch ) {
		if ( platinvbatchfilename == t21batchfilename )
			return 1
	}
	return 0
}


#----------------------------------------------------------
#----------------------------------------------------------
# T21

function store_t21calls_gggrid_cde_info()
{
	printf("store_t21calls_gggrid_cde_info() callcost_arr[%s] = %0.2f  Xsundry=%s  Xsupplier=%s  last_DIVID=%s last_SEID=%s\n", cstr, callcost_arr[cstr], Xsundry, Xsupplier, last_DIVID, last_SEID)
	if ( Xinvoiceno == "All" )	# skip all for invoice numbers
		return
	if ( Xsundry == "All" )	# skip alls
		return
	# store info for later processing of T21 calls
	#if (last_SEID != "" && Xsupplier == t21_supplier && Xsundry == t21_sundry && last_SEID == 1043) {
	# seid now set here in ld_cde()
	if (last_SEID != "" && Xsupplier == t21_supplier && Xsundry == t21_sundry && last_SEID == 101043) {
		# store cost info for DIVID
		Xtag = last_DIVID
		t21gggrid_to_rentcost_arr[Xtag] = rentcost_arr[cstr]
		t21gggrid_to_callcost_arr[Xtag] = callcost_arr[cstr]
		t21gggrid_to_othercost_arr[Xtag] = othercost_arr[cstr]
		printf("store_t21calls_gggrid_cde_info() t21gggrid_to_callcost_arr[%s] = %0.2f\n", Xtag, t21gggrid_to_callcost_arr[Xtag])
	}
}


function store_t21calls_eggrid_cde_info()
{
	printf("store_t21calls_eggrid_cde_info() callcost_arr[%s] = %0.2f  Xsundry=%s  Xsupplier=%s  last_SID=%s last_SEID=%s\n", cstr, callcost_arr[cstr], Xsundry, Xsupplier, last_SID, last_SEID)
	if ( Xinvoiceno == "All" )	# skip alls for invoicenumber
		return
	if ( Xsundry == "All" )	# skip alls
		return
	# store info for later processing of T21 calls
	#if (last_SID != "" && last_SEID != "" && Xsupplier == t21_supplier && Xsundry == t21_sundry && last_SEID == 1043) {
	# seid now set here in ld_cde()
	if (last_SID != "" && last_SEID != "" && Xsupplier == t21_supplier && Xsundry == t21_sundry && last_SEID == 101043) {
		Xtag = last_DIVID "|" last_SID
		# create cde DIVID lookup for T21 calls processing
		# handle dups
		if ( t21eggrid_to_cdeDIVID[last_SID] != "" ) {
			# if stored t21 - cdeDIV has 0 callcost
			# then replace it with current one
			# if current rentcost is 0
			if ( t21gggrid_eggrid_to_callcost_arr[Xtag] == 0 && rentcost_arr[cstr] == 0 )
				t21eggrid_to_cdeDIVID[last_SID] = last_DIVID

		}
		else {
			t21eggrid_to_cdeDIVID[last_SID] = last_DIVID
		}
		print "store t21eggrid_to_cdeDIVID[" last_SID "] = " t21eggrid_to_cdeDIVID[last_SID]
		# store cost info for DIVID, SID
		t21gggrid_eggrid_to_rentcost_arr[Xtag] = rentcost_arr[cstr]
		t21gggrid_eggrid_to_callcost_arr[Xtag] = callcost_arr[cstr]
		t21gggrid_eggrid_to_othercost_arr[Xtag] = othercost_arr[cstr]
		printf("store_t21calls_eggrid_cde_info() t21gggrid_eggrid_to_callcost_arr[%s] = %0.2f\n", Xtag, t21gggrid_eggrid_to_callcost_arr[Xtag])
	}
}

#----------------------------------------------------------
#----------------------------------------------------------
# Process Detail data bellow ServiceID Summary

function process_SID_detail_data()
{
	print "process_SID_detail_data() last_SEID = " last_SEID

	XRENT = HIERIDx_to_rentcost_arr[last_HIERIDx]
	XCALL = HIERIDx_to_callcost_arr[last_HIERIDx]
	XOTHER = HIERIDx_to_othercost_arr[last_HIERIDx]
	XTOTAL = HIERIDx_to_totalcost_arr[last_HIERIDx]

	print "XRENT = " XRENT "  XCALL = " XCALL "  XOTHER = " XOTHER
	# SEID for...      rest                 VRT
	# mobile SEID and only if cde has call cost
	#if ( (last_SEID == 1044 || last_SEID == 2405) && XCALL > 0 ) {
	# seid now set here in ld_cde()
	# t21 cdr
	if ( last_SEID == 101043 ) {
		printf("skipping T21 CDR detail for %s\n", last_HIERIDx)
	}
	else # mobile SEID
	if ( last_SEID == 101044 && XCALL > 0 ) {
		procgsmcalldetails(gsmcallsfile)
	}
	else # voicemail SEID
	if ( last_SEID == 101047 ) {
		procvmlcalldetails(t21vmcallsfile)
	}
	else # switchboard SEID
	if ( last_SEID == 101030 ) {
		procswbcalldetails(t21swcallsfile)
	}
	else {
		printf("skipping detail for %s\n", last_HIERIDx)
	}
#rjsdet-
#	#else {
#		#printf("skipping detail for %s\n", last_HIERIDx)
#		# look SQL detail dir
#		#indetdir = "detail_" YYYYMM "_"  "all"
#		indetdir = detailodir
#		indetfile = "detail_" YYYYMM "_" last_sundry "_" last_SID
#		process_indetail_file(indetdir "/" indetfile ".unl")
#	#}
}


function process_indetail_file(indetailfile)
{
	#sqldetail

	#30074|2009/01|4|Telstra Mobile 208 4550 371|TELSTRA CORPORATION LTD|
	# 0407-326077|0407326077|TYH|NSA MOBILE PHONE 2084550371|
	# Feb 20 2009 12:06PM|Dec 22 2008 11:26AM|Network Services|
	# TBSFEB2009011194|VRT042703|VNE|V/LINE PASSENGER PTY LTD|
	# 72130||1044|Telco Voice Wireless 3rd|||1044|
	# Telco Voice Wireless 3rd|34572|KYNETON|KYNETON|NEWLYN TODD|
	# DIVERTED TO||CALL FORWARDING CHARGES|
	# Mobile Call Forwarding|CALL|
	# 101|30|0.0400|
	# ||||||||||||||||||||||||||||||

	create_siddetail_detail_file()
	print "process_indetail_file(" indetailfile ")"
	if ( (getline aline < indetailfile) < 0 ) {
		print "  - INDETNOTFOUND [" indetailfile "]"
		close(indetailfile)
		close(siddetail_fname)
		return
	}
	afound = 1
	while ( afound ) {
		#print "indetail aline = " aline
		split(aline, a_arr, "|")

		f = 0

		siddet_tBatch_ID = a_arr[++f]
		siddet_tBatch_BillingPeriod = a_arr[++f]
		siddet_tBatchType_SupplierID = a_arr[++f]
		siddet_tBatchType_Description = a_arr[++f]
		siddet_tSupplier_SupplierName = a_arr[++f]
		siddet_tServiceID_ServiceID = a_arr[++f]
		siddet_tServiceID_Service = a_arr[++f]
		siddet_tServiceType_Code = a_arr[++f]
		siddet_tServiceType_Description = a_arr[++f]
		siddet_tInvoice_InvoiceDate = a_arr[++f]
		siddet_tFinalisedTransaction_TxnDate = a_arr[++f]
		siddet_tReportGroup_GroupDesc = a_arr[++f]
		siddet_tInvoice_PlatinumFileName = a_arr[++f]
		siddet_tInvoice_PlatinumInvoiceNo = a_arr[++f]
		siddet_tCustomer_ShipTo = a_arr[++f]
		siddet_tCustomer_FullName = a_arr[++f]
		siddet_tCentre_Description = a_arr[++f]
		siddet_tActivity_Description = a_arr[++f]
		siddet_tElement_ElementCode = a_arr[++f]
		siddet_tElement_Description = a_arr[++f]
		siddet_tElement_CustEleCode = a_arr[++f]
		siddet_tElement_CustEleDesc = a_arr[++f]
		siddet_tElement_EleAdmCode = a_arr[++f]
		siddet_tElement_EleAdmDesc = a_arr[++f]
		siddet_tSubledger_CustSubLedger = a_arr[++f]
		siddet_tDepartment_CustDept = a_arr[++f]
		siddet_tLocation_Description = a_arr[++f]
		siddet_tPerson_Person = a_arr[++f]

		siddet_tOrigin_Description = a_arr[++f]
		siddet_tDestination_Description = a_arr[++f]
		siddet_tRateDescription_Description = a_arr[++f]
		siddet_tTransactionType_Description = a_arr[++f]
		siddet_tTransactionGroup_Description = a_arr[++f]
		siddet_tDialledNumber_Description = a_arr[++f]
		siddet_tFinalisedTransaction_Duration = a_arr[++f]

		siddet_tFinalisedTransaction_AmountExGST = a_arr[++f]

		siddet_tBatchType_Var01Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var01 = a_arr[++f]
		siddet_tBatchType_Var02Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var02 = a_arr[++f]
		siddet_tBatchType_Var03Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var03 = a_arr[++f]
		siddet_tBatchType_Var04Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var04 = a_arr[++f]
		siddet_tBatchType_Var05Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var05 = a_arr[++f]
		siddet_tBatchType_Var06Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var06 = a_arr[++f]
		siddet_tBatchType_Var07Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var07 = a_arr[++f]
		siddet_tBatchType_Var08Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var08 = a_arr[++f]
		siddet_tBatchType_Var09Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var09 = a_arr[++f]
		siddet_tBatchType_Var10Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var10 = a_arr[++f]
		siddet_tBatchType_Var11Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var11 = a_arr[++f]
		siddet_tBatchType_Var12Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var12 = a_arr[++f]
		siddet_tBatchType_Var13Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var13 = a_arr[++f]
		siddet_tBatchType_Var14Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var14 = a_arr[++f]
		siddet_tBatchType_Var15Description = a_arr[++f]
		siddet_tFinalisedTransaction_Var15 = a_arr[++f]

		spit_siddetail_todetailfile()

		if ( (getline aline < indetailfile) <= 0 )
			afound = 0
	}
	close(indetailfile)
	# close detail file
	close(siddetail_fname)
	siddetail_fname = ""
}


function create_siddetail_detail_file()
{
	siddetail_fname = sprintf("topdat/%s/data/siddetail/detail_%s_%s_%s_%s_%s_%s.csv", last_pardir, last_DIVID, last_SGID, last_SEID, last_DEPTID, last_SID, last_sundry);
	printf(">>>            siddetail_fname = %s\n", siddetail_fname);
	if ( (getline x < siddetail_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/siddetail", last_pardir)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		print "system 3 [" cmd "]"
		system(cmd)
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "ServiceID Detail", exbillperiod, "SDATE", "EDATE", ShipTo_to_CustomerDesc_arr[last_DIVID], last_DIVID, SGID_to_SGIDdesc_arr[last_SGID], last_SGID, SEID_to_SEIDdesc_arr[last_SEID], last_SEID, DEPTID_to_department_arr[last_DEPTID], last_DEPTID, last_SID, last_invoiceno, last_sundry, last_supplier, last_user, XRENT, XCALL, XOTHER, "Date","Time","Origin","Dialled Number","Description","Duration","Cost:Float") >siddetail_fname
		siddetail_file_exists = 0
	}
	else {
		printf("WARNING %d: siddetail_fname = %s exists.\n", NR, siddetail_fname)
		siddetail_file_exists = 1
	}
}




function spit_siddetail_todetailfile()
{

	# mobile m10 input file...
	# 30143|0434187604|OPTUS| M|Jan 2009|12/01/2009|134900|FRANKSTON|MELBOURNE|0397815031|P|27|0.09|

	# append record
	if ( siddetail_file_exists ) {	# skip deatils if already exists
		if ( siddetail_file_exists == 1 )
			print "siddetail file exists - skipping gen detail for " last_SID
		siddetail_file_exists = 2
		return
	}

	#Jan 05 2009 04:23PM
	dt = siddet_tFinalisedTransaction_TxnDate

	# cnv dt to "dd/mm/yyyy" and 24hr "hhmmss"
	MM = MMM_to_MM(substr(dt,1,3))
	DD = 0 + substr(dt,5,2)
	YYYY = 0 + substr(dt,8,4)
	siddet_cdate = sprintf("%02d/%02d/%04d", DD, MM, YYYY)
	hh = 0 + substr(dt,13,2)
	if ( hh == 12 && toupper(substr(dt,18,2)) == "AM" )
		hh = 0
	if ( hh < 12 && toupper(substr(dt,18,2)) == "PM" )
		hh += 12
	mm = 0 + substr(dt,16,2)
	ss = 0
	siddet_ctime = sprintf("%02s%02d%02d", hh, mm, ss)

	date = fixdate(siddet_cdate)

	durhh = int(siddet_tFinalisedTransaction_Duration / 3600)
	remd = siddet_tFinalisedTransaction_Duration - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	siddet_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	hh = substr(siddet_ctime,1,2)
	mm = substr(siddet_ctime,3,2)
	ss = substr(siddet_ctime,5,2)
	ctimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

	siddet_origin = siddet_tOrigin_Description
	## if blank use Location Desciption 
	#if ( siddet_origin == "" )
	#	siddet_origin = siddet_tLocation_Description
	# if blank use ServiceType Desciption
	if ( siddet_origin == "" )
		siddet_origin = siddet_tServiceType_Description

	# set dialled no
	siddet_dialled = siddet_tDialledNumber_Description

	# set destination/description info
	siddet_destination = siddet_tDestination_Description

	# User TransactionType Description (Rent/Calltype Desc)
	## if still blank
	#if ( siddet_destination == "" )
	if ( siddet_destination != "" )
		siddet_destination = siddet_destination " "
	siddet_destination = siddet_destination siddet_tTransactionType_Description

	# Rate Desc
	## if still blank
	#if ( siddet_destination == "" )
	if ( siddet_destination != "" )
		siddet_destination = siddet_destination " "
	siddet_destination = siddet_destination siddet_tRateDescription_Description

	## use var05 if still blank
	#if ( siddet_destination == "" )
	#	getdet_destination = siddet_tFinalisedTransaction_Var05

	## add call class description to destination
	#if ( siddet_callclass != "" )
	#	siddet_destination = siddet_destination " " siddet_callclass

	# if still blank use TransactionGroup Desc
	if ( siddet_destination == "" )
		getdet_destination = siddet_tTransactionGroup_Description


	if (siddet_tTransactionGroup_Description == "CALL") { # RENT/CALL/OTHER
		siddet_callclass = siddet_tRateDescription_Description
	}
	else {
		date = "CHARGE_DESC"
		ctimestr = "00:00:00"
		siddet_origin = siddet_tTransactionGroup_Description
		siddet_callclass = siddet_tTransactionType_Description
	}

	# remove dialled number from start of destination
	#if ( siddet_dialled == siddet_destination )
	#	siddet_destination = ""
	if ( siddet_dialled != "" ) {
		#sub(siddet_dialled,"",siddet_destination)
		if ( substr(siddet_destination,1,length(siddet_dialled)) == siddet_dialled )
			siddet_destination = substr(siddet_destination,length(siddet_dialled)+1)
	}
	# dialno_desc = sprintf("%s", siddet_dialled)
	# if ( siddet_destination != "" )
	# 	dialno_desc = sprintf("%s %s", dialno_desc, siddet_destination)

#ZZZZZ

	dialledno = siddet_dialled
	#printf("noddsuparr[%s] = %d\n", gggrid, noddsuparr[gggrid]);
	gggrid = siddet_tServiceID_ServiceID
	if ( 1 || noddsuparr[gggrid] == 1 ) {	# group has NO digit suppression
		expdialledno = dialledno;
	}
	else {
		# xx for last 2 digits in dialledno if length >= 0
		## supress for these callcategories only
		#if ( index("JALMESIOF", callcat) ) {
			dnl = length(dialledno);
			dnpreflen = dnl - 2;
			if ( dnpreflen < 0 )
				dnpreflen = 0;
			if ( dnl >= 0 ) {
				dnpref = substr(dialledno, 1, dnpreflen);
				expdialledno = sprintf("%sxx", dnpref);
			}
		#}
		#else {
		#	expdialledno = dialledno;
		#}
	}

	siddet_cost = siddet_tFinalisedTransaction_AmountExGST

	csvstr = sprintf(",,,,,,,,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s,%s\n", date, ctimestr, siddet_origin, expdialledno, siddet_destination "~" aline, siddet_durstr, siddet_cost)

	#printf("%s", csvstr)
	printf("%s", csvstr) >>siddetail_fname
}



function MMM_to_MM(MMM)
{
	mmmstr["Jan"] = 1
	mmmstr["Feb"] = 2
	mmmstr["Mar"] = 3
	mmmstr["Apr"] = 4
	mmmstr["May"] = 5
	mmmstr["Jun"] = 6
	mmmstr["Jul"] = 7
	mmmstr["Aug"] = 8
	mmmstr["Sep"] = 9
	mmmstr["Oct"] = 10
	mmmstr["Nov"] = 11
	mmmstr["Dec"] = 12
	return 0 + mmmstr[MMM]
}


#----------------------------------------------------------
#----------------------------------------------------------
# Voicemail Call Details


function create_vmlextnsum_file()
{
	vmlextnsum_fname = sprintf("topdat/%s/data/vmlextnsum/vmlextnsum_%s_%s_%s_%s_%s_%s.csv", last_pardir, last_DIVID, last_SGID, last_SEID, last_DEPTID, last_SID, last_sundry);
	printf(">>>            vmlextnsum_fname = %s\n", vmlextnsum_fname);
	if ( (getline x < vmlextnsum_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/vmlextnsum", last_pardir)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		print "system 3 [" cmd "]"
		system(cmd)
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "Extension Voicemail Breakdown", exbillperiod, "SDATE", "EDATE", ShipTo_to_CustomerDesc_arr[last_DIVID], last_DIVID, SGID_to_SGIDdesc_arr[last_SGID], last_SGID, SEID_to_SEIDdesc_arr[last_SEID], last_SEID, DEPTID_to_department_arr[last_DEPTID], last_DEPTID, last_SID, last_invoiceno, last_sundry, last_supplier, last_user, XRENT, XCALL, XOTHER, "Extension","Surname","FirstName","Section","Title","InQuantity","InDuration","InCost","OutQuantity","OutDuration","OutCost","RentCost","TotalCost:Float") >vmlextnsum_fname
		vmlextnsum_file_exists = 0
	}
	else {
		printf("WARNING %d: vmlextnsum_fname = %s exists.\n", NR, vmlextnsum_fname)
		vmlextnsum_file_exists = 1
	}
}


function spit_vmlextnsum_tovmlextnsumfile()
{
	# append vmlextnsum call record data to vmlextnsum file

	if ( vmlextnsum_file_exists ) {	# skip deatils if already exists
		if ( vmlextnsum_file_exists == 1 )
			print "vmlextnsum file exists - skipping vml extnsumail for " last_SID
		vmlextnsum_file_exists = 2
		return
	}

	durhh = int(vmlextntot_duration["in"] / 3600)
	remd = vmlextntot_duration["in"] - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	vml_in_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	durhh = int(vmlextntot_duration["out"] / 3600)
	remd = vmlextntot_duration["out"] - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	vml_out_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	vmlitag = last_vml_eggrid "|" last_vml_extn
 	vml_t21surname = egridextn_to_t21surname_arr[vmlitag]
 	vml_t21firstname = egridextn_to_t21firstname_arr[vmlitag]
 	vml_t21section = egridextn_to_t21section_arr[vmlitag]
 	vml_t21title = egridextn_to_t21title_arr[vmlitag]

	csvstr = sprintf(",,,,,,,,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", last_vml_extn, vml_t21surname, vml_t21firstname, vml_t21section, vml_t21title, vmlextntot_count["in"], vml_in_durstr, vmlextntot_cost["in"], vmlextntot_count["out"], vml_out_durstr, vmlextntot_cost["out"], VMLEXTN_XRENT, vmlextntot_cost["in"] + vmlextntot_cost["out"] + VMLEXTN_XRENT)
	printf("VMLextnsum %s", csvstr)
	printf("%s", csvstr) >>vmlextnsum_fname
}



function create_vmldet_detail_file()
{
	vmldet_fname = sprintf("topdat/%s/data/vmldet/vmldet_%s_%s_%s_%s_%s_%s_%s.csv", last_pardir, last_DIVID, last_SGID, last_SEID, last_DEPTID, last_SID, vml_extn, last_sundry);
	printf(">>>            vmldet_fname = %s\n", vmldet_fname);
	if ( (getline x < vmldet_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/vmldet", last_pardir)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		print "system 3 [" cmd "]"
		system(cmd)
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "Voicemail Call Detail", exbillperiod, "SDATE", "EDATE", ShipTo_to_CustomerDesc_arr[last_DIVID], last_DIVID, SGID_to_SGIDdesc_arr[last_SGID], last_SGID, SEID_to_SEIDdesc_arr[last_SEID], last_SEID, DEPTID_to_department_arr[last_DEPTID], last_DEPTID, last_SID, vml_extn, vml_name, last_invoiceno, last_sundry, last_supplier, last_user, VMLEXTN_XRENT, 0, 0, "Date","Time", "Dialled Number","Description","Duration","Cost:Float") >vmldet_fname
		vmldet_file_exists = 0
	}
	else {
		printf("WARNING %d: vmldet_fname = %s exists.\n", NR, vmldet_fname)
		vmldet_file_exists = 1
	}
}


function spit_sdrrec_tovmldetfile()
{
	# append vmldet call record data to vmldet file

	if ( vmldet_file_exists ) {	# skip deatils if already exists
		if ( vmldet_file_exists == 1 )
			print "vmldet file exists - skipping vml detail for " last_SID
		vmldet_file_exists = 2
		return
	}

	date = fixdate(vml_cdate)

	durhh = int(vml_duration / 3600)
	remd = vml_duration - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	vml_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	hh = substr(vml_ctime,1,2)
	mm = substr(vml_ctime,3,2)
	ss = substr(vml_ctime,5,2)
	ctimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

	dialledno = vml_dialled

	csvstr = sprintf(",,,,,,,,,,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s\n", date, ctimestr, dialledno, vml_dirdesc, vml_durstr, vml_cost)
	printf("VMLdet %s", csvstr)
	printf("%s", csvstr) >>vmldet_fname

}


function procvmlcalldetails(vmlcallsfile)
{
	printf("\n")
	printf("procvmlcalldetails(%s) %s %s %s %s)\n", vmlcallsfile, last_SID, last_HIERIDxDUPcount, last_supplier, last_sundry)

	vmlextnsum_fname = ""
	vmldet_fname = ""

	vmlextntot_count["in"] = 0
	vmlextntot_duration["in"] = 0
	vmlextntot_cost["in"] = 0
	vmlextntot_count["out"] = 0
	vmlextntot_duration["out"] = 0
	vmlextntot_cost["out"] = 0

	create_vmlextnsum_file()

	vml_eggrid = substr(last_SID,3)

	#tmpvmlcallsfile = sprintf("%s.tmp", vmlcallsfile)
	cmd = "basename " vmlcallsfile
	cmd | getline basevmlcallsfile
	tmpvmlcallsfile = sprintf("%s/%s.tmp", logdir, basevmlcallsfile)
	print "tmpvmlcallsfile = " tmpvmlcallsfile

	system("rm -f " tmpvmlcallsfile)
	cmdstr = sprintf("grep -iF \"%s,%s,\" %s >%s", last_DIVID, vml_eggrid, vmlcallsfile, tmpvmlcallsfile)
	print "RUN: " cmdstr
	system(cmdstr)
	#system("cat " tmpvmlcallsfile)
	
	# count extensions
	last_vml_extn = ""
	vml_extncount = 0
	while ( (getline aline < tmpvmlcallsfile) > 0 ) {
		#print "VMLEXTNCOUNT aline = " aline "
		split(aline, a_arr, ",")
		vml_extn = a_arr[3]
		if ( vml_extn != last_vml_extn)
			++vml_extncount
		last_vml_extn = vml_extn
		#print "VMLEXTNCOUNT vml_extn = " vml_extn "   vml_extncount = " vml_extncount
	}
	close(tmpvmlcallsfile)

	if ( vml_extncount != 0 )
		VMLEXTN_XRENT = sprintf("%0.2f", XRENT / vml_extncount)
	else
		VMLEXTN_XRENT = 0

	print "SID = " last_SID "  " "XRENT = " XRENT "  " "vml_extncount = " vml_extncount "  " "VMLEXTN_XRENT = " VMLEXTN_XRENT

	#ALA,ALA01PWS,18171,09/02/2004,104508,39,60033,out,19000,O,Outgoing Internal Network,396,0.0,
	#gggrid, eggrid, inletno, calldate, endtime, $cdrtable.siteid, inoutno, "out", dialledno,  callcategory, calltypedesc, $cdrtable.duration, $cdrtable.callcost

	last_vml_eggrid = ""
	last_vml_extn = ""

	while ( (getline aline < tmpvmlcallsfile) > 0 ) {
		#print "VMLDET aline = " aline
		split(aline, a_arr, ",")
		f = 0
		vml_divid = a_arr[++f]
		vml_eggrid = a_arr[++f]
		vml_extn = a_arr[++f]
		vml_cdate = a_arr[++f]
		vml_ctime = a_arr[++f]
		vml_siteid = a_arr[++f]
		vml_inoutno = a_arr[++f]
		vml_direction = a_arr[++f]
		vml_dialled = a_arr[++f]
		vml_category = a_arr[++f]
		vml_calltypedesc = a_arr[++f]
		vml_duration = a_arr[++f]
		vml_cost = a_arr[++f]

		vml_cost = 0 + voicemailcallcost

		itag = vml_eggrid "|" vml_extn
		vml_name = egridextn_to_t21surname_arr[itag]

		vml_operator = ""
		vml_dirdesc = ""
		if ( vml_direction == "in" ) {
			vml_dirdesc = "Incomming Voicemail Call"
		}
		if ( vml_direction == "out" ) {
			vml_dirdesc = "Voicemail Facility"
		}

		#printf("VMLDET: %s %s %s %s %s %s %s %s %d %0.2f\n", vml_divid, vml_eggrid, vml_extn, vml_name, vml_cdate, vml_ctime, vml_direction, vml_dialled, vml_duration, vml_cost)

		if ( vml_extn != last_vml_extn ) {
			if ( last_vml_extn != "" ) {
				if ( vmlextnsum_fname != "" ) {
					spit_vmlextnsum_tovmlextnsumfile()
				}
			}
			if ( vmldet_fname != "" ) {
				print "close(" vmldet_fname ")"
				# close vml detail file
				close(vmldet_fname)
				vmldet_fname == ""
				print "     incount=" vmlextntot_count["in"] "    outcount=" vmlextntot_count["out"]
				if ( (vmlextntot_count["in"] + vmlextntot_count["out"]) == 0 ) {
					#no calls so delete detail file
					# (only X dummies)
					print "remove empty vmldet_fname=" vmldet_fname
					system("rm -f " vmldet_fname)
				}
			}
			vmlextntot_count["in"] = 0
			vmlextntot_duration["in"] = 0
			vmlextntot_cost["in"] = 0
			vmlextntot_count["out"] = 0
			vmlextntot_duration["out"] = 0
			vmlextntot_cost["out"] = 0
			create_vmldet_detail_file()
		}

		# add call and spit if NOT dummy from directory
		if ( vml_category != "X" ) {
			vmlextntot_count[vml_direction] += 1
			vmlextntot_duration[vml_direction] += vml_duration
			vmlextntot_cost[vml_direction] += voicemailcallcost
			#print "vml_extn = " vml_extn "  vmlextntot_cost[" vml_direction "] = " vmlextntot_cost[vml_direction]

			spit_sdrrec_tovmldetfile()
		}

		last_vml_eggrid = vml_eggrid
		last_vml_extn = vml_extn
	}
	close(tmpvmlcallsfile)
	system("rm -f " tmpvmlcallsfile)

	if ( last_vml_extn != "" ) {
		if ( vmlextnsum_fname != "" ) {
			spit_vmlextnsum_tovmlextnsumfile()
		}
	}
	if ( vmldet_fname != "" ) {
		# close vml detail file
		close(vmldet_fname)
		vmldet_fname == ""
		print "     incount=" vmlextntot_count["in"] "    outcount=" vmlextntot_count["out"]
		if ( (vmlextntot_count["in"] + vmlextntot_count["out"]) == 0 ) {
			#no calls so delete detail file
			# (only X dummies)
			print "remove empty vmldet_fname=" vmldet_fname
			system("rm -f " vmldet_fname)
		}
	}

	# close vmlextnsum file
	close(vmlextnsum_fname)
	vmlextnsum_fname == ""
}



#----------------------------------------------------------
#----------------------------------------------------------
# Switchboard Call Details


function create_swbextnsum_file()
{
	swbextnsum_fname = sprintf("topdat/%s/data/swbextnsum/swbextnsum_%s_%s_%s_%s_%s_%s.csv", last_pardir, last_DIVID, last_SGID, last_SEID, last_DEPTID, last_SID, last_sundry);
	printf(">>>            swbextnsum_fname = %s\n", swbextnsum_fname);
	if ( (getline x < swbextnsum_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/swbextnsum", last_pardir)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		print "system 3 [" cmd "]"
		system(cmd)
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "Extension Switchboard Breakdown", exbillperiod, "SDATE", "EDATE", ShipTo_to_CustomerDesc_arr[last_DIVID], last_DIVID, SGID_to_SGIDdesc_arr[last_SGID], last_SGID, SEID_to_SEIDdesc_arr[last_SEID], last_SEID, DEPTID_to_department_arr[last_DEPTID], last_DEPTID, last_SID, last_invoiceno, last_sundry, last_supplier, last_user, XRENT, XCALL, XOTHER, "Extension","InQuantity","InDuration","InCost","OutQuantity","OutDuration","OutCost","TotalCost:Float") >swbextnsum_fname
		swbextnsum_file_exists = 0
	}
	else {
		printf("WARNING %d: swbextnsum_fname = %s exists.\n", NR, swbextnsum_fname)
		swbextnsum_file_exists = 1
	}
}


function spit_swbextnsum_toswbextnsumfile()
{
	# append swbextnsum call record data to swbextnsum file

	if ( swbextnsum_file_exists ) {	# skip deatils if already exists
		if ( swbextnsum_file_exists == 1 )
			print "swbextnsum file exists - skipping swb extnsumail for " last_SID
		swbextnsum_file_exists = 2
		return
	}

	durhh = int(swbextntot_duration["in"] / 3600)
	remd = swbextntot_duration["in"] - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	swb_in_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	durhh = int(swbextntot_duration["out"] / 3600)
	remd = swbextntot_duration["out"] - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	swb_out_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	csvstr = sprintf(",,,,,,,,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%s\n", last_swb_extn, swbextntot_count["in"], swb_in_durstr, swbextntot_cost["in"], swbextntot_count["out"], swb_out_durstr, swbextntot_cost["out"], swbextntot_cost["in"] + swbextntot_cost["out"])
	printf("SWBextnsum %s", csvstr)
	printf("%s", csvstr) >>swbextnsum_fname
}



function create_swbdet_detail_file()
{
	swbdet_fname = sprintf("topdat/%s/data/swbdet/swbdet_%s_%s_%s_%s_%s_%s_%s.csv", last_pardir, last_DIVID, last_SGID, last_SEID, last_DEPTID, last_SID, swb_extn, last_sundry);
	printf(">>>            swbdet_fname = %s\n", swbdet_fname);
	if ( (getline x < swbdet_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/swbdet", last_pardir)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		print "system 3 [" cmd "]"
		system(cmd)
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "Switchboard Call Detail", exbillperiod, "SDATE", "EDATE", ShipTo_to_CustomerDesc_arr[last_DIVID], last_DIVID, SGID_to_SGIDdesc_arr[last_SGID], last_SGID, SEID_to_SEIDdesc_arr[last_SEID], last_SEID, DEPTID_to_department_arr[last_DEPTID], last_DEPTID, last_SID, swb_extn, swb_name, last_invoiceno, last_sundry, last_supplier, last_user, 0, 0, 0, "Date","Time","Operator", "Dialled Number","Description","Duration","Cost:Float") >swbdet_fname
		swbdet_file_exists = 0
	}
	else {
		printf("WARNING %d: swbdet_fname = %s exists.\n", NR, swbdet_fname)
		swbdet_file_exists = 1
	}
}


function spit_sdrrec_toswbdetfile()
{
	# append swbdet call record data to swbdet file

	if ( swbdet_file_exists ) {	# skip deatils if already exists
		if ( swbdet_file_exists == 1 )
			print "swbdet file exists - skipping swb detail for " last_SID
		swbdet_file_exists = 2
		return
	}

	date = fixdate(swb_cdate)

	durhh = int(swb_duration / 3600)
	remd = swb_duration - (durhh * 3600)
	durmm = int(remd / 60)
	remd = remd - (durmm * 60)
	durss = remd
	swb_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

	hh = substr(swb_ctime,1,2)
	mm = substr(swb_ctime,3,2)
	ss = substr(swb_ctime,5,2)
	ctimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

	dialledno = swb_dialled

	csvstr = sprintf(",,,,,,,,,,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s,%s\n", date, ctimestr, swb_operator, dialledno, swb_dirdesc, swb_durstr, swb_cost)
	printf("SWBdet %s", csvstr)
	printf("%s", csvstr) >>swbdet_fname

}


function procswbcalldetails(swbcallsfile)
{
	printf("\n")
	printf("procswbcalldetails(%s) %s %s %s %s)\n", swbcallsfile, last_SID, last_HIERIDxDUPcount, last_supplier, last_sundry)

	swbextnsum_fname = ""
	swbdet_fname = ""

	swbextntot_count["in"] = 0
	swbextntot_duration["in"] = 0
	swbextntot_cost["in"] = 0
	swbextntot_count["out"] = 0
	swbextntot_duration["out"] = 0
	swbextntot_cost["out"] = 0

	create_swbextnsum_file()

	last_swb_extn = ""
	last_swb_name = ""

	swb_eggrid = substr(last_SID,3)

	#tmpswbcallsfile = sprintf("%s.tmp", swbcallsfile)
	cmd = "basename " swbcallsfile
	cmd | getline baseswbcallsfile
	tmpswbcallsfile = sprintf("%s/%s.tmp", logdir, baseswbcallsfile)
	print "tmpswbcallsfile = " tmpswbcallsfile

	system("rm -f " tmpswbcallsfile)
	cmdstr = sprintf("grep -iF \"%s,%s,\" %s >%s", last_DIVID, swb_eggrid, swbcallsfile, tmpswbcallsfile)
	print "RUN: " cmdstr
	system(cmdstr)
	#system("cat " tmpswbcallsfile)

	#ALA,ALA01PWS,18171,09/02/2004,104508,39,60033,out,19000,O,Outgoing Internal Network,396,0.0,
	#gggrid, eggrid, inletno, calldate, endtime, $cdrtable.siteid, inoutno, "out", dialledno,  callcategory, calltypedesc, $cdrtable.duration, $cdrtable.callcost

	while ( (getline aline < tmpswbcallsfile) > 0 ) {
		#print "SWBDET aline = " aline
		split(aline, a_arr, ",")
		f = 0
		swb_divid = a_arr[++f]
		swb_eggrid = a_arr[++f]
		swb_extn = a_arr[++f]
		swb_cdate = a_arr[++f]
		swb_ctime = a_arr[++f]
		swb_siteid = a_arr[++f]
		swb_inoutno = a_arr[++f]
		swb_direction = a_arr[++f]
		swb_dialled = a_arr[++f]
		swb_category = a_arr[++f]
		swb_calltypedesc = a_arr[++f]
		swb_duration = a_arr[++f]
		swb_cost = a_arr[++f]

		swb_cost = 0 + switchboardcallcost

		itag = swb_eggrid "|" swb_extn
		swb_name = egridextn_to_t21surname_arr[itag]

		swb_operator = ""
		swb_dirdesc = ""
		if ( swb_direction == "in" ) {
			swb_operator = swb_inoutno
			swb_dirdesc = "Incomming Enquiry Call"
		}
		if ( swb_direction == "out" ) {
			swb_operator = ""	# not available in cdr
			swb_dirdesc = "Operator Assisted Call"
		}

		#printf("SWBDET: %s %s %s %s %s %s %s %s %d %0.2f\n", swb_divid, swb_eggrid, swb_extn, swb_name, swb_cdate, swb_ctime, swb_direction, swb_dialled, swb_duration, swb_cost)

		if ( swb_extn != last_swb_extn ) {
			if ( last_swb_extn != "" ) {
				if ( swbextnsum_fname != "" ) {
					spit_swbextnsum_toswbextnsumfile()
				}
			}
			if ( swbdet_fname != "" ) {
				print "close(" swbdet_fname ")"
				# close swb detail file
				close(swbdet_fname)
				swbdet_fname == ""
				print "     incount=" swbextntot_count["in"] "    outcount=" swbextntot_count["out"]
				if ( (swbextntot_count["in"] + swbextntot_count["out"]) == 0 ) {
					#no calls so delete detail file
					# (only X dummies)
					print "remove empty swbdet_fname=" swbdet_fname
					system("rm -f " swbdet_fname)
				}
			}
			swbextntot_count["in"] = 0
			swbextntot_duration["in"] = 0
			swbextntot_cost["in"] = 0
			swbextntot_count["out"] = 0
			swbextntot_duration["out"] = 0
			swbextntot_cost["out"] = 0
			create_swbdet_detail_file()
		}

		# add call and spit if NOT dummy from directory
		if ( swb_category != "X" ) {
			swbextntot_count[swb_direction] += 1
			swbextntot_duration[swb_direction] += swb_duration
			swbextntot_cost[swb_direction] += switchboardcallcost
			#print "swb_extn = " swb_extn "  swbextntot_cost[" swb_direction "] = " swbextntot_cost[swb_direction]

			spit_sdrrec_toswbdetfile()
		}

		last_swb_extn = swb_extn
		last_swb_name = swb_name
	}
	close(tmpswbcallsfile)
	system("rm -f " tmpswbcallsfile)

	if ( last_swb_extn != "" ) {
		if ( swbextnsum_fname != "" ) {
			spit_swbextnsum_toswbextnsumfile()
		}
	}
	if ( swbdet_fname != "" ) {
		# close swb detail file
		close(swbdet_fname)
		swbdet_fname == ""
		print "     incount=" swbextntot_count["in"] "    outcount=" swbextntot_count["out"]
		if ( (swbextntot_count["in"] + swbextntot_count["out"]) == 0 ) {
			#no calls so delete detail file
			# (only X dummies)
			print "remove empty swbdet_fname=" swbdet_fname
			system("rm -f " swbdet_fname)
		}
	}

	# close swbextnsum file
	close(swbextnsum_fname)
	swbextnsum_fname == ""
}


#----------------------------------------------------------
#----------------------------------------------------------

function ld_platinv(platinvfile)
{
	printf("ld_platinv(%s)\n", platinvfile)

	while ( (getline platinvline < platinvfile) > 0 ) {
		split(platinvline, platinvarr, "|");
		#printf("platinvline=%s\n", platinvline);

		f = 0
		tblInvoice_ShipToCode = trim(platinvarr[++f])
		tblInvoice_PlatinumFileName = trim(platinvarr[++f])
		tblInvoice_PlatinumInvoiceNo = trim(platinvarr[++f])
		tblInvoicedTransaction_Var1 = trim(platinvarr[++f])
		tblTASSEMap_TASType = trim(platinvarr[++f])
		tblServiceGroup_ServiceGroupID = trim(platinvarr[++f])
		tblServiceGroup_ServiceGroupDesc = trim(platinvarr[++f])
		tblInvoiceDetail_ServiceElementID = trim(platinvarr[++f])
		tblServiceElements_ServiceElementDesc = trim(platinvarr[++f])
		tblInvoiceDetail_Period = trim(platinvarr[++f])
		tblInvoicedTransaction_ImportedFileID = trim(platinvarr[++f])
		tblInvoicedTransaction_InvoiceDetailID = trim(platinvarr[++f])
		tblInvoice_InvoiceDate = trim(platinvarr[++f])
		tblInvoiceDetail_Amount = trim(platinvarr[++f])

		tblInvoice_ShipToCode = toupper(tblInvoice_ShipToCode)

		platinv_parent = tblInvoice_ShipToCode
		platinv_batch = tblInvoice_PlatinumFileName
		platinv_invoicenumber = tblInvoice_PlatinumInvoiceNo
		platinv_sundry = tblInvoicedTransaction_Var1
		platinv_supplier = tblTASSEMap_TASType
		platinv_elementid = tblInvoiceDetail_ServiceElementID

		if ( platinv_parent == "" ) {
			print "FATAL ERROR: Blank parent (ShipTo) in platinum invoice data"
			exit 1
		}
		if ( platinv_batch == "" ) {
			print "FATAL ERROR: Blank PlatinumFileName in platinum invoice data"
			exit 1
		}
		if ( platinv_invoicenumber == "" ) {
			print "FATAL ERROR: Blank InvoiceNumber in platinum invoice data"
			exit 1
		}
		if ( platinv_sundry == "" ) {
			print "FATAL ERROR: Blank Sundry (var1) in platinum invoice data"
			exit 1
		}

		print ""
		print "        platinv_batch = " platinv_batch
		print "platinv_invoicenumber = " platinv_invoicenumber
		print "       platinv_sundry = " platinv_sundry
		print "    platinv_elementid = " platinv_elementid
		print "     platinv_supplier = " platinv_supplier
		print "       platinv_parent = " platinv_parent

		#if (length(inp_platinumBATCH) > 0 ) {
		#	if (length(inp_platinumBATCH) >= 7 && length(inp_platinumBATCH) <= 10) {
		#		if ( inp_platinumBATCH != platinv_invoicenumber ) {
		#			print "   skipping invoicenumber"
		#			continue			
		#		}
		#	}
		#	if (length(inp_platinumBATCH) > 10) {
		#		if ( inp_platinumBATCH != platinv_batch ) {
		#			print "   skipping batch"
		#			continue			
		#		}
		#	}
		#}

		# rjs 25/01/2005
		hack = 0
		if ( platinv_batch == "TBSJAN2005001288" && platinv_invoicenumber == "VRT025261" && platinv_sundry == "15321" && platinv_parent == "NAD" ) {
			platinv_batch = "TBSJAN2005001291"
			platinv_invoicenumber = "VRT025334"
			hack = 11
		}
		if ( platinv_batch == "TBSJAN2005001288" && platinv_invoicenumber == "VRT025261" && platinv_sundry == "15322" && platinv_parent == "NAD" ) {
			platinv_batch = "TBSJAN2005001291"
			platinv_invoicenumber = "VRT025334"
			hack = 12
		}
		if ( platinv_batch == "TBSJAN2005001288" && platinv_invoicenumber == "VRT025268" && platinv_sundry == "15321" && platinv_parent == "RBD" ) {
			platinv_batch = "TBSJAN2005001291"
			platinv_invoicenumber = "VRT025335"
			hack = 21
		}
		if ( platinv_batch == "TBSJAN2005001288" && platinv_invoicenumber == "VRT025268" && platinv_sundry == "15322" && platinv_parent == "RBD" ) {
			platinv_batch = "TBSJAN2005001291"
			platinv_invoicenumber = "VRT025335"
			hack = 22
		}
		if ( platinv_batch == "TBSJAN2005001288" && platinv_invoicenumber == "VRT025275" && platinv_sundry == "15322" && platinv_parent == "SDM" ) {
			platinv_batch = "TBSJAN2005001291"
			platinv_invoicenumber = "VRT025336"
			hack = 3
		}
		if ( platinv_batch == "TBSJAN2005001300" && platinv_invoicenumber == "VRT025348" && platinv_sundry == "15374" && platinv_parent == "ART" ) {
			platinv_batch = "TBSJAN2005001302"
			platinv_invoicenumber = "VRT025403"
			hack = 4
		}
		if ( hack ) {
			print "  XXXXXXXXXXXXXXXXXXX"
			print "  XX hack = " hack
			print "  XX        platinv_batch = " platinv_batch
			print "  XXplatinv_invoicenumber = " platinv_invoicenumber
			print "  XX       platinv_sundry = " platinv_sundry
			print "  XX     platinv_supplier = " platinv_supplier
			print "  XX       platinv_parent = " platinv_parent
		}


		htag = platinv_parent "|" platinv_invoicenumber "|" platinv_sundry
		printf("                htag = [%s]\n", htag)

		#itag = platinv_parent "|" platinv_sundry
		itag = platinv_parent "|" platinv_sundry "|" platinv_elementid
		printf("                itag = [%s]\n", itag)

		jtag = platinv_parent "|" platinv_invoicenumber
		printf("                jtag = [%s]\n", jtag)

		## rjs
		#if ( platinv_batch == "TBSAUG2004001134" ) {
		#	print "Warning 0 Skipping platinv_batch = " platinv_batch
		#	continue
		#}

		billingPeriod = tblInvoiceDetail_Period
		parent_invoicenumber_sundry_to_period_arr[htag] = billingPeriod
		print "  parent_invoicenumber_sundry_to_period_arr[" htag "] = " parent_invoicenumber_sundry_to_period_arr[htag]

		## rjs 18/8/2008
		if ( parent_sundry_to_platinv_batch_arr[itag] != "" && parent_sundry_to_platinv_batch_arr[itag] != platinv_batch ) {
			print "FATAL ERROR: conflicting platinum invoice batch / sundry"
			print "       platinv_parent = " platinv_parent
			print "        platinv_batch = " platinv_batch
			print "platinv_invoicenumber = " platinv_invoicenumber
			print "       platinv_sundry = " platinv_sundry
			print "                 itag = " itag
			print " parent_sundry_to_platinv_batch_arr[" itag "] = " parent_sundry_to_platinv_batch_arr[itag]
			exit 1
		}
		if ( parent_sundry_to_platinv_batch_arr[itag] == "" )
			parent_sundry_to_platinv_batch_arr[itag] = platinv_batch


		print "    parent_sundry_to_platinv_batch_arr[" itag "] = " parent_sundry_to_platinv_batch_arr[itag]

		## rjs 18/8/2008
		if ( parent_sundry_to_platinv_invoicenumber_arr[itag] != "" && parent_sundry_to_platinv_invoicenumber_arr[itag] != platinv_invoicenumber ) {
			print "FATAL ERROR: conflicting platinum invoice number / sundry"
			print "       platinv_parent = " platinv_parent
			print "        platinv_batch = " platinv_batch
			print "platinv_invoicenumber = " platinv_invoicenumber
			print "       platinv_sundry = " platinv_sundry
			print "                 itag = " itag
			print " parent_sundry_to_platinv_invoicenumber_arr[" itag "] = " parent_sundry_to_platinvinvoicenumber_arr[itag]
			exit 1
		}
		if ( parent_sundry_to_platinv_invoicenumber_arr[itag] == "" )
			parent_sundry_to_platinv_invoicenumber_arr[itag] = platinv_invoicenumber
		print "    parent_sundry_to_platinv_invoicenumber_arr[" itag "] = " parent_sundry_to_platinv_invoicenumber_arr[itag]
		
		if ( parent_invoicenumber_to_platinv_batch_arr[jtag] != "" && parent_invoicenumber_to_platinv_batch_arr[jtag] != platinv_batch ) {
			print "FATAL ERROR: conflicting platinum invoice batch / invoicenumber"
			print "       platinv_parent = " platinv_parent
			print "        platinv_batch = " platinv_batch
			print "platinv_invoicenumber = " platinv_invoicenumber
			print "       platinv_sundry = " platinv_sundry
			print "                 jtag = " jtag
			print " parent_invoicenumber_to_platinv_batch_arr[" jtag "] = " parent_invoicenumber_to_platinv_batch_arr[jtag]
			exit 1
		}
		parent_invoicenumber_to_platinv_batch_arr[jtag] = platinv_batch
		print "    parent_invoicenumber_to_platinv_batch_arr[" jtag "] = " parent_invoicenumber_to_platinv_batch_arr[jtag]

		# flag parent / sundry in platinv
		platinv_parent_sundry_arr[itag] = 1
		print "platinv_parent_sundry_arr[" itag "]=[" platinv_parent_sundry_arr[itag] "]"

		# flag parent in platinv
		platinv_parent_arr[platinv_parent] = 1
	}
	close(platinvfile);

}


#----------------------------------------------------------
#----------------------------------------------------------

#end Victrack custom
#rjs9
#####################################################
#####################################################


#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------

function ld_acccodeconf(acccodeconffile) {
	printf("ld_acccodeconf(%s)\n", acccodeconffile)
	system("date")
	while ( (getline aline < acccodeconffile) > 0 ) {
		split(aline, a_arr, "|")
		#printf("aline=%s\n", aline)
		f = 0

		# from gett21acccode
		#101|1626|VM 0 OPTION TO MOBILE 0408939653|7950002|

		acc_desc_siteid = clip(a_arr[++f])
		acc_desc_account_code = clip(a_arr[++f])
		acc_desc_account_desc = clip(a_arr[++f])
		acc_grid_grid = fixforfname(clip(a_arr[++f]))

		if ( acc_desc_account_code == "" )
			acc_desc_account_code == "Account Code"

		acccode = acc_desc_account_code

		acccode_to_siteid_arr[acccode] = acc_desc_siteid
		acccode_to_desc_arr[acccode] = acc_desc_account_desc
		acccode_to_egrid_arr[acccode] = acc_grid_grid
		print "   acccode_to_egrid_arr[" acccode "] = " acccode_to_egrid_arr[acccode]

	}
	close(acccodeconffile)
}


function ld_mobconf(mobconffile) {
	printf("ld_mobconf(%s)\n", mobconffile)
	system("date")
	while ( (getline aline < mobconffile) > 0 ) {
		split(aline, a_arr, "|")
		#printf("aline=%s\n", aline)
		f = 0

		## old mobconf
		#carriercode = clip(a_arr[++f])
		#mobile = clip(a_arr[++f])
		#surname = clip(a_arr[++f])
		#firstname = clip(a_arr[++f])
		#directoryID = clip(a_arr[++f])

		# from getSIDMAINTconf
		recordno = clip(a_arr[++f])
		mobconf_mobile = clip(a_arr[++f])
		sidmainttype = clip(a_arr[++f])
		mobconf_sdate = clip(a_arr[++f])
		mobconf_edate = clip(a_arr[++f])
		directoryID = clip(a_arr[++f])
		grid = fixforfname(clip(a_arr[++f]))
		datatype = clip(a_arr[++f])
		serviceproviderdir = clip(a_arr[++f])
		carriercode = clip(a_arr[++f])
		grname1 = clip(a_arr[++f])
		grname3 = fixforfname(clip(a_arr[++f]))
		surname = clip(a_arr[++f])
		firstname = clip(a_arr[++f])
		manufacturer = clip(a_arr[++f])
		model = clip(a_arr[++f])

		mobile = mobconf_mobile
		gsub(" ","",mobile)
		gsub("-","",mobile)

		if ( mobile == "" ) {
			mobile = "_blank_"
			print "ERROR: blank mobile in mobconf recordno = ["  recordno "]"
			directoryID = -2
		}
		if ( surname == "" )
			surname = "_blank_"
		if ( firstname == "" )
			firstname = "_blank_"
		name = surname
		if ( firstname != "_blank_")
			name = sprintf("%s %s", firstname, name)

		if ( directoryID == "" ) {
			directoryID = -1
			name = "Group Assigned"
		}

		if ( mobile != "_blank_" ) {
			mobsid = substr(mobile,1,4) "-" substr(mobile,5)
			mobile_to_sid_arr[mobile] = mobsid
			mobile_to_mob_carriercode_arr[mobile] = carriercode
			mobile_to_directoryID_arr[mobile] = directoryID
			mobile_to_grid_arr[mobile] = grid
			mobile_to_manufacturer_arr[mobile] = manufacturer
			mobile_to_model_arr[mobile] = model

			mobsid_to_directoryID_arr[mobsid] = directoryID

			if ( mobile_to_name_arr[mobile] == "" )
				mobile_to_name_arr[mobile] = name
			if ( mobile_to_name_arr[mobile] != name )
				mobile_to_name_arr[mobile] = "Multiple"

			print "mobconf: mobile_to_sid_arr[" mobile "] = " mobile_to_sid_arr[mobile]
			print "mobconf: mobile_to_directoryID_arr[" mobile "] = " mobile_to_directoryID_arr[mobile]
			print "mobconf: mobile_to_grid_arr[" mobile "] = " mobile_to_grid_arr[mobile]
			print "mobconf: mobile_to_name_arr[" mobile "] = " mobile_to_name_arr[mobile]
			print "mobconf: mobile_to_manufacturer_arr[" mobile "] = " mobile_to_manufacturer_arr[mobile]
			print "mobconf: mobile_to_model_arr[" mobile "] = " mobile_to_model_arr[mobile]
		}

	}
	close(mobconffile)
}


function ld_chargecat(chargecatfile) {
	printf("ld_chargecat(%s)\n", chargecatfile)
	system("date")
	while ( (getline aline < chargecatfile) > 0 ) {
		split(aline, a_arr, "|")
		#printf("aline=%s\n", aline)
		f = 0
		chargecatid = clip(a_arr[++f])
		chargecat = clip(a_arr[++f])
		importdatatypeid = clip(a_arr[++f])
		carriercode = clip(a_arr[++f])
		rectype = clip(a_arr[++f])
		chargeclasstype = clip(a_arr[++f])
		globalroaming = clip(a_arr[++f])

		Ctag = carriercode "|" rectype "|" chargeclasstype
		carriercode_chargeclasstype_to_chargecat_arr[Ctag] = chargecat

		print "  carriercode_chargeclasstype_to_chargecat_arr[" Ctag "] = " carriercode_chargeclasstype_to_chargecat_arr[Ctag]

		# global roaming flag
		if ( toupper(globalroaming) == "Y" ) {
			Ctag = carriercode "|" rectype "|" chargeclasstype
			gloroam_class_arr[Ctag] = 1
			print "  gloroam_class_arr[" Ctag "] = " gloroam_class_arr[Ctag]
		}

	}
	close(chargecatfile)
}




function ld_t21rt(t21rtfile) {
	printf("ld_t21rt(%s)\n", t21rtfile)
	system("date")
	while ( (getline aline < t21rtfile) > 0 ) {
		#print aline
		split(aline, a_arr, "|")
		f = 0

		rt_siteid = clip(a_arr[++f])
		rt_routeid = clip(a_arr[++f])
		rt_routetype = clip(a_arr[++f])
		rt_routedestination = clip(a_arr[++f])
		rt_routelocalid = clip(a_arr[++f])
		rt_shortholdingtime = clip(a_arr[++f])
		rt_trunkid = clip(a_arr[++f])
		rt_trunktype = clip(a_arr[++f])
		rt_trunklocalid = clip(a_arr[++f])
		rt_pulsetype = clip(a_arr[++f])
		rt_trunkdesc = clip(a_arr[++f])
		rt_altsiteid = clip(a_arr[++f])
		rt_ovrcar1 = clip(a_arr[++f])
		rt_ovrcar1siteid = clip(a_arr[++f])
		rt_ovrcar1acc = clip(a_arr[++f])
		rt_ovrcar2 = clip(a_arr[++f])
		rt_ovrcar2siteid = clip(a_arr[++f])
		rt_ovrcar2acc = clip(a_arr[++f])

		rte_siteid = clip(a_arr[++f])
		rte_routeid = clip(a_arr[++f])
		rte_trunklocalid = clip(a_arr[++f])
		rte_rt_remark = clip(a_arr[++f])
		rte_exch_a_end = clip(a_arr[++f])
		rte_exch_b_end = clip(a_arr[++f])
		rte_rt_code = clip(a_arr[++f])
		rte_tkid = clip(a_arr[++f])
		rte_len_no = clip(a_arr[++f])
		rte_naildn_len = clip(a_arr[++f])
		rte_cct_type = clip(a_arr[++f])
		rte_tk_remark = clip(a_arr[++f])
		rte_tk_status = clip(a_arr[++f])

		rti_siteid = clip(a_arr[++f])
		rti_routeid = clip(a_arr[++f])
		rti_trunklocalid = clip(a_arr[++f])
		rti_ipaddr = clip(a_arr[++f])
		rti_device = clip(a_arr[++f])

		site_sitenm1 = clip(a_arr[++f])

		rt_stripdd = rt_trunkid

		ROUTE = rt_siteid "_" rt_routeid

		ROUTE_to_ROUTEdesc_arr[ROUTE] = site_sitenm1 ": " rt_routedestination
		#print "ROUTE_to_ROUTEdesc_arr[" ROUTE "] = [" ROUTE_to_ROUTEdesc_arr[ROUTE] "]"

		ROUTE_to_SITEdesc_arr[ROUTE] = site_sitenm1

		site_trunk = rt_siteid "|" rt_trunklocalid

		site_trunk_to_stripdd[site_trunk] = rt_stripdd

		site_trunk_to_ovrcar1[site_trunk] = rt_ovrcar1
		site_trunk_to_ovrcar1acc[site_trunk] = rt_ovrcar1acc

		site_trunk_to_ovrcar2[site_trunk] = rt_ovrcar2
		site_trunk_to_ovrcar2acc[site_trunk] = rt_ovrcar2acc

	}
	close(t21rtfile)
}


function ld_t21extranges(t21extrangesfile) {
	printf("ld_t21extranges(%s)\n", t21extrangesfile)
	system("date")
	id = -1
	while ( (getline aline < t21extrangesfile) > 0 ) {
		++id
		split(aline, a_arr, "|")
		#printf("aline=%s\n", aline)
		f = 0
		siteid = clip(a_arr[++f])
		lorange = clip(a_arr[++f])
		hirange = clip(a_arr[++f])
		code1 = clip(a_arr[++f])
		code2 = clip(a_arr[++f])
		codedesc = clip(a_arr[++f])

		extrange_to_siteid_arr[lorange "|" hirange] = siteid
		#print "extrange_to_siteid_arr[" lorange "|" hirange "] = " siteid

		extrange_to_code1_arr[lorange "|" hirange "|" id] = code1
		extrange_to_code2_arr[lorange "|" hirange "|" id] = code2
		extrangecode1_to_code2_arr[lorange "|" hirange "|" code1 "|" id] = code2
	}
	close(t21extrangesfile)
}



function ld_t21dircsvfile(t21dircsvfile) {
	printf("ld_t21dircsvfile(%s)\n", t21dircsvfile)
	system("date")

	t21dirreccnt = -1
	while ( (getline aline < t21dircsvfile) > 0 ) {
		++t21dirreccnt
		split(aline, a_arr, ",")
		printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 2=%s 3=%s 4=%s 5=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4], a_arr[5])
		recordno = trim(a_arr[1])
		t21surname = trim(a_arr[2])
		t21firstname = trim(a_arr[3])
		extn = clip(a_arr[4])
		t21site = clip(a_arr[8])
		section = clip(a_arr[8])
		t21divsion = clip(a_arr[8])
		title = clip(a_arr[7])
		t21location = trim(a_arr[9])
		extgroupunique = fixforfname(clip(a_arr[10]))
		email = clip(a_arr[11])
		tec = clip(a_arr[11])
		faxno = clip(a_arr[12])
		voicemail = clip(a_arr[13])

		t21department = grid_to_grname1_arr[extgroupunique]
		staffid = "D" recordno
		master = "Y"

		# for mk_dircsvfile()
		print " recordno = [" recordno "]"
		recordno_to_aline_arr[recordno] = aline
		print "   recordno_to_aline_arr[" recordno "] = [" recordno_to_aline_arr[recordno] "]"
		t21dirreccnt_to_recordno_arr[t21dirreccnt] = recordno
		print "   t21dirreccnt_to_recordno_arr[" t21dirreccnt "] = [" t21dirreccnt_to_recordno_arr[t21dirreccnt] "]"

		recordno_to_master_arr[recordno] = master
		print "   recordno_to_master_arr[" recordno "] = [" recordno_to_master_arr[recordno] "]"

		if ( t21surname == "" )
			t21surname = "_blank_"
		if ( t21firstname == "" )
			t21firstname = "_blank_"

		if ( t21location == "" )
			t21location = "_blank_"

		gsub(" ","",t21mobile)
		gsub("-","",t21mobile)

		printf(" - extgroupunique = [%s]  extn = [%s]\n", extgroupunique, extn)
		printf("   t21surname = [%s]  t21firstname = [%s]\n", t21surname, t21firstname)
		printf("   t21site = [%s]  t21location = [%s]\n", t21site, t21location)
		printf("   t21division  = [%s]\n", t21division)
		printf("   t21department = [%s]\n", t21department)

		t21name = t21surname
		if ( t21firstname != "_blank_")
			t21name = sprintf("%s %s", t21firstname, t21name)
		recordno_to_t21name_arr[recordno] = t21name
		print "      recordno_to_t21name_arr[" recordno "] = [" recordno_to_t21name_arr[recordno] "]"

		recordno_to_staffid_arr[recordno] = staffid
		print "      recordno_to_staffid_arr[" recordno "] = [" recordno_to_staffid_arr[recordno] "]"

		recordno_to_extn_arr[recordno] = extn
		recordno_to_eggrid_arr[recordno] = extgroupunique
		recordno_to_t21site_arr[recordno] = t21site
		recordno_to_t21location_arr[recordno] = t21location

		# newbb1 BBBBBBB
		code1 = get_code1(extn)
		print "code1=[" code1 "]" "  extn=[" extn "]"
		if ( code1 != "" ) {
			if ( egrid_to_code1[extgroupunique] != "" && egrid_to_code1[extgroupunique] != code1 )
				print "ld_t21dircsv() extgroupunique=" extgroupunique " code1=" code1 "  already has egrid_to_code1[" extgroupunique "] set to [" egrid_to_code1[extgroupunique] "]"
			else 
				egrid_to_code1[extgroupunique] = code1
			print "egrid_to_code1[" extgroupunique "]=[" egrid_to_code1[extgroupunique] "]"
		}
		code2 = nget_code2(extn,code1)
		print "code2=[" code2 "]" "  extn=[" extn "]"

		# can't do this (code2 is NOT unique within extn group)
		#if ( code2 != "" ) {
		#	if ( egrid_to_code2[extgroupunique] != "" && egrid_to_code2[extgroupunique] != code2 )
		#		print "ld_t21dircsv() extgroupunique=" extgroupunique " code2=" code2 "  already has egrid_to_code2[" extgroupunique "] set to [" egrid_to_code2[extgroupunique] "]"
		#	else 
		#		egrid_to_code2[extgroupunique] = code2
		#	print "egrid_to_code2[" extgroupunique "]=[" egrid_to_code2[extgroupunique] "]"
		#}

		recordno_to_t21surname_arr[recordno] = t21surname
		recordno_to_t21firstname_arr[recordno] = t21firstname
		recordno_to_t21division_arr[recordno] = t21division
		recordno_to_t21department_arr[recordno] = t21department_college


		print "      recordno_to_extn_arr[" recordno "] = [" recordno_to_extn_arr[recordno] "]"
		print "      recordno_to_eggrid_arr[" recordno "] = [" recordno_to_eggrid_arr[recordno] "]"

		#itag = extgroupunique "|" extn
		itag = extn
		printf(" itag = [%s]\n", itag)

		if ( master == "Y" ) {
			if ( dirextn_to_recordno_arr[itag] == "" )
				dirextn_to_recordno_arr[itag] = recordno
			if ( dirextn_to_t21name_arr[itag] == "" )
				dirextn_to_t21name_arr[itag] = t21name
			if ( dirextn_to_t21name_arr[itag] != t21name )
				dirextn_to_t21name_arr[itag] = "Multiple"
			print "    dirextn_to_t21name_arr[" itag "] = [" dirextn_to_t21name_arr[itag] "]"

			if ( dirextn_to_t21surname_arr[itag] == "" )
				dirextn_to_t21surname_arr[itag] = t21surname
			if ( dirextn_to_t21surname_arr[itag] != t21surname )
				dirextn_to_t21surname_arr[itag] = "Multiple"

			if ( dirextn_to_t21firstname_arr[itag] == "" )
				dirextn_to_t21firstname_arr[itag] = t21firstname
			if ( dirextn_to_t21firstname_arr[itag] != t21firstname )
				dirextn_to_t21firstname_arr[itag] = "Multiple"

			if ( dirextn_to_t21site_arr[itag] == "" )
				dirextn_to_t21site_arr[itag] = t21site
			if ( dirextn_to_t21site_arr[itag] != t21site )
				dirextn_to_t21site_arr[itag] = "Multiple"

			if ( dirextn_to_t21location_arr[itag] == "" )
				dirextn_to_t21location_arr[itag] = t21location
			if ( dirextn_to_t21location_arr[itag] != t21location )
				dirextn_to_t21location_arr[itag] = "Multiple"

			if ( dirextn_to_t21division_arr[itag] == "" )
				dirextn_to_t21division_arr[itag] = t21division
			if ( dirextn_to_t21division_arr[itag] != t21division )
				dirextn_to_t21division_arr[itag] = "Multiple"

			if ( dirextn_to_t21department_arr[itag] == "" )
				dirextn_to_t21department_arr[itag] = t21department
			if ( dirextn_to_t21department_arr[itag] != t21department )
				dirextn_to_t21department_arr[itag] = "Multiple"
			dirextn_to_eggrid_arr[itag] = extgroupunique
		}

		if ( egrid_to_t21site_arr[extgroupunique] == "" )
			egrid_to_t21site_arr[extgroupunique] = t21site
		if ( egrid_to_t21site_arr[extgroupunique] != t21site )
			egrid_to_t21site_arr[extgroupunique] = "Multiple"

		extn_to_egridlist_arr[extn] = extn_to_egridlist_arr[extn] "|" extgroupunique

		if ( t21surname == ".INDIAL" ) {
			indial_nbr = gsub("X","[0-9]",telephone)
			indial_arr[telephone] = t21site
			print " indial_arr[" telephone "] = [" indial_arr[telephone] "]"
		}

	}
	close(t21dircsvfile)
}


function ld_t21groups4(t21groups4file) {
	printf("ld_t21groups4(%s)\n", t21groups4file)
	system("date")

	# loop first to look at G groups (to set grid_to_parentgroupid_arr)
	while ( (getline aline < t21groups4file) > 0 ) {
		split(aline, a_arr, "|")
		##printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 2=%s 3=%s 4=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4])
		parentgroupid = fixforfname(clip(a_arr[1]))
		grid = fixforfname(clip(a_arr[2]))
		grtype = clip(a_arr[3])
		grname1 = clip(a_arr[4])
		grname2 = clip(a_arr[5])
		grname3 = fixforfname(clip(a_arr[6]))

		#if ( parentgroupid == "" )
		#	parentgroupid = "NOPAR"
		if ( grname1 == "" )
			grname1 = "BLANK"
		if ( grname2 == "" )
			grname2 = "BLANK"
		if ( grname3 == "" )
			grname3 = "BLANK"

		# look at G groups only
		if ( grtype != "G" )
			continue

		printf(" G - parentgroupid = [%s]  grid = [%s]  grtype = [%s]", parentgroupid, grid, grtype)
		printf("   grname1 = [%s]  grname2 = [%s]  grname3 = [%s]\n", grname1, grname2, grname3)

		parentchild_arr[parentgroupid "|" grid] = 1

		childcount_arr[parentgroupid] += 1

		grid_to_parentgroupid_arr[grid] = parentgroupid
		print "  grid_to_parentgroupid_arr[" grid "] = [" grid_to_parentgroupid_arr[grid] "]"

		grid_to_grtype_arr[grid] = grtype
		grid_to_grname1_arr[grid] = grname1
		grid_to_grname2_arr[grid] = grname2
		grid_to_grname3_arr[grid] = grname3

		## default CENTRE/PROJECT to grname1/00000
		#CENTRE = grname1
		CENTRE = parentgroupid

		#if ( grtype == "G" ) {
		if ( substr(grid,1,4) == "DEPT" ) {
			#rjs4
			# CENTRE = grname3
			CENTRE = grid
			CENTREdesc = grname2
			CENTREdesc1 = grname1
			CENTREdesc2 = grname2
			CENTREdesc3 = grname3
                 	if ( CENTRE == "" )
				CENTRE = grname1
                 	if ( CENTRE == "" )
				CENTRE = grid
                 	if ( CENTREdesc == "" )
				CENTREdesc = grname1
			if ( CENTREdesc == "" )
				 CENTREdesc = grid
			if ( CENTREdesc3 == "" )
				 CENTREdesc = grname1
			CENTRE_to_CENTREdesc_arr[CENTRE] = CENTREdesc
			CENTRE_to_CENTREdesc1_arr[CENTRE] = CENTREdesc1
			CENTRE_to_CENTREdesc2_arr[CENTRE] = CENTREdesc2
			CENTRE_to_CENTREdesc3_arr[CENTRE] = CENTREdesc3
			print "CENTRE_to_CENTREdesc_arr[" CENTRE "] = " CENTRE_to_CENTREdesc_arr[CENTRE]
		}

		printf("              CENTRE = [%s]\n", CENTRE)
		#rjs9 - set in ld_cde()
		#grid_to_centre_arr[grid] = CENTRE

                #print "grid_to_centre_arr[" grid "]  = [" grid_to_centre_arr[grid] "]"

		#-------------

		CCP = grname1
		centre_dot_project = 0

		## default CENTRE/PROJECT to grname1/00000
		#CENTRE = grname1
		#PROJECT = "00000"
		CENTRE = parentgroupid
		PROJECT = grid

		if ( substr(grid,1,6) == "CENTRE" ) {
			#rjs4
                        CENTRE = parentgroupid
                        PROJECT = grid
			CCP = grnmame3
                        centre_dot_project = 1
                        print "IS centre_dot_project"
			PROJECTdesc = grname2
			PROJECTdesc1 = grname1
			PROJECTdesc2 = grname2
			PROJECTdesc3 = grname3
			if ( PROJECTdesc == "" )
				PROJECTdesc = grid
			if ( PROJECTdesc3 == "" )
				PROJECTdesc3 = grname2
			if ( PROJECTdesc3 == "" )
				PROJECTdesc3 = grid

			CENTREPROJECT_to_PROJECTdesc_arr[CENTRE "|" PROJECT] = PROJECTdesc
			CENTREPROJECT_to_PROJECTdesc1_arr[CENTRE "|" PROJECT] = PROJECTdesc1
			CENTREPROJECT_to_PROJECTdesc2_arr[CENTRE "|" PROJECT] = PROJECTdesc2
			CENTREPROJECT_to_PROJECTdesc3_arr[CENTRE "|" PROJECT] = PROJECTdesc3

			print "0: CENTREPROJECT_to_PROJECTdesc_arr[" CENTRE "|" PROJECT "] = " CENTREPROJECT_to_PROJECTdesc_arr[CENTRE "|" PROJECT]

			#CENTRE_to_GGRID_arr[CENTRE] = parentgroupid
			CENTRE_to_GGRID_arr[CENTRE] = CENTRE
			print "CENTRE_to_GGRID_arr[" CENTRE "] = " CENTRE_to_GGRID_arr[CENTRE]
			# rjs9 centre|project has multiple egrids
			# see ld_cde/ldt21detail which sets CENTREPROJECTSID_to_EGRID_arr
			#CENTREPROJECT_to_EGRID_arr[CENTRE "|" PROJECT] = grid
			#print "CENTREPROJECT_to_EGRID_arr[" CENTRE "|" PROJECT "] = " CENTREPROJECT_to_EGRID_arr[CENTRE "|" PROJECT]

			is_CENTRE_dot_PROJECT_arr[grid] = centre_dot_project
		}

		printf("              CENTRE = [%s]  PROJECT = [%s]\n", CENTRE, PROJECT)
		#rjs9 - set in ld_cde()
		#grid_to_ccp_arr[grid] = CCP
		#grid_to_centre_arr[grid] = CENTRE
		#grid_to_project_arr[grid] = PROJECT

                #print "grid_to_centre_arr[" grid "]  = [" grid_to_centre_arr[grid] "]"
                #print "grid_to_project_arr[" grid "]  = [" grid_to_project_arr[grid] "]"

	}
	close(t21groups4file)


	# now look at non G groups to handle service
	while ( (getline aline < t21groups4file) > 0 ) {
		split(aline, a_arr, "|")
		##printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 2=%s 3=%s 4=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4])
		parentgroupid = fixforfname(clip(a_arr[1]))
		grid = fixforfname(clip(a_arr[2]))
		grtype = clip(a_arr[3])
		grname1 = clip(a_arr[4])
		grname2 = clip(a_arr[5])
		grname3 = fixforfname(clip(a_arr[6]))

		#if ( parentgroupid == "" )
		#	parentgroupid = "NOPAR"
		if ( grname1 == "" )
			grname1 = "BLANK"
		if ( grname2 == "" )
			grname2 = "BLANK"
		if ( grname3 == "" )
			grname3 = "BLANK"

		# look at non G groups only
		if ( grtype == "G" )
			continue

		printf(" nonG - parentgroupid = [%s]  grid = [%s]  grtype = [%s]", parentgroupid, grid, grtype)
		printf("   grname1 = [%s]  grname2 = [%s]  grname3 = [%s]\n", grname1, grname2, grname3)

		parentchild_arr[parentgroupid "|" grid] = 1

		childcount_arr[parentgroupid] += 1

		grid_to_parentgroupid_arr[grid] = parentgroupid
		print "  grid_to_parentgroupid_arr[" grid "] = [" grid_to_parentgroupid_arr[grid] "]"

		grid_to_grtype_arr[grid] = grtype
		grid_to_grname1_arr[grid] = grname1
		grid_to_grname2_arr[grid] = grname2
		grid_to_grname3_arr[grid] = grname3

		#rjs9 - set in ld_cde()
		#grid_to_ccp_arr[grid] = CCP
		#grid_to_centre_arr[grid] = CENTRE
		#grid_to_project_arr[grid] = PROJECT

                #print "grid_to_centre_arr[" grid "]  = [" grid_to_centre_arr[grid] "]"
                #print "grid_to_project_arr[" grid "]  = [" grid_to_project_arr[grid] "]"
	}
	close(t21groups3file)


	# create entry for Unallocated Mobiles
	desc = "Unallocated Mobiles"
	grid = "UN_MOB"
	parentgroupid = "UNA"
	CENTRE = parentgroupid
	PROJECT = grid
	grid_to_grtype_arr[grid] = "E"
	grid_to_centre_arr[grid] = CENTRE
	grid_to_project_arr[grid] = PROJECT
	grid_to_ccp_arr[grid] = desc
	grid_to_grname1_arr[grid] = desc
	grid_to_grname2_arr[grid] = desc
	grid_to_grname3_arr[grid] = desc
	grid_to_parentgroupid_arr[grid] = parentgroupid
	#CENTRE_to_CENTREdesc_arr[CENTRE] = desc
	#CENTRE_to_CENTREdesc1_arr[CENTRE] = desc
	#CENTRE_to_CENTREdesc2_arr[CENTRE] = desc
	#CENTRE_to_CENTREdesc3_arr[CENTRE] = desc
	CENTREPROJECT_to_PROJECTdesc_arr[CENTRE "|" PROJECT] = desc
	CENTREPROJECT_to_PROJECTdesc1_arr[CENTRE "|" PROJECT] = desc
	CENTREPROJECT_to_PROJECTdesc2_arr[CENTRE "|" PROJECT] = desc
	CENTREPROJECT_to_PROJECTdesc3_arr[CENTRE "|" PROJECT] = desc
	CENTRE_to_GGRID_arr[CENTRE] = parentgroupid
	# rjs9 centre|project has multiple egrids
	# see ld_cde/ldt21detiail which sets CENTREPROJECTSID_to_EGRID_arr
	#CENTREPROJECT_to_EGRID_arr[CENTRE "|" PROJECT] = grid
	is_CENTRE_dot_PROJECT_arr[grid] = 0
	is_TENANT_arr[grid] = 0
}


function ld_t21WBDL(t21WBDLfile) {
	printf("ld_t21WBDL(%s)\n", t21WBDLfile)
	system("date")
	while ( (getline aline < t21WBDLfile) > 0 ) {
		split(aline, a_arr, "|")
		printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 2=%s 3=%s 4=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4])
		f = 0
		wbdconf_recordno = clip(a_arr[++f])
		wbdconf_distid = clip(a_arr[++f])
		wbdconf_distiddesc = clip(a_arr[++f])
		wbdconf_lastdist = clip(a_arr[++f])
		wbdconf_lastdistdate = clip(a_arr[++f])
		wbdconf_altemail = clip(a_arr[++f])
		wbdconf_altemailyn = clip(a_arr[++f])
		wbdconf_wbd_method = clip(a_arr[++f])
		wbdconf_wbd_type = clip(a_arr[++f])
		wbdconf_userid = toupper(clip(a_arr[++f]))
		wbdconf_passwd = clip(a_arr[++f])
		wbdconf_sdate = clip(a_arr[++f])
		wbdconf_edate = clip(a_arr[++f])
		wbdlist_grid = fixforfname(clip(a_arr[++f]))
		dc_email = clip(a_arr[++f])

		if ( wbdconf_distid == "" ) {
			printf("FATAL ERROR: blank wbdconf_distid aline=[%s]\n", aline)
			exit 1
		}

		DISTID = wbdconf_distid

		# Testing
		if ( Testing >= 1 && ! (DISTID == "1001" || DISTID == "1002") ) {
			#print "DISTID #TESTING... SKIP  DISTID = " DISTID
			continue
		}

		# skip PERSONAL type (used for passwords only)
		# virtual personal list entries will be created by 
		# create_virtual_user_dist_lists()
		if ( wbdconf_wbd_type == "PERSONAL" ) {
			continue;
		}

                directoryID_to_distid_arr[wbdconf_recordno] = wbdconf_distid

		distid_to_directoryID_arr[wbdconf_distid] = wbdconf_recordno
		distid_to_distiddesc_arr[wbdconf_distid] = wbdconf_distiddesc

		t21name = recordno_to_t21name_arr[wbdconf_recordno]
		distid_to_t21name_arr[wbdconf_distid] = t21name
		distid_to_userid_arr[wbdconf_distid] = wbdconf_userid
		if ( distid_to_userid_arr[wbdconf_distid] == "" ) {
			staffid = recordno_to_staffid_arr[wbdconf_recordno]
			distid_to_userid_arr[wbdconf_distid] = staffid
		}

		distid_to_wbd_method_arr[wbdconf_distid] = wbdconf_wbd_method
		distid_to_wbd_type_arr[wbdconf_distid] = wbdconf_wbd_type
		print "distid_to_wbd_type_arr[" wbdconf_distid "]=[" distid_to_wbd_type_arr[wbdconf_distid] "]"

		distgrid = wbdconf_distid "|" wbdlist_grid
		distgrid_arr[distgrid] = 1

		print "distid_to_t21name_arr[" wbdconf_distid "]=[" distid_to_t21name_arr[wbdconf_distid] "]"


		###############
		# create virual management distribution lists
		mng_distid = "mng" wbdconf_distid
		mng_distiddesc = "Management Reports"
		mng_wbd_type = "MANAGEMENT"
		virtual_management_distid_arr[mng_distid] = wbdconf_distid
		distid_to_directoryID_arr[mng_distid] = wbdconf_recordno
		distid_to_distiddesc_arr[mng_distid] = mng_distiddesc
		distid_to_t21name_arr[mng_distid] = t21name
		distid_to_userid_arr[mng_distid] = wbdconf_userid
		if ( distid_to_userid_arr[mng_distid] == "" ) {
			staffid = recordno_to_staffid_arr[wbdconf_recordno]
			distid_to_userid_arr[mng_distid] = staffid
		}
		distid_to_wbd_method_arr[mng_distid] = wbdconf_wbd_method
		distid_to_wbd_type_arr[mng_distid] = mng_wbd_type

		distgrid = mng_distid "|" wbdlist_grid
		distgrid_arr[distgrid] = 1

	}
	close(t21WBDLfile)
}


function ld_t21wbdexclude(t21wbdexcludefile) {
	printf("ld_t21wbdexclude(%s)\n", t21wbdexcludefile)
	system("date")
	while ( (getline aline < t21wbdexcludefile) > 0 ) {
		split(aline, a_arr, "|")
		printf("aline=%s\n", aline)
		#printf("a_arr 1=%s 2=%s 3=%s 4=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4])
		f = 0
		wbdexclude_servicetypeid = clip(a_arr[++f])
		wbdexclude_siteid = clip(a_arr[++f])
		wbdexclude_grid = fixforfname(clip(a_arr[++f]))
		wbdexclude_extnlo = clip(a_arr[++f])
		wbdexclude_extnhi = clip(a_arr[++f])

		exclude_arr[wbdexclude_servicetypeid "|" wbdexclude_siteid "|" wbdexclude_grid "|" wbdexclude_extnlo "|" wbdexclude_extnhi] = 1
	}
	close(t21wbdexcludefile)
}



function ld_exwebconf(exwebconffile)
{
	printf("ld_exwebconf(%s)\n", exwebconffile)
	system("date")

	#noddsupfile = "noddsup.txt"
	#while ( (getline custline < noddsupfile) > 0 ) {
	#	split(custline, noddsupgggrid, " ")
	#	noddsuparr[noddsupgggrid[1]] = 1
	#}
	#close(noddsupfile)

	while ( (getline exwebconfline < exwebconffile) > 0 ) {
		split(exwebconfline, exwebconfarr, ",")
		#printf("exwebconfline=%s\n", exwebconfline)
		#printf("exwebconfarr 1=%s 2=%s 3=%s 4=%s\n", exwebconfarr[1], exwebconfarr[2], exwebconfarr[3], exwebconfarr[4])

		exwebconf_parent = exwebconfarr[1]
		exwebconf_dialxx = exwebconfarr[2]
		exwebconf_email = exwebconfarr[3]
		exwebconf_emailyn = exwebconfarr[4]
		exwebconf_status1 = exwebconfarr[5]
		exwebconf_lastemailed = exwebconfarr[6]
		exwebconf_lastemaileddate = exwebconfarr[7]
		exwebconf_print = exwebconfarr[8]
		exwebconf_cdgroup = exwebconfarr[9]

		# flag parent in exwebconf
		exwebconf_parent_arr[exwebconf_parent] = 1

		#printf("noddsuparr[%s] = %d\n", exwebconf_parent, noddsuparr[exwebconf_parent])
		if ( toupper(exwebconf_dialxx) == "Y" )
			noddsuparr[exwebconf_parent] = 0
		else
			noddsuparr[exwebconf_parent] = 1
		#tmpgggrid = exwebconf_parent
		#if ( noddsuparr[tmpgggrid] == 1 )
		#	printf("     NO DD SUPPRESS\n")
		#else
		#	printf("     DO DD SUPPRESS\n")
	}
	close(exwebconffile)

}

#----------------------------------------------------------
# onnet ?

function is_onnet_mobile(nbr, i)
{
	i = index(nbr,"04")
	if ( i > 0 ) {
		realnbr = substr(nbr,i,10)
		if ( length(realnbr) == 10 ) {
			#print " is_onnet_mobile() 04  "  "nbr=[" nbr "]" "  mobile_to_sid_arr[" realnbr "] = [" mobile_to_sid_arr[realnbr] "]"
			if ( mobile_to_sid_arr[realnbr] != "" )
				return 1
		}
	}
	i = index(nbr,"614")
	if ( i > 0 ) {
		realnbr = "0" substr(nbr,i+2,9)
		if ( length(realnbr) == 10 ) {
			#print " is_onnet_mobile() 614 "  "nbr=[" nbr "]" "  mobile_to_sid_arr[" realnbr "] = [" mobile_to_sid_arr[realnbr] "]"
			if ( mobile_to_sid_arr[realnbr] != "" )
				return 1
		}
	}
	return 0
}


function is_onnet_fixed(nbr, i,tnbr)
{
	split(nbr, tmpnbr_arr, " ")
	tnbr = tmpnbr_arr[1]
	if ( i > 1 )
		tnbr = substr(nbr,i,10)
	# is an extn
	if ( dirextn_to_t21site_arr[tnbr] != "" ) {
		#print " is_onnet_fixed()"  "  dirextn_to_t21site_arr[" tnbr "] = [" dirextn_to_t21site_arr[tnbr] "]"
		return 1
	}
	for ( indial in indial_arr ) {
		if ( match(tnbr, indial) ) {
			#print " is_onnet_fixed()"  "  tnbr=[" tnbr "]" "  indial=[" indial "]"
			return 1
		}
		if ( match(tnbr, substr(indial,3)) ) {	# without area code
			#print " is_onnet_fixed()"  "  tnbr=[" tnbr "]" "  substr(" indial ",3)=[" substr(indial,3) "]"
			return 1
		}
	}
	return 0
}


function is_onnet(nbr,is_onnet)
{
	is_onnet = is_onnet_mobile(nbr) ? "ONNET Mobile" : ""
	if ( is_onnet == "" )
		is_onnet = is_onnet_fixed(nbr) ? "Extension" : ""
	return is_onnet
}


#----------------------------------------------------------
# premium 19XXXXxx mobile / 19XXXX... fixed line service ?

function is_premium_service(nbr, servtype, i,tnbr)
{
	split(nbr, tmpnbr_arr, " ")
	tnbr = tmpnbr_arr[1]
	if ( substr(tnbr,1,1) == "+" )
		tndr = substr(tnbr,2)
	i = match(tnbr,"^19[0-9][0-9][0-9][0-9]")
	if ( i > 0  ) {
		# mobile premium 19XXXXxx
		if ( servtype == "10" && length(tnbr) <= 8 ) {
			#print " is_premium_service()"  "  nbr=[" nbr "]" "  servtype=[" servtype "]" "  tnbr=[" tnbr "]"
			return 1
		}
		# fixed line 19XXXX...
		if ( servtype == "1" ) {
			#print " is_premium_service()"  "  nbr=[" nbr "]" "  servtype=[" servtype "]" "  tnbr=[" tnbr "]"
			return 1
		}
	}
	return 0
}


#----------------------------------------------------------
# apply stripdd and ovrcars to dialled no

function rtdialno(siteid,trunklocalid,dialledno)
{
	#print "rtdialno(" siteid "," trunklocalid "," dialledno ")"

	if ( dialledno == "" )
		return dialledno

	new_dialno = dialledno

	site_trunk = siteid "|" trunklocalid

	stripdd = site_trunk_to_stripdd[site_trunk]
	ovrcar1 = site_trunk_to_ovrcar1[site_trunk]
	ovrcar1acc = site_trunk_to_ovrcar1acc[site_trunk]
	ovrcar2 = site_trunk_to_ovrcar2[site_trunk]
	ovrcar2acc = site_trunk_to_ovrcar2acc[site_trunk]

	if ( strippdd > 0 ) {
		new_dialno = substr(dialledno,stripdd + 1)
		#print "rtdialno stripdd=" stripdd "  new_dialno=[" new_dialno "]" "  dialledno=[" dialledno "]"
	}

	len_ovrcar1acc = length(ovrcar1acc)
	if ( len_ovrcar1acc > 0 ) {
		if ( substr(ovrcar1acc,length_ovrcar1acc) == "+" )
			--len_ovrcar1acc
		if ( ovrcar1 != "" && len_ovrcar1acc > 0 && substr(new_dialno,1,len_ovrcar1acc) == substr(ovrcar1acc,1,len_ovrcar1acc) ) {
			new_dialno = substr(new_dialno,len_ovrcar1acc + 1)
			#print "rtdialno ovrcar1acc=[" ovrcar1acc "]  new_dialno=[" new_dialno "]" "  dialledno=[" dialledno "]"
			return new_dialno
		}
	}

	len_ovrcar2acc = length(ovrcar2acc)
	if ( len_ovrcar2acc > 0 ) {
		if ( substr(ovrcar2acc,length_ovrcar2acc) == "+" )
			--len_ovrcar2acc
		if ( ovrcar2 != "" && len_ovrcar2acc > 0 && substr(new_dialno,1,len_ovrcar2acc) == substr(ovrcar2acc,1,len_ovrcar2acc) ) {
			new_dialno = substr(new_dialno,len_ovrcar2acc + 1)
			#print "rtdialno ovrcar2acc=[" ovrcar2acc "]  new_dialno=[" new_dialno "]" "  dialledno=[" dialledno "]"
			return new_dialno
		}
	}

	#print "rtdialno done new_dialno=[" new_dialno "]" "  dialledno=[" dialledno "]"

	return new_dialno
}



#----------------------------------------------------------

function create_virtual_user_dist_lists()
{
	print "create_virtual_user_dist_lists()"
	system("date")
	# Mobile users...
	for ( mobile in mobile_to_directoryID_arr ) {
		directoryID = mobile_to_directoryID_arr[mobile]
		grid = mobile_to_grid_arr[mobile]
		mob_carrier = mobile_to_mob_carriercode_arr[mobile] 
		mob_name = mobile_to_name_arr[mobile]
		if ( mob_name == "_blank_" )
			mob_name = "BLANK NAME"
		sid = mobile_to_sid_arr[mobile]

		if ( (directoryID <= 0 || directoryID == "") && grid == "" ) {
			print "ERROR: create virtual user dist list: SKIPPING blank directoryID and grid for mobile=" mobile
			continue
		}

		staffid = recordno_to_staffid_arr[directoryID]
		if ( directoryID > 0 && staffid == "" ) {
			print "WARNING: create virtual user dist list: SKIPPING blank staffid for mobile=" mobile "  directoryID=" directoryID
			continue
		}

		# use extgroupunique from directory if mobconf grid is not set
		if ( grid == "" ) {
			grid = recordno_to_eggrid_arr[directoryID]
			if ( grid == "" ) {
				print "ERROR: create virtual user dist list: SKIPPING blank directory grid for mobile=" mobile "  directoryID=" directoryID
				continue
			}
		}

		Vdistid = staffid

		## Testing
		#if ( Testing >= 1 && !(Vdistid == "H9500027") ) {
		#	#print "DISTID TESTING... SKIP  Vdistid = " Vdistid
		#	continue
		#}

		if ( distid_to_distiddesc_arr[Vdistid] == "" ) {
			print "create Vdistid=[" Vdistid "]" "  staffid=[" staffid "]" "  directoryID=[" directoryID "]" "  grid=[" grid "]" "  sid=[" sid "]" "  mob_name=[" mob_name "]"  
			distid_to_directoryID_arr[Vdistid] = directoryID
			Vdistid_to_directoryID_arr[Vdistid] = directoryID
			distid_to_distiddesc_arr[Vdistid] = "Personal Reports for " mob_name
			distid_to_t21name_arr[Vdistid] = mob_name
			distid_to_userid_arr[Vdistid] = staffid
			distid_to_wbd_method_arr[Vdistid] = "WEB"
			distid_to_wbd_type_arr[Vdistid] = "PERSONAL"

			print "  distid_to_distiddesc_arr[" Vdistid "]=[" distid_to_distiddesc_arr[Vdistid] "]"
		}
		#else {
		#	print "WARNING: Existing distid_to_distiddesc_arr[" Vdistid "] = " distid_to_distiddesc_arr[Vdistid]
		#}

		Stag = grid "|" 10 "|" sid
		personal_egrid_servtype_SID_to_distid_arr[Stag] = Vdistid
		print "DEBUG: personal_egrid_servtype_SID_to_distid_arr[" Stag "] = " personal_egrid_servtype_SID_to_distid_arr[Stag]

		distgrid = Vdistid "|" Stag
		distgrid_arr[distgrid] = 1
	}
}


#----------------------------------------------------------


function create_egrid_distidlist()
{
	print "create_egrid_distidlist()"
	system("date")
	for (grid in grid_to_grtype_arr ) {
		if ( grid_to_grtype_arr[grid] != "E" )
			continue
		for ( DISTID in distid_to_distiddesc_arr ) {
			# do all grids in distlist
			for ( dgstr in distgrid_arr ) {
				split(dgstr, dgstr_arr, "|")
				if ( DISTID != dgstr_arr[1] )
					continue
				distgrid = dgstr_arr[2]

				# keep a list of egrids in distids
				# (see addstar code below)
				if ( grid_to_grtype_arr[distgrid] == "E" && distgrid == grid ) {
					distid_egrid_arr[DISTID "|" grid] = 1
				}

				# Vdistid not added to distgrid_arr yet !
				#distservtype = dgstr_arr[3]
				#distsid = dgstr_arr[4]
				#if ( distservtype != "" || distsid != "" ) {
				#	# skip single servtype/sid
				#	# (personal Vdistid)
				#	continue
				#}

				if (test_grid1_belongs_to_grid2(grid, distgrid)) {
					if ( distid_to_wbd_type_arr[DISTID] == "MANAGEMENT" ) {
						if ( mng_egrid_distidlist_arr[grid] != "" )
							mng_egrid_distidlist_arr[grid] = mng_egrid_distidlist_arr[grid] "|" DISTID
						else
							mng_egrid_distidlist_arr[grid] = DISTID
					}
					else {
						if ( egrid_distidlist_arr[grid] != "" )
							egrid_distidlist_arr[grid] = egrid_distidlist_arr[grid] "|" DISTID
						else
							egrid_distidlist_arr[grid] = DISTID
					}
					distid_allegrid_arr[DISTID "|" grid] = 1
				}

			}
		}
	}
}




#----------------------------------------------------------

function get_siteid(extn)
{
	for ( extrngstr in extrange_to_siteid_arr ) {
		split(extrngstr, extrngstr_arr, "|")
		#print "getsiteid extn = " extn "   extrngstr_arr[1] = " extrngstr_arr[1] "   extrngstr_arr[2] = " extrngstr_arr[2]
		if ( extn >= extrngstr_arr[1] && extn <= extrngstr_arr[2] ) {
			
			#print "get_siteid found siteid = " extrange_to_siteid_arr[extrngstr] "  for extn = " extn
			#print "      extrngstr_arr[1] = " extrngstr_arr[1] "   extrngstr_arr[2] = " extrngstr_arr[2]
			
			return extrange_to_siteid_arr[extrngstr]
		}
	}
	return -1
}


function get_code1(extn)
{
	for ( extrngstr in extrange_to_code1_arr ) {
		split(extrngstr, extrngstr_arr, "|")
		if ( extn >= extrngstr_arr[1] && extn <= extrngstr_arr[2] ) {
			
			#print "get_code1 found code1 = " extrange_to_code1_arr[extrngstr] "  for extn = " extn
			#print "      extrngstr_arr[1] = " extrngstr_arr[1] "   extrngstr_arr[2] = " extrngstr_arr[2]
			
			return extrange_to_code1_arr[extrngstr]
		}
	}
	return ""
}


function get_code2(extn)
{
	for ( extrngstr in extrange_to_code2_arr ) {
		split(extrngstr, extrngstr_arr, "|")
		if ( extn >= extrngstr_arr[1] && extn <= extrngstr_arr[2] ) {
			
			#print "get_code2 found code2 = " extrange_to_code2_arr[extrngstr] "  for extn = " extn
			#print "      extrngstr_arr[1] = " extrngstr_arr[1] "   extrngstr_arr[2] = " extrngstr_arr[2]
			
			return extrange_to_code2_arr[extrngstr]
		}
	}
	return ""
}


function nget_code2(extn,code1)
{
	for ( extrngcode1str in extrangecode1_to_code2_arr ) {
		split(extrngcode1str, extrngcode1str_arr, "|")
		#print "nget_code2 extn=[" extn "]" "  code1=[" code1 "]" "  extrngcode1str=[" extrngcode1str "]"
		#print "      extrngcode1str_arr[1] = " extrngcode1str_arr[1] "   extrngcode1str_arr[2] = " extrngcode1str_arr[2] "   extrngcode1str_arr[3] = " extrngcode1str_arr[3]
		if ( extn >= extrngcode1str_arr[1] && extn <= extrngcode1str_arr[2] && extrngcode1str_arr[3] == code1 ) {
			#print "nget_code2  found code2=[" extrangecode1_to_code2_arr[extrngcode1str] "]"
			return extrangecode1_to_code2_arr[extrngcode1str]
		}
	}
	return ""
}


#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------

##############################################################
# add extension totals to correct back billing output

function spit_oldbb1(grid, extn)
{
	#print "spit_oldbb1(" grid "," extn ")"
	gn_ccpcode = grid_to_ccp_arr[grid]
	cc_pc = gn_ccpcode

	CENTRE = grid_to_centre_arr[grid]
	PROJECT = grid_to_project_arr[grid]
	## rjs9
	#pargrid = grid_to_parentgroupid_arr[grid]
	#CENTRE = grid_to_centre_arr[pargrid]
	#PROJECT = grid_to_project_arr[pargrid]

	last_inv_cc_pc = ""
	last_inv_grid = ""

	# total call cost for extension
	tot_ccost = totalcost_arr["TOTAL" "|" "1" "|" CENTRE "|" PROJECT "|" extn "|" "All" "|" "All"]
	# total equipment/service charge for extension
	tot_ecost = totalcost_arr["TOTAL" "|" 2 "|" CENTRE "|" PROJECT "|" extn "|" "All" "|" "All"]

	code1 = get_code1(extn)
	code2 = get_code2(extn)

	print "spit_oldbb1(" grid "," extn ")  cc_pc=" cc_pc "   code1=" code1 "  code2=" code2

	# Add campus code to centre.project for valid cost-centres only
	# and set correct output file extension
	if ( is_CENTRE_dot_PROJECT_arr[grid] ) {
		cc = substr(gn_ccpcode,1,5)
		pc = substr(gn_ccpcode,7,5)
		cc_pc = CENTRE "." PROJECT "." code2
		outfileext=".txt"
		delim="|"
		outfile = "oldTIMS_" eyyyymmdd outfileext
	}
	else
	if ( is_TENANT_arr[grid] ) {
		outfileext="_invoice.csv"
		delim=","
		outfile = "oldTIMS_" eyyyymmdd outfileext
		inv_outfile = "oldTIMS_" eyyyymmdd outfileext
		inv_tot_ccost_exgst = sprintf("%.2f", mround2(inv_tot_ccost_exgst + tot_ccost))
		inv_tot_ecost_exgst = sprintf("%.2f", mround2(inv_tot_ecost_exgst + tot_ecost))
		last_inv_cc_pc = cc_pc
		last_inv_grid = grid
	}
	else {
		outfileext=".other"
		delim="|"
		outfile = "oldTIMS_" eyyyymmdd outfileext
	}

	#itag = grid "|" extn
	itag = extn
	surname = dirextn_to_t21surname_arr[itag]
	firstname = dirextn_to_t21firstname_arr[itag]
	division = dirextn_to_t21division_arr[itag]
	department = dirextn_to_t21department_arr[itag]
	location = dirextn_to_t21location_arr[itag]

	if ( surname == "_blank_" )
		surname = ""
	if ( firstname == "_blank_" )
		firstname = ""
	if ( division == "_blank_" )
		division = ""
	if ( department == "_blank_" )
		department = ""
	if ( location == "_blank_" )
		location = ""

	name_sep = " "
	if ( firstname == "" || surname == "" )
		name_sep = ""
	dep_sep = " "
	if ( division == "" || division == "" )
		dep_sep = ""

	# SKIP 0 cost SPARE
	# (test grid incase Master not set in Directory ie.extn not in T21E csv)
	if ( outfileext == ".other" ) {
		if ( (surname == ".SPARE" || grid == "SPARE") && tot_ccost == 0 && tot_ecost == 0 )
			return
	}

	# do output
	outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f%s%.2f", extn, delim, firstname, name_sep, surname, delim, department, dep_sep, division, delim, location, delim, cc_pc, delim, syyyymmdd, delim, eyyyymmdd, delim, mround2(tot_ccost), delim, mround2(tot_ecost))
	print outstr1 >> outfile
	close(outfile)
	#print "BB1 " outfile ": " outstr1

}


function spit_oldbb1_inv_totGST()
{
	#print "spit_oldbb1_inv_totGST()"
	# extn totals are ex gst
	outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f%s%.2f", "Total", delim, "Ex. GST", "", "", delim, grid_to_grname3[last_inv_grid], "", "", delim, "", delim, last_inv_cc_pc, delim, syyyymmdd, delim, eyyyymmdd, delim, mround2(inv_tot_ccost_exgst), delim, mround2(inv_tot_ecost_exgst))
	print outstr1 >> inv_outfile

	inv_tot_ccost_gst = sprintf("%.2f", mround2(10 * inv_tot_ccost_exgst / 100))
	inv_tot_ecost_gst = sprintf("%.2f", mround2(10 * inv_tot_ecost_exgst / 100))

	inv_tot_ccost_incgst = sprintf("%.2f", mround2(inv_tot_ccost_exgst + inv_tot_ccost_gst))
	inv_tot_ecost_incgst = sprintf("%.2f", mround2(inv_tot_ecost_exgst + inv_tot_ecost_gst))
	outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f%s%.2f", "Total", delim, "Inc. GST", "", "", delim, grid_to_grname3[last_inv_grid], "", "", delim, "", delim, last_inv_cc_pc, delim, syyyymmdd, delim, eyyyymmdd, delim, mround2(inv_tot_ccost_incgst), delim, mround2(inv_tot_ecost_incgst))
	print outstr1 >> inv_outfile
	last_inv_cc_pc = ""
	last_inv_grid = ""
	inv_tot_ccost_exgst = 0
	inv_tot_ecost_exgst = 0
}


##############################################################
# newbb1 - includes all service type
# newbb1 BBBBBBBB

function spit_newbb1(grid, sid, servtype)
{
	#print "spit_newbb1(" grid "," sid "," servtype ")"
	gn_ccpcode = grid_to_ccp_arr[grid]
	cc_pc = gn_ccpcode

	CENTRE = grid_to_centre_arr[grid]
	PROJECT = grid_to_project_arr[grid]
	## rjs9
	#pargrid = grid_to_parentgroupid_arr[grid]
	#CENTRE = grid_to_centre_arr[pargrid]
	#PROJECT = grid_to_project_arr[pargrid]

	newlast_inv_cc_pc = ""
	newlast_inv_grid = ""

	# total call cost
	tot_cost = totalcost_arr["TOTAL" "|" servtype "|" CENTRE "|" PROJECT "|" sid "|" "All" "|" "All"]

	# mobile GROUP ASSIGNED mobile
	#if ( servtype == "10" && sid == "" )

#ZZZZZ
#	# if no extn (mostly mobile GROUP ASSIGNED mobile)
#	if ( t21_extn == "" ) {
#		code1 = ""
#		code2 = ""
#	}
#	else {
#		# from extension range table get
#		code1 = get_code1(t21_extn)
#		code2 = get_code2(t21_extn)
#	}

#ZZZZZ
#	if ( servtype == "10" ) {
#		directoryID = mobsid_to_directoryID_arr[sid]
#		code1 = recordno_to_t21site_arr[directoryID]
#	}
#	else {
#		#code1 = dirextn_to_t21site_arr[t21extn]
#		code1 = get_code1(t21_extn)
#		#code2 = get_code2(t21_extn)
#	}
#	if ( code1 == "" )
#		code1 = egrid_to_t21site_arr[grid]
#
#	if ( t21_extn == "" ) {
#		#code1 = ""
#		code2 = ""
#	}
#	else {
#		# from extension range table get
#		#code1 = get_code1(t21_extn)
#		code2 = nget_code2(t21_extn,code1)
#	}

	if ( t21_extn == "" ) {
		code1 = ""
		code2 = ""
	}
	else {
		if ( servtype == "10"  && t21_extn == 0 ) {
			directoryID = mobsid_to_directoryID_arr[sid]
			code1 = recordno_to_t21site_arr[directoryID]
			code2 = nget_code2(t21_extn,code1)
		}
		else {
			# from extension range table get
			code1 = get_code1(t21_extn)
			code2 = get_code2(t21_extn)
		}
	}
#ZZZZZ

	# can't do this (code2 is NOT unique within extn group)
	#code1 = egrid_to_code1[grid]
	#code2 = egrid_to_code2[grid]
	if ( code2 == "" ) 
		code2 = "16"	# default

	# set output format
	outfmt = 1

	# Add campus code to centre.project for valid cost-centres only
	# and set correct output file extension
	if ( is_CENTRE_dot_PROJECT_arr[grid] ) {
		if ( code2 != "" ) {
			cc_pc = CENTRE "." PROJECT "." code2
		}
		else {
			cc_pc = CENTRE "." PROJECT
		}
		outfileext=".txt"
		delim="|"
		outfile = "TIMS_" eyyyymmdd outfileext
		outfmt = 1
	}
	else
	if ( is_TENANT_arr[grid] ) {
		outfileext="_invoice.csv"
		delim=","
		outfile = "TIMS_" eyyyymmdd outfileext
		newinv_delim = delim
		newinv_outfile = outfile
		newinv_tot_cost_exgst = sprintf("%.2f", mround2(newinv_tot_cost_exgst + tot_cost))
		newlast_inv_cc_pc = cc_pc
		newlast_inv_grid = grid
		outfmt = 2
	}
	else {
		outfileext=".other"
		delim="|"
		outfile = "TIMS_" eyyyymmdd outfileext
		outfmt =1
	}

	print "spit_newbb1(" grid "," sid "," servtype ")  sid=[" sid "]  cc_pc=[" cc_pc "]   CENTRE=[" CENTRE "]  PROJECT=[" PROJECT "]  code1=[" code1 "]  code2=[" code2 "]  directoryID=[" directoryID "]"

	set_project_displayinfo(CENTRE, PROJECT)

	if ( servtype != 10 ) {
		#itag = grid "|" sid
		itag = sid
		surname = dirextn_to_t21surname_arr[itag]
		firstname = dirextn_to_t21firstname_arr[itag]
		division = dirextn_to_t21division_arr[itag]
		department = dirextn_to_t21department_arr[itag]
		location = dirextn_to_t21location_arr[itag]
	}
	else {
		if ( directoryID != "" ) {
			surname = recordno_to_t21surname_arr[directoryID]
			firstname = recordno_to_t21firstname_arr[directoryID]
			division = recordno_to_t21division_arr[directoryID]
			department = recordno_to_t21department_arr[directoryID]
			location = recordno_to_t21location_arr[directoryID]
		}
		else {
			surname = ""
			firstname = ""
			division = ccpdesc
			department = ""
			location = ""
		}
	}

	if ( surname == "_blank_" )
		surname = ""
	if ( firstname == "_blank_" )
		firstname = ""
	if ( division == "_blank_" )
		division = ""
	if ( department == "_blank_" )
		department = ""
	if ( location == "_blank_" )
		location = ""

	name_sep = " "
	if ( firstname == "" || surname == "" )
		name_sep = ""
	dep_sep = " "
	if ( division == "" || division == "" )
		dep_sep = ""

	# SKIP 0 cost SPARE
	# test grid incase Master not set in Directory ie. extn not in T21E csv
	if ( servtype != 10 && outfileext == ".other" ) {
		if ( (surname == ".SPARE" || grid == "SPARE") && tot_cost == 0 )
			return
	}

	# do output
	if ( outfmt == 2 ) {	# output format 2, (no division)
		outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f", sid, delim, firstname, name_sep, surname, delim, department, delim, location, delim, cc_pc, delim, syyyymmdd, delim, eyyyymmdd, delim, servtype, delim, SERVTYPE_to_GLcode_arr[servtype], delim, SERVTYPE_to_SERVTYPEdesc_arr[servtype], delim, mround2(tot_cost))
	}
	else {			# output format 1, (default)
		outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f", sid, delim, firstname, name_sep, surname, delim, department, dep_sep, division, delim, location, delim, cc_pc, delim, syyyymmdd, delim, eyyyymmdd, delim, servtype, delim, SERVTYPE_to_GLcode_arr[servtype], delim, SERVTYPE_to_SERVTYPEdesc_arr[servtype], delim, mround2(tot_cost))
	}

	print outstr1 >> outfile
	close(outfile)
	#print "BB1 " outfile ": " outstr1

}


function spit_newbb1_inv_totGST()
{
	#print "spit_newbb1_inv_totGST()"
	# sid totals are ex gst
	outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f", "Total", newinv_delim, "Ex. GST", "", "", newinv_delim, grid_to_grname3[newlast_inv_grid], "", "", newinv_delim, "", newinv_delim, newlast_inv_cc_pc, newinv_delim, syyyymmdd, newinv_delim, eyyyymmdd, newinv_delim, last_SERVTYPE, newinv_delim, SERVTYPE_to_GLcode_arr[last_SERVTYPE], newinv_delim, SERVTYPE_to_SERVTYPEdesc_arr[last_SERVTYPE], newinv_delim, mround2(newinv_tot_cost_exgst))

 print outstr1 >> newinv_outfile

	newinv_tot_cost_gst = sprintf("%.2f", mround2(10 * newinv_tot_cost_exgst / 100))

	newinv_tot_cost_incgst = sprintf("%.2f", newinv_tot_cost_exgst + newinv_tot_cost_gst)
	outstr1 = sprintf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%.2f", "Total", newinv_delim, "Inc. GST", "", "", newinv_delim, grid_to_grname3[newlast_inv_grid], "", "", newinv_delim, "", newinv_delim, newlast_inv_cc_pc, newinv_delim, syyyymmdd, newinv_delim, eyyyymmdd, newinv_delim, last_SERVTYPE, newinv_delim, SERVTYPE_to_GLcode_arr[last_SERVTYPE], newinv_delim, SERVTYPE_to_SERVTYPEdesc_arr[last_SERVTYPE], newinv_delim, mround2(newinv_tot_cost_incgst))
	print outstr1 >> newinv_outfile
	newlast_inv_cc_pc = ""
	newlast_inv_grid = ""
	newinv_tot_cost_exgst = 0
}


##############################################################

function spit_dircsv()
{
	printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", recordno, t21surname, t21firstname, out_extn, out_t21mobile, t21mobile_carrier, out_centre, out_project, ccpdesc, title, t21site, t21location) >>dircsvfile_fname
}


function split_dir_aline(aline)
{
	if ( aline == "" ) {
		#print "WARNING: split_dir_aline BLANK aline DISTID = " DISTID
		t21surname = ""
		t21firstname = ""
		extn = ""
		t21mobile = ""
		t21mobile_carrier = ""
		title = ""
		t21site = ""
		t21location = ""
		extgroupunique = ""
		email = ""
		fax = ""
		telephone = ""
		mobsid = ""
	}
	split(aline, a_arr, ",")
	##printf("aline=%s\n", aline)
	#printf("a_arr 1=%s 2=%s 3=%s 4=%s 5=%s\n", a_arr[1], a_arr[2], a_arr[3], a_arr[4], a_arr[5])
	#recordno = clip(a_arr[1])
	t21surname = clip(a_arr[2])
	t21firstname = clip(a_arr[3])
	extn = clip(a_arr[4])
	t21mobile = clip(a_arr[5])
	t21mobile_carrier = clip(a_arr[6])
	title = clip(a_arr[7])
	t21site = clip(a_arr[8])
	t21location = clip(a_arr[9])
	extgroupunique = clip(a_arr[10])
	email = clip(a_arr[11])
	fax = clip(a_arr[12])
	telephone = clip(a_arr[13])

	gsub(" ","",t21mobile)
	gsub("-","",t21mobile)
	mobsid = mobile_to_sid_arr[t21mobile]
}


function mk_dircsvfile() {
	printf("mk_dircsvfile() DISTID = %s\n", DISTID)
	system("date")

	dircsvfile_fname = sprintf("topdat/%s/%s/data/direnq/T21E_%s.csv", monthdir, DISTID, DISTID)

	#if ( virtual_management_distid_arr[DISTID] != "" ) {
	#	# vmng
	#	## dircsv file is sym link for virtual management lists
	#	#real_distid = virtual_management_distid_arr[DISTID]
	#	#real_dircsvfile_fname = sprintf("../../../%s/data/direnq/T21E_%s.csv", real_distid, real_distid)
	#	#cmd = "ln -s \"" real_dircsvfile_fname "\" \"" dircsvfile_fname "\""
	#	#print "virtual management distid dircsv symlink [" cmd "]"
	#	#system(cmd)
	#	return
	#}

	newdir = sprintf("topdat/%s/%s/data/direnq", monthdir, DISTID)
	cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
	system(cmd)
	add_fname_to_fnamelist(dircsvfile_fname)

	for ( reccnt = 0; reccnt <= t21dirreccnt; ++reccnt ) {
		recordno = t21dirreccnt_to_recordno_arr[reccnt]

		aline = recordno_to_aline_arr[recordno]

		#print "  t21dirreccnt_to_recordno_arr[" reccnt "] = [" t21dirreccnt_to_recordno_arr[reccnt] "]"
		#print "  recordno = [" recordno "]" "  aline = [" aline "]"

		if ( aline == "" ) {
			print "WARNING: skipping BLANK aline DISTID = " DISTID "  reccnt=[" reccnt "]" "  recordno=[" recordno "]"
			continue
		}
		split_dir_aline(aline)
		if ( reccnt == 0 ) {		# header
			out_centre = "}Centre__"
			out_project = "Project_"
			# rjs9
			#ccpdesc = "Centre_Project_Description______________"
			ccpdesc = "Description_____________________________"

			out_extn = "}#eXtension"
			out_t21mobile = "}#Mobile__________"

			spit_dircsv()
			continue
		}
	
		# is a PERSONAL virtual distid
		# only has one user entry
		Vdistid_directoryID = Vdistid_to_directoryID_arr[DISTID]
		if ( Vdistid_directoryID != "" ) {
			print "   mk_dircsv PERSONAL Vdistid = DISTID"
			print "        Vdistid_directoryID = [" Vdistid_directoryID "]"
			aline = recordno_to_aline_arr[Vdistid_directoryID]
			#print "        aline = [" aline "]"
			split_dir_aline(aline)
			out_extn = extn
			extngroupid = extgroupunique

			out_centre = grid_to_centre_arr[extngroupid]
			out_project = grid_to_project_arr[extngroupid]
			## rjs9
			#pargrid = grid_to_parentgroupid_arr[extngroupid]
			#out_centre = grid_to_centre_arr[pargrid]
			#out_project = grid_to_project_arr[pargrid]

			# rjs9
			#ccpdesc = CENTREPROJECT_to_PROJECTdesc_arr[out_centre "|" out_project]
			shipto = CENTREPROJECT_to_ShipTo_arr[out_centre "|" out_project]
			#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]
			ccpdesc = costcentre

			out_t21mobile = mobsid
			spit_dircsv()
			break
		}

		# configured distid directory contains all entries
		# belonging to the distribution list

		## skip non master
		#if ( recordno_to_master_arr[recordno] != "Y" ) {
		#	continue
		#}

		pgrid = grid_to_parentgroupid_arr[extgroupunique]
		if ( pgrid == "SPARE" || pgrid == "UNPROG" )	# skip
			continue

		# test if dir entry belongs to a grid in distlist
		for ( dgstr in distgrid_arr ) {
			split(dgstr, dgstr_arr, "|")
			if ( DISTID != dgstr_arr[1] )
				continue
			distgrid = dgstr_arr[2]
			distservtype = dgstr_arr[3]
			if ( distservtype != "" ) {	# only this servtype
				distsid = dgstr_arr[4]
				incl = 0
				if ( distsid != "" ) {	# only this sid
					if (distservtype == "1" && distsid ==  extn) {
						print "  mk_dircsv SINGLE extn dgstr = " dgstr
						incl =  1
					}
					if (distservtype == "10" && distsid == mobsid) {
						print "  mk_dircsv SINGLE mobile dgstr = " dgstr
						incl =  1
					}
				}
				else {
					incl = 1
				}
				if ( incl ) {
					extngroupid = distgrid
					out_extn = extn
					out_centre = grid_to_centre_arr[extngroupid]
					out_project = grid_to_project_arr[extngroupid]
					## rjs9
					#pargrid = grid_to_parentgroupid_arr[extngroupid]
					#out_centre = grid_to_centre_arr[pargrid]
					#out_project = grid_to_project_arr[pargrid]
					# rjs9
					#ccpdesc = CENTREPROJECT_to_PROJECTdesc_arr[out_centre "|" out_project]
					shipto = CENTREPROJECT_to_ShipTo_arr[out_centre "|" out_project]
					#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]
					ccpdesc = costcentre

					out_t21mobile = mobsid
					spit_dircsv()
				}
				continue
			}

			#print "mk_dircsvfile() test extgroupunique=" extgroupunque " belongs to distgrid=" distgrid
			if (test_grid1_belongs_to_grid2(extgroupunique, distgrid)) {
				extngroupid = extgroupunique
				out_centre = grid_to_centre_arr[extngroupid]
				out_project = grid_to_project_arr[extngroupid]
				## rjs9
				#pargrid = grid_to_parentgroupid_arr[extngroupid]
				#out_centre = grid_to_centre_arr[pargrid]
				#out_project = grid_to_project_arr[pargrid]

				# rjs9
				#ccpdesc = CENTREPROJECT_to_PROJECTdesc_arr[out_centre "|" out_project]
				shipto = CENTREPROJECT_to_ShipTo_arr[out_centre "|" out_project]
				#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]
				ccpdesc = costcentre

				out_extn = extn
				out_t21mobile = mobsid

				spit_dircsv()
				break
			}
		}
	}
	close(dircsvfile_fname)
}



function ln_userhtml_index()
{
	t21name = distid_to_t21name_arr[DISTID]
	t21userid = distid_to_userid_arr[DISTID]
	t21wbd_method = distid_to_wbd_method_arr[DISTID]
	t21wbd_type = distid_to_wbd_type_arr[DISTID]
	if ( t21userid == "" )
		t21userid = distid_to_directoryID_arr[DISTID]
	userhtml_index_fname = sprintf("topdat/%s Click here to run your reports.html", t21userid)
	cmd = "rm -f " "\"" userhtml_index_fname "\"" "; ln -s ../img/user.html " "\"" userhtml_index_fname "\""
	print "ln_userhtml_index() cmd=[" cmd "]"
	system(cmd)
}

function mk_useridfile()
{
	t21name = distid_to_t21name_arr[DISTID]
	t21userid = distid_to_userid_arr[DISTID]
	t21wbd_method = distid_to_wbd_method_arr[DISTID]
	t21wbd_type = distid_to_wbd_type_arr[DISTID]
	if ( t21userid == "" )
		t21userid = distid_to_directoryID_arr[DISTID]
	usertag = sprintf("%s_%s", t21userid, monthtag)
	printf("usertag = %s\n", usertag)
	userid_fname = sprintf("topdat/%s/%s.txt", monthdir, usertag)

	# generate userid file
	printf("Generate userid (%s) for %s %s\n", userid_fname, t21name, monthdir)

	if ( (getline x < userid_fname) >= 0 ) { # exists (multiple dist lists)
		close(userid_fname)
		printf("\r\n") >>userid_fname
		printf("------\r\n") >>userid_fname
		printf("\r\n") >>userid_fname
	}
	else {					# create it
		printf("\r\n") >userid_fname
	}


	printf("Bilmax21 Web Billing Reports\r\n") >>userid_fname
	printf("For %s", t21name) >>userid_fname
	printf(" (userid: %s)", t21userid) >>userid_fname
	printf(" Period: %s\r\n", exbillperiod) >>userid_fname
	if ( retroBDL == "1" ) {
		printf("\r\n") >>userid_fname
		print "Retrospective Generation/Regeneration of Distribution List" >>userid_fname
	}
	printf("\r\n") >>userid_fname

	printf("Distribution Method: %s\r\n", t21wbd_method) >>userid_fname
	printf("          List Type: %s\r\n", t21wbd_type) >>userid_fname
	printf("\r\n") >>userid_fname
	add_fname_to_fnamelist(userid_fname)

	printf("%s - %s\r\n", DISTIDdesc, DISTID) >>userid_fname
	
	close(userid_fname)
}


function mk_distidfile()
{
	idtag = sprintf("%s_%s", DISTID, monthtag)
	#printf("idtag = %s\n", idtag)

	distidfile_dir = sprintf("topdat/%s/%s", monthdir, DISTID)
	distidfile_fname = sprintf("%s/%s.txt", distidfile_dir, idtag)

	cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", distidfile_dir, distidfile_dir)
	system(cmd)

	DISTIDdesc = distid_to_distiddesc_arr[DISTID]

	distid_t21name = distid_to_t21name_arr[DISTID]
	distid_t21userid = distid_to_userid_arr[DISTID]
	if ( distid_t21userid == "" )
		distid_t21userid = distid_to_directoryID_arr[DISTID]
	distid_t21wbd_method = distid_to_wbd_method_arr[DISTID]
	distid_t21wbd_type = distid_to_wbd_type_arr[DISTID]

	# generate ID file
	printf("Generate distidfile (%s) for %s %s\n", distidfile_fname, distid_t21name, monthdir)

	printf("") >distidfile_fname
	printf("%s   (%s)\r\n", distid_t21name, distid_t21userid) >>distidfile_fname
	printf("\r\n") >distidfile_fname
	printf("Welcome to your Bilmax21 reports for %s\r\n", exbillperiod) >>distidfile_fname
	printf("\r\n") >>distidfile_fname
	printf("%s - %s\r\n", DISTIDdesc, DISTID) >>distidfile_fname
	printf("\r\n") >>distidfile_fname

	printf("Distribution Method: %s\r\n", distid_t21wbd_method) >>distidfile_fname
	printf("          List Type: %s\r\n", distid_t21wbd_type) >>distidfile_fname
	printf("\r\n") >>distidfile_fname

	printf("The Cost Centres/Services included in your reports for this month are as follows,\r\n") >>distidfile_fname
	printf("\r\n") >>distidfile_fname

	# do all grids/sids in distlist
	for ( dgstr in distgrid_arr ) {
		#print "dgstr=[" dgstr "]"
		split(dgstr, dgstr_arr, "|")
		if ( DISTID != dgstr_arr[1] )
			continue
		grid = dgstr_arr[2]
		distservtype = dgstr_arr[3]
		distsid = dgstr_arr[4]

		print "mk_distidfile DISTID = " DISTID " (" DISTIDdesc ")" "  grid = " grid  "  distservtype=" distservtype "  distsid=" distsid

		printf("\r\n") >>distidfile_fname

		printf("%-8.8s : %s - %s\r\n", grid, grid_to_grname2_arr[grid], grid_to_grname3_arr[grid]) >>distidfile_fname

		if ( distservtype != "" ) { #only this servtype
			#print "DEBUGMOB: 3a DISTID=" DISTID "  distservtype=" distservtype
			printf("\tServiceType %s\t - %s\r\n", distservtype, SERVTYPE_to_SERVTYPEdesc_arr[distservtype]) >>distidfile_fname
		}
		if ( distsid != "" ) {	# only this sid
			#print "DEBUGMOB: 3b DISTID=" DISTID "  distsid=" distsid
			printf("\t\tServiceID \t - %s\r\n", distsid) >>distidfile_fname
		}
		printf("\r\n") >>distidfile_fname
	}

	add_fname_to_fnamelist(distidfile_fname)
	close(distidfile_fname)
}


function distidfile_totals()
{
	#print "distidfile_totals()" " DISTID=[" DISTID "]" " SERVTYPE=[" SERVTYPE "]" " last_SERVTYPE=[" last_SERVTYPE "]" " CENTRE=[" CENTRE "]" " PROJECT=[" PROJECT "]"

	idtag = sprintf("%s_%s", DISTID, monthtag)

	# vmng
	svdistid = DISTID

	distidfile_fname = sprintf("topdat/%s/%s/%s.txt", monthdir, DISTID, idtag)
	if ( virtual_management_distid_arr[DISTID] != "" )
		DISTID = virtual_management_distid_arr[DISTID]
	if ( distidfile_created[DISTID] != 1 ) {
		mk_distidfile()
		distidfile_created[DISTID] = 1
	}

	# vmng
	DISTID = svdistid

	tot_cost = totalcost_arr["TOTAL" "|" SERVTYPE "|" CENTRE "|" PROJECT "|" SID "|" "All" "|" "All"]

	if ( SERVTYPE == 10 ) {	# mobile only

		if ( done_distidfile_servtype_arr[DISTID "|" SERVTYPE] == "" ) {
			printf("\r\n") >>distidfile_fname
			printf("-----------------------------------------------------\r\n") >>distidfile_fname
			printf("\r\n") >>distidfile_fname
			done_distidfile_servtype_arr[DISTID "|" SERVTYPE] = 1
		}

		if ( SERVTYPE != last_SERVTYPE || CENTRE != last_CENTRE || PROJECT != last_PROJECT ) {
			printf("\r\n") >>distidfile_fname
			CENTREdesc = CENTRE_to_CENTREdesc_arr[CENTRE]
			CCP = grid_to_ccp_arr[EGRID]
			printf("%s - GroupID: %-8.8s\r\n", SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], EGRID) >>distidfile_fname
			printf("    %s - %s\r\n", CENTREdesc, CCP) >>distidfile_fname
			printf("\r\n") >>distidfile_fname
		}

		printf("        %-30.30s %-15.15s %5.2f\r\n", t21name, SID, mround2(tot_cost)) >>distidfile_fname

	}

	close(distidfile_fname)
}


##############################################################

function gen_top_csv()
{
	# generate top csv file
	top_fname = sprintf("topdat/%s/data/top_%s.csv", monthdir, CENTRE)
	printf("%s,%s,%s,%s,%s,%s\n", "Monthly Service Reports", exbillperiod, "SDATE", "EDATE", CENTREdesc, CENTRE) >top_fname
	close(top_fname)
}


function cpy_img(x)
{
	# test if image already done
	imgmarkerfile = sprintf("topdat/%s/%s/index.html", monthdir, CENTRE)
	printf("cpy_img(%d): testing for %s\n", x, imgmarkerfile)
	if ( (getline xs < imgmarkerfile) < 0 ) {
		printf("%d: Copy image files for %s/%s\n", x, monthdir, CENTRE)
		# copy image folder dirs and files
		cmd = sprintf("cpyimg topdat/%s/%s 2>&1", monthdir, CENTRE)
		system(cmd)
	}
	else {
		printf("%d: Image ALREADY exists for %s/%s\n", x, monthdir, CENTRE)
	}
	close(imgmarkerfile)
}



##############################################################


function detail_fnames_to_fnamelist(centreproject)
{
	for ( cpstr in fname_to_SERVTYPECENTREPROJECT_arr ) {
		if ( fname_to_SERVTYPECENTREPROJECT_arr[cpstr] != centreproject )
			continue
		print "detail_fnames: SERVTYPE=" SERVTYPE "  CENTRE=" CENTRE "  PROJECT=" PROJECT "  cpstr=" cpstr
		add_fname_to_fnamelist(cpstr)
	}
}

function add_fname_to_fnamelist(fname)
{
	# vmng
	fdistid = DISTID
	if ( virtual_management_distid_arr[DISTID] != "" )
		fdistid = virtual_management_distid_arr[DISTID]

	fnamelist_fname = sprintf("topdat/%s/%s/fnamelist.csv",monthdir,fdistid)
	print fname >> fnamelist_fname
	close(fnamelist_fname)
}

#----------------------------------------------------------
# highest usage...

function do_highest_usage(distid,servtype,centre,project,egrid,sid)
{
	# fixed highest users
	if ( servtype == "1" ) {
		supplier = "Fixed Line"
		Wtag = "TOTAL" "|" servtype "|" centre "|" project "|" sid "|" supplier
		chg_cat = "All"

		chg_count = totalcount_arr[Wtag "|"  chg_cat]
		chg_duration = totalduration_arr[Wtag "|" chg_cat]
		chg_cost = totalcost_arr[Wtag "|" chg_cat]

		print "do_highest_usage: Wtag=" Wtag "  chg_cat=" chg_cat
		print "        chg_count=[" chg_count "]"
		print "     chg_duration=[" chg_duration "]"
		print "         chg_cost=[" chg_cost "]"

		htag = distid "|" servtype
		hobj = centre "|" project "|" sid 
		hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 

		# by cost
		hval = chg_cost
		hi_in( htag, 20, hi_sid_by_cost_arr, hobj, hval )

		# highest premium service users
		Stag = servtype "|" centre "|" project "|" sid
		if ( sid_premserv_count_arr[Stag] != "" ) {
			chg_count = sid_premserv_count_arr[Stag]
			chg_duration = sid_premserv_duration_arr[Stag]
			chg_cost = sid_premserv_cost_arr[Stag]
			htag = distid "|" servtype
			hobj = centre "|" project "|" sid
			hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 
			hval = chg_cost
			hi_in(htag, 20, hi_premserv_users_by_cost_arr, hobj, hval)
		}
	}

	# mobile highest users
	if ( servtype == "10" ) {
		supplier = "All"
		Wtag = "TOTAL" "|" servtype "|" centre "|" project "|" sid "|" supplier
		chg_cat = "All"
		
		chg_count = totalcount_arr[Wtag "|" "All_MOBILE_CDR"]
		chg_duration = totalduration_arr[Wtag "|" "All_MOBILE_CDR"]
		chg_cost = totalcost_arr[Wtag "|" chg_cat]

		print "do_highest_usage: Wtag=" Wtag "  chg_cat=" chg_cat
		print "        chg_count=[" chg_count "]"
		print "     chg_duration=[" chg_duration "]"
		print "         chg_cost=[" chg_cost "]"

		htag = distid "|" servtype
		hobj = centre "|" project "|" sid 
		hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 

		# by cost
		hval = chg_cost
		hi_in( htag, 20, hi_sid_by_cost_arr, hobj, hval )

		###############
		# SMS
		supplier = "All"
		Wtag = "TOTAL" "|" servtype "|" centre "|" project "|" sid "|" supplier
		chg_cat = "Mobile Messaging"

		chg_count = totalcount_arr[Wtag "|" chg_cat]
		chg_duration = totalduration_arr[Wtag "|" chg_cat]
		chg_cost = totalcost_arr[Wtag "|" chg_cat]

		print "do_highest_usage: Wtag=" Wtag "  chg_cat=" chg_cat
		print "        chg_count=[" chg_count "]"
		print "     chg_duration=[" chg_duration "]"
		print "         chg_cost=[" chg_cost "]"

		htag = distid "|" servtype
		hobj = centre "|" project "|" sid
		hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 

		# by mobile messaging by count
		hval = chg_count
		hi_in(htag, 20, hi_sid_mobile_messaging_by_count_arr, hobj, hval)

		# by mobile messaging by cost
		hval = chg_cost
		hi_in(htag, 20, hi_sid_mobile_messaging_by_cost_arr, hobj, hval)

		# global roaming users
		hobj = centre "|" project "|" sid
		chg_cost = gloroam_users_cost_arr[hobj]
		if ( chg_cost != "" ) {
			chg_count = gloroam_users_count_arr[hobj]
			chg_duration = gloroam_users_duration_arr[hobj]
			hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 
			#print " gloroam htag=[" htag "]" "  hobj=[" hobj "]" "  chg_cost=[" chg_cost "]"
			hval = chg_cost
			hi_in(htag, 2000, hi_gloroam_users_by_cost_arr, hobj, hval)
		}

		# internet users
		hobj = centre "|" project "|" sid
		if ( internet_users_arr[hobj] == 1 ) {
			kbytes = internet_users_kbytes_arr[hobj]
			chg_duration = 0
			chg_cost = internet_users_cost_arr[hobj]
			hobj = hobj "|" kbytes "|" chg_duration "|" chg_cost 
			print " internet htag=[" htag "]" "  hobj=[" hobj "]" "  chg_cost=[" chg_cost "]"
			hval = chg_cost
			hi_in(htag, 2000, hi_internet_users_by_cost_arr, hobj, hval)
		}

		# highest premium service users
		Stag = servtype "|" centre "|" project "|" sid
		if ( sid_premserv_count_arr[Stag] != "" ) {
			chg_count = sid_premserv_count_arr[Stag]
			chg_duration = sid_premserv_duration_arr[Stag]
			chg_cost = sid_premserv_cost_arr[Stag]
			htag = distid "|" servtype
			hobj = centre "|" project "|" sid
			hobj = hobj "|" chg_count "|" chg_duration "|" chg_cost 
			hval = chg_cost
			hi_in(htag, 20, hi_premserv_users_by_cost_arr, hobj, hval)
		}
	}
}


		# screen out 0 values
	#print "hi_in() id=" id "  N_HIGH=" N_HIGH "  obj=" obj "  val=" val
		#print "        hi_arr[" id "|" i "]=" hi_arr[id "|" i]
	#print "        NEW i+1=" i+1
	# move i+1 --> i+2...
	# insert entry
function hi_in(id, N_HIGH, hi_arr, obj, val)
{
	if (val == 0)
		return
	j = N_HIGH - 1
	for ( i = j; i >= 0 ; --i ) {
		if ( hi_arr[id "|" i] == "" )
			continue
		split(hi_arr[id "|" i], hi_obj_val, "|")
		if ( val <= hi_obj_val[1] )
			break
	}
	if ( i == j )
		return
	k = i + 1
	while ( j > k ) {
		t = id "|" j
		hi_arr[t] = hi_arr[id "|" --j]
	}
	hi_arr[id "|" k] = val "|" obj
}


#----------------------------------------------------------
#


function add_totals(Xdistid, Xservtype, Xcentre, Xproject, Xsid, Xsupplier, Xrectype, Xchg_cat, chg_count, chg_duration, chg_cost)
{
	#print "add_totals:"
	#print "      Xdistid=[" Xdistid "]"
	#print "    Xservtype=[" Xservtype "]"
	#print "      Xcentre=[" Xcentre "]"
	#print "     Xproject=[" Xproject "]"
	#print "         Xsid=[" Xsid "]"
	#print "    Xsupplier=[" Xsupplier "]"
	#print "     Xrectype=[" Xrectype "]"
	#print "     Xchg_cat=[" Xchg_cat "]"

	# don't add mobile CDR to All charge category totals
	# because the total call cost comes from the CHARGE_DESC CALL rec
	# (which contains and discounts)
	# as well as CHARGE_DESC_INFO (which duplicates the costs)
	if ( Xservtype == "10" ) {
		# All total for mobile charge desc 
		if ( Xrectype == "MOBILE_CHARGE_DESC" )
			XAll_chg_cat = "All"
		else
			XAll_chg_cat = "All_" Xrectype
	}
	else {
		XAll_chg_cat = "All"
	}

	#print "     XAll_chg_cat=[" XAll_chg_cat "]"
	#print "        chg_count=[" chg_count "]"
	#print "     chg_duration=[" chg_duration "]"
	#print "         chg_cost=[" chg_cost "]"

        doAllsid = 1
        # skip accountcode sid individualextn totals when doing All_sid tots
        if ( Xservtype == 5 ) {
                split(Xsid,xsid_arr,":")
                if ( xsid_arr[2] != "All" )
                        doAllsid = 0
        }

        if ( doAllsid == 1 ) {
                # total for ALL_servtype/All_centre/All_project/All_sid
                add_tots(Xdistid, "All", "All", "All", "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)

                # total for servtype/All_centre/All_project/All_sid
                add_tots(Xdistid, Xservtype, "All", "All", "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)
        }

	# rjs
	## grand totals and centre totals (from detail data loading only)
	#if ( substr(Xdistid,1,5) == "TOTAL" ) {
                if ( doAllsid == 1 ) {
                        # total for All_servtype/centre/All_project/All_sid
                        add_tots(Xdistid, "All", Xcentre, "All", "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)

                        # total for All_servtype/centre/project/All_sid
                        add_tots(Xdistid, "All", Xcentre, Xproject, "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)

                        # total for servtype/centre/All_project/All_sid
                        add_tots(Xdistid, Xservtype, Xcentre, "All", "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)

                        # total for servtype/centre/project/All_sid
                        add_tots(Xdistid, Xservtype, Xcentre, Xproject, "All", Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)
                }

		# total for servtype/centre/project/sid
		add_tots(Xdistid, Xservtype, Xcentre, Xproject, Xsid, Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)

	# rjs
	if ( substr(Xdistid,1,5) == "TOTAL" ) {
		nstag = "TOTAL" "|" Xservtype "|" Xcentre "|" Xproject
		if ( nsids_arr[nstag "|" Xsid] == "" ) {
			if ( Xservtype == 1 ) {
				if ( chg_count > 0 ) {
					nsids_arr[nstag "|" Xsid] = "1"
					nsids_arr[nstag] += 1
					nsids_arr["TOTAL" "|" Xservtype] += 1
				}
			}
			else {
				nsids_arr[nstag "|" Xsid] = "1"
				nsids_arr[nstag] += 1
				nsids_arr["TOTAL" "|" Xservtype] += 1
			}
		}
	}
}



function add_tots(Xdistid, Xservtype, Xcentre, Xproject, Xsid, Xsupplier, Xchg_cat, XAll_chg_cat, chg_count, chg_duration, chg_cost)
{
	# supplier / charge category total
	Xtag = Xdistid "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" Xsupplier "|" Xchg_cat
	print "add_tots - Xtag=[" Xtag "] addcost = " chg_cost
	totalcount_arr[Xtag] += chg_count
	totalduration_arr[Xtag] += chg_duration
	totalcost_arr[Xtag] += chg_cost

	# supplier / All charge category total
	Xtag = Xdistid "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" Xsupplier "|" XAll_chg_cat
	#print "add_tots - Xtag=[" Xtag "] addcost = " chg_cost
	totalcount_arr[Xtag] += chg_count
	totalduration_arr[Xtag] += chg_duration
	totalcost_arr[Xtag] += chg_cost

	# All supplier / charge category total
	Xtag = Xdistid "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" "All" "|" Xchg_cat
	#print "add_tots - Xtag=[" Xtag "] addcost = " chg_cost
	totalcount_arr[Xtag] += chg_count
	totalduration_arr[Xtag] += chg_duration
	totalcost_arr[Xtag] += chg_cost

	# All supplier / All charge category total
	Xtag = Xdistid "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" "All" "|" XAll_chg_cat
	#print "add_tots - Xtag=[" Xtag "] addcost = " chg_cost
	totalcount_arr[Xtag] += chg_count
	totalduration_arr[Xtag] += chg_duration
	totalcost_arr[Xtag] += chg_cost
}


function print_totals(Xservtype, Xcentre, Xproject, Xsid)
{
	# total for centre/project/servtype/sid
	Xtag = "TOTAL" "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" "All" "|" "All"

	print "print_totals() - >>>> totalcost_arr[" Xtag "] = " totalcost_arr[Xtag]
}


#---------------------

function add_distid_totals()
{
	print "add_distid_totals HIERIDx = [" HIERIDx "]"

	split(HIERIDx, HIERIDx_arr, "|")
	Xservtype = HIERIDx_arr[1]
	Xcentre = HIERIDx_arr[2]
	Xproject = HIERIDx_arr[3]
	Xsid = HIERIDx_arr[4]
	Xsupplier = HIERIDx_arr[5]
	Xrectype = HIERIDx_arr[6]
	Xchg_cat = HIERIDx_arr[7]

	Xtag = "TOTAL" "|" Xservtype "|" Xcentre "|" Xproject "|" Xsid "|" Xsupplier "|" Xchg_cat

	chg_count = totalcount_arr[Xtag]
	chg_duration = totalduration_arr[Xtag]
	chg_cost = totalcost_arr[Xtag]

	#print "add_distid_totals totalcost_arr[" Xtag "] = [" totalcost_arr[Xtag] "]"
	# rjs9 centre|project has multiple egrids
	#Xegrid = CENTREPROJECT_to_EGRID_arr[Xcentre "|" Xproject]
	Xegrid = CENTREPROJECTSID_to_EGRID_arr[Xcentre "|" Xproject "|" Xsid]
	#print "     Xegrid = [" Xegrid "]"

	if ( retroBDL != "1" ) {
	    if ( Xservtype == "10" ) {
		# do totals for virtual distids
		Stag = Xegrid "|" Xservtype "|" Xsid
		Vdistid = personal_egrid_servtype_SID_to_distid_arr[Stag]

		#print "add_distid_totals test Vdistid - personal_egrid_servtype_SID_to_distid_arr[" Stag "] = [" personal_egrid_servtype_SID_to_distid_arr[Stag] "]"
		if ( Vdistid != "" ) {
			#print "add_distid_totals PERSONAL Stag=[" Stag "]"
			Xdistid = "TOTAL_" Vdistid
			add_totals(Xdistid, Xservtype, Xcentre, Xproject, Xsid, Xsupplier, Xrectype, Xchg_cat, chg_count, chg_duration, chg_cost)
		}
	    }
	}

	#print "add_distid_totals Xservtype = [" Xservtype "]"

	# do totals for each configured distid that has this egrid
	distidlist = egrid_distidlist_arr[Xegrid]
	#print "add_distid_totals distidlist=[" distidlist "]"
	split(distidlist, distid_arr, "|")
	for ( i in distid_arr ) {
		Xdistid = distid_arr[i]
		add_totals(Xdistid, Xservtype, Xcentre, Xproject, Xsid, Xsupplier, Xrectype, Xchg_cat, chg_count, chg_duration, chg_cost)
		# add nsids for distid
		if ( Xservtype == 1 || Xservtype == 2 || Xservtype == 10 ) {
		    nsdistidtag = Xdistid "|" Xservtype "|" Xcentre "|" Xproject

		    if ( nsids_arr[nsdistidtag "|" "DONE" ] != "1" ) {
			nsids_arr[nsdistidtag "|" "DONE" ] = "1"

			# get project sid count for servicetype
			nstag = "TOTAL" "|" Xservtype "|" Xcentre "|" Xproject
			nsids = nsids_arr[nstag]
			#print "nsids: get project nsids_arr[" nstag "]=[" nsids_arr[nstag] "]"

			# set distid/centre sid count for servicetype 
			nstag = Xdistid "|" Xservtype "|" Xcentre "|" "All"
			nsids_arr[nstag] += nsids
			#print "nsids: set centre nsids_arr[" nstag "]=[" nsids_arr[nstag] "]"

			# set distid sids for servicetype
			nstag = Xdistid "|" Xservtype "|" "All" "|" "All"
			nsids_arr[nstag] += nsids
			#print "nsids: set distid nsids_arr[" nstag "]=[" nsids_arr[nstag] "]"
		    }
		}
	}
}


#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------



function handle_DISTID_datafile()
{
	print "handle_DISTID_datafile() DISTID=" DISTID "  HIERIDx=" HIERIDx

	DISTID_fname = sprintf("topdat/%s/%s/data/distid/distid_%s.csv", monthdir, DISTID, DISTID)

	if ( REC_TYPE == "MOBILE_CHARGE_DESC" ) {
		if ( CHG_CAT != "Mobile Other" && CHG_CAT != "Mobile Misc" ) {
			print "    CHG_CAT skipping rec_type=[" REC_TYPE "]" "  CHG_CAT=[" CHG_CAT "]"
			return
		}
	}

	if ( REC_TYPE == "MOBILE_CHARGE_DESC_INFO" ) {
		if ( CHG_CAT != "Mobile Equipment" && CHG_CAT != "Mobile Adjustment" && CHG_CAT != "Mobile Recurring" ) {
			print "    CHG_CAT skipping rec_type=[" REC_TYPE "]" "  CHG_CAT=[" CHG_CAT "]"
			return
		}
	}

	if ( done_DISTID_fname_arr[DISTID_fname] == "" ) {
		printf(">>>          DISTID_fname = %s\n", DISTID_fname)
		if ( (getline x < DISTID_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/distid", monthdir, DISTID)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(DISTID_fname)
			spit_header_to_DISTIDfile()
		}
		else {
			printf("WARNING %d: DISTID_fname = %s exists.\n", NR, DISTID_fname)
		}
		done_DISTID_fname_arr[DISTID_fname] = "1"
	}


	# ALL DISTID_centres total for all projects and servicetypes and sids
	spit_allsid_totals_to_DISTIDfile("All", "All", "All")

	# centre total for all projects and servicetypes and sids
	spit_allsid_totals_to_DISTIDfile("All", CENTRE, "All")

	# centre - project total for all servicetypes and sids
	spit_allsid_totals_to_DISTIDfile("All", CENTRE, PROJECT)

	# servicetype total for all centres and projects and sids
	spit_allsid_totals_to_DISTIDfile(SERVTYPE, "All", "All")

	# servicetype total for all projects and sids in each centre
	spit_allsid_totals_to_DISTIDfile(SERVTYPE, CENTRE, "All")

	# centre - project - servicetype total for all sids
	spit_allsid_totals_to_DISTIDfile(SERVTYPE, CENTRE, PROJECT)

	close(DISTID_fname)
}


function handle_SERVTYPE_datafile()
{
	print "handle_SERVTYPE_datafile() SERVTYPE= " SERVTYPE "  DISTID=" DISTID "  HIERIDx=" HIERIDx

	# rjs9
	tmpSERVTYPE = SERVTYPE
	#if ( SERVTYPE >= 100000 )	# tbs rest
	#	tmpSERVTYPE = 20

	SERVTYPE_fname = sprintf("topdat/%s/%s/data/service%s/service_%s_%s_%s.csv", monthdir, DISTID, tmpSERVTYPE, DISTID, CENTRE, tmpSERVTYPE)

	if ( done_SERVTYPE_fname_header_arr[SERVTYPE_fname] == "" ) {
		printf(">>>          SERVTYPE_fname = %s\n", SERVTYPE_fname)
		if ( (getline x < SERVTYPE_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/service%s", monthdir, DISTID, SERVTYPE)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(SERVTYPE_fname)
			spit_header_to_SERVTYPEfile()
		}
		else {
			printf("WARNING %d: SERVTYPE_fname = %s exists.\n", NR, SERVTYPE_fname)
		}
		done_SERVTYPE_fname_header_arr[SERVTYPE_fname] = "1"
	}

	# sid total
	if ( done_SERVTYPE_fname_SID_totals_arr[SERVTYPE_fname "|" PROJECT "|" SID] == "" ) {

                if ( SERVTYPE == 5 ) {  # account code summary extn totals
                        print "ACCCDEBUG: SID=[" SID "]"
                        for ( acccode_extn in acccode_extn_arr ) {
                                split(acccode_extn, accex_arr, "|")
                                if ( SID == accex_arr[1] ) {
                                        print "ACCCDEBUG: acccode_extn=[" acccode_extn "]"
                                        t21_extn = accex_arr[2]
                                        a_eggrid = dirextn_to_eggrid_arr[t21_extn]
					get_t21info(1,a_eggrid,t21_extn)
					spit_SIDtotals_to_SERVTYPEfile(SERVTYPE, CENTRE, PROJECT, SID ":" t21_extn, SUPPLIER)
                                }
                        }
                        t21_extn = "All"
                        t21name = "All Extension"
                        t21surname = ""
                        t21firstname = ""
                        t21location = ""
                        t21site = ""
                        spit_SIDtotals_to_SERVTYPEfile(SERVTYPE, CENTRE, PROJECT, SID ":" t21_extn, SUPPLIER)
                }
                else {
                        spit_SIDtotals_to_SERVTYPEfile(SERVTYPE, CENTRE, PROJECT, SID, SUPPLIER)
                }

		# all supplie total
		#spit_SIDtotals_to_SERVTYPEfile(SERVTYPE, CENTRE, PROJECT, SID, "All")

		done_SERVTYPE_fname_SID_totals_arr[SERVTYPE_fname "|" PROJECT "|" SID] = "1"
	}

	close(SERVTYPE_fname)
}

################################################
################################################

#-------
function spit_header_to_DISTIDfile()
{
	#print "spit_header_to_DISTIDfile() - " DISTID_fname
	csvstr = sprintf("%s,%s,%s,%s,%s,%s,divisiondesc,division,centredesc,centre,projectdesc,project,projectfilter,ccpdesc,servicetypedesc,servicetypeID,supplier,chargecategory,totcount:Int,totduration:Int,totcost:Float\n", "V2 Cost Centre Summary", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID)

	#printf("%s", csvstr)
	printf("%s", csvstr) >>DISTID_fname
}


#-------

function spit_allsid_totals_to_DISTIDfile(Xservtype, Xcentre, Xproject)
{
	##XDISTIDtag = DISTID_fname "|" Xservtype "|" Xcentre "|" Xproject
	##if ( done_DISTID_fname_totals_arr[XDISTIDtag] == "" ) {
		#if ( spit_PERSONAL ) {
		#    #print "spit PERSONAL for XDISTIDtag=" XDISTIDtag
		#    spit_cat_totals_to_DISTIDfile(Xservtype,Xcentre,Xproject,"PERSONAL_" DISTID)
		#}
		#else {
		    spit_cat_totals_to_DISTIDfile(Xservtype,Xcentre,Xproject,"All")
		#}
		##done_DISTID_fname_totals_arr[XDISTIDtag] = "1"
	##}
}

#-------

function spit_cat_totals_to_DISTIDfile(Xservtype, Xcentre, Xproject, Xsid)
{
	# All chg_cat total for each supplier
	spit_totals_to_DISTIDfile(DISTID,Xservtype,Xcentre,Xproject,Xsid,SUPPLIER,"All")

	# All chg_cat total for All suppliers
	spit_totals_to_DISTIDfile(DISTID,Xservtype,Xcentre,Xproject,Xsid,"All","All")

	## NO - supplier/charge category totals for All servtype tots
	#if ( Xservtype == "All" ) {
	#	return
	#}

	#  servtype/centre/project/sid totals for each supplier and charge cat
	spit_totals_to_DISTIDfile(DISTID,Xservtype,Xcentre,Xproject,Xsid,SUPPLIER,CHG_CAT)
}

#-------

function spit_totals_to_DISTIDfile(distid,servtype,centre,project,sid,supplier,chg_cat)
{
	#print "spit_totals_to_DISTIDfile() - " DISTID_fname

	Ztag = servtype "|" centre "|" project "|" sid "|" supplier "|" chg_cat

	if ( distid_to_wbd_type_arr[distid] == "PERSONAL" ) { # persernal list
		Xtag = "TOTAL_" distid "|" Ztag
	}
	else {
		# rjs
		#if ( centre != "All" ) {
		#	Xtag = "TOTAL" "|" Ztag
		#}
		#else {
			Xtag = distid "|" Ztag
		#}
	}

	XDISTIDtag = DISTID_fname "|" Xtag
	if ( done_DISTID_fname_totals_arr[XDISTIDtag] == "" ) {

		totalcount = totalcount_arr[Xtag]
		totalduration = totalduration_arr[Xtag]
		totalcost = totalcost_arr[Xtag]

		#print "  spit_totals_to_DISTIDfile Xtag=" Xtag "  totalcost=" totalcost

		set_project_displayinfo(centre, project)

		servtypedesc = SERVTYPE_to_SERVTYPEdesc_arr[servtype]

		if ( supplier == "All" && chg_cat == "All" ) {
		    if ( servtype == 1 || servtype == 2 || servtype == 10 ) {
			if ( centre != "All" && project != "All" )
				nstag = "TOTAL" "|" servtype "|" centre "|" project
			else
				nstag = distid "|" servtype "|" centre "|" project
			nsids = nsids_arr[nstag]
			#print "nsids: got nsids_arr[" nstag "]=[" nsids_arr[nstag] "]"
			if ( nsids != "" ) {
				if ( servtype == 1 )
					linecountdesc = "Active: " nsids
				if ( servtype == 2 )
					linecountdesc = "Lines: " nsids
				if ( servtype == 10 )
					linecountdesc = "Mobiles: " nsids
				#sub("EXTNCNT", " - " linecountdesc " ", servtypedesc)
				servtypedesc = servtypedesc " " linecountdesc
			}
		    }
		}

		csvstr = sprintf(",,,,,,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%d,%d,%0.2f\n", divisiondesc, division, display_centredesc, centre, display_projectdesc, disp_project, projectfilter, ccpdesc, servtypedesc, servtype, supplier, chg_cat, totalcount, totalduration, mround2(totalcost))

		#printf("%s", csvstr)
		printf("%s", csvstr) >>DISTID_fname

		done_DISTID_fname_totals_arr[XDISTIDtag] = "1"
	}

}


#-------
function spit_header_to_SERVTYPEfile()
{
	#print "spit_header_to_SERVTYPEfile() - " SERVTYPE_fname

	if ( SERVTYPE == 1 ) {
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)
		csvstr = csvstr sprintf("extn,site,location,name,projectdesc,project,ccpdesc,")
		csvstr = csvstr sprintf("Incoming Calls Ext:Int,Incoming Calls Int:Int,Outgoing Calls Free:Int,Outgoing Calls Local:Int,Outgoing Calls STD:Int,Outgoing Calls Mobile:Int,Outgoing Calls IDD:Int,Outgoing Calls Int:Int,Outgoing Call Costs Local:Float,Outgoing Call Costs STD:Float,Outgoing Call Costs Mobile:Float,Outgoing Call Costs IDD:Float,Total Cost:Float\n")
	}

	if ( SERVTYPE == 2 )
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,extn,site,location,name,projectdesc,project,ccpdesc,Total Cost:Float\n", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)

	if ( SERVTYPE == 3 )
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,extn,site,location,name,projectdesc,project,ccpdesc,Total Cost:Float\n", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)

	if ( SERVTYPE == 4 )
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,extn,site,location,name,projectdesc,project,ccpdesc,Total Cost:Float\n", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)

        if ( SERVTYPE == 5 ) {
                csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)
                csvstr = csvstr sprintf("accountcode,accountcode_description,extn,name,projectdesc,project,ccpdesc,")

                csvstr = csvstr sprintf("Incoming Calls Ext:Int,Incoming Calls Int:Int,Outgoing Calls Free:Int,Outgoing Calls Local:Int,Outgoing Calls STD:Int,Outgoing Calls Mobile:Int,Outgoing Calls IDD:Int,Outgoing Calls Int:Int,Outgoing Call Costs Local:Float,Outgoing Call Costs STD:Float,Outgoing Call Costs Mobile:Float,Outgoing Call Costs IDD:Float,Total Cost:Float\n")
        }

	if ( SERVTYPE == 10 ) {
		sidcount = nsids_arr["TOTAL|10"]
		overallcost = totalcost_arr["TOTAL|10|All|All|All|All|All"]
		avg_cost = overallcost
		if ( mobdummy_cost > 0 ) {
			sidcount = sidcount - 1
			avg_cost = avg_cost - mobdummy_cost
			print "AVGDUMMY 1: mobdummy_cost=[" mobdummy_cost "]" "  avg_cost=[" avg_cost "]" "  sidcount=[" sidcount "]"
		}
		if ( sidcount )
			overallavgcost = sprintf("%0.2f", mround2(avg_cost / sidcount))
		else
			overallavgcost = 0
		#csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "V2 Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "V2 Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE "~" overallavgcost)
		csvstr = csvstr sprintf("mobile,site,location,name,projectdesc,project,ccpdesc,supplier,")
		csvstr = csvstr sprintf("Onnet Count:Int,Onnet Duration:Int,Onnet Cost:Float,National Count:Int,National Duration:Int,National Cost:Float,International Count:Int,International Duration:Int,International Cost:Float,Commerce Count:Int,Commerce Duration:Int,Commerce Cost:Float,Messaging Count:Int,Messaging Duration:Int,Messaging Cost:Float,Misc Count:Int,Misc Duration:Int,Misc Cost:Float,")
		csvstr = csvstr sprintf("CDR Total Count:Int,CDR Total Duration:Int,CDR Total Cost:Float,")
		csvstr = csvstr sprintf("Equipment Cost:Float,Adjustment Cost:Float,Other Cost:Float,Recurring Cost:Float,Call Total Cost:Float,Total Cost:Float\n")
	}

	# rjs9
	# tbs rest
	if ( SERVTYPE >= 100000 )
		csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,sid,site,location,name,projectdesc,project,ccpdesc,Total Cost:Float\n", "Service Detail", exbillperiod, "SDATE", "EDATE", DISTIDdesc, DISTID, CENTREdesc, CENTRE, SERVTYPEdesc, SERVTYPE)


	#printf("%s", csvstr)
	printf("%s", csvstr) >>SERVTYPE_fname
}


function spit_SIDtotals_to_SERVTYPEfile(servtype,centre,project,sid,supplier)
{
	print "spit_SIDtotals_to_SERVTYPEfile() - " SERVTYPE_fname

	Wtag = "TOTAL" "|" servtype "|" centre "|" project "|" sid "|" supplier
	totalcost = totalcost_arr[Wtag "|All"]

	#print "  Wtag=" Wtag "  totalcost=" totalcost

	set_project_displayinfo(centre, project)

	if ( SERVTYPE == 1 ) {
	    P_cat = fixed_callcat_to_chg_cat["P"]
		#print "fixed P_cat=[" P_cat "]"
	    A_cat = fixed_callcat_to_chg_cat["A"]
		#print "fixed A_cat=[" A_cat "]"
	    N_cat = fixed_callcat_to_chg_cat["N"]
		#print "fixed N_cat=[" N_cat "]"
	    F_cat = fixed_callcat_to_chg_cat["F"]
		#print "fixed F_cat=[" F_cat "]"
	    L_cat = fixed_callcat_to_chg_cat["L"]
		#print "fixed L_cat=[" L_cat "]"
	    S_cat = fixed_callcat_to_chg_cat["S"]
		#print "fixed S_cat=[" S_cat "]"
	    E_cat = fixed_callcat_to_chg_cat["E"]
		#print "fixed E_cat=[" E_cat "]"
	    M_cat = fixed_callcat_to_chg_cat["M"]
		#print "fixed M_cat=[" M_cat "]"
	    I_cat = fixed_callcat_to_chg_cat["I"]
		#print "fixed I_cat=[" I_cat "]"
	    J_cat = fixed_callcat_to_chg_cat["J"]
		#print "fixed J_cat=[" J_cat "]"
	    O_cat = fixed_callcat_to_chg_cat["O"]
		#print "fixed O_cat=[" O_cat "]"

	    P_count = totalcount_arr[Wtag "|" P_cat]
	    A_count = totalcount_arr[Wtag "|" A_cat]
	    N_count = totalcount_arr[Wtag "|" N_cat]
	    F_count = totalcount_arr[Wtag "|" F_cat]
	    L_count = totalcount_arr[Wtag "|" L_cat]
	    S_count = totalcount_arr[Wtag "|" S_cat]
	    E_count = totalcount_arr[Wtag "|" E_cat]
	    M_count = totalcount_arr[Wtag "|" M_cat]
	    I_count = totalcount_arr[Wtag "|" I_cat]
	    J_count = totalcount_arr[Wtag "|" J_cat]
	    O_count = totalcount_arr[Wtag "|" O_cat]
	    L_cost = totalcost_arr[Wtag "|" L_cat]
	    S_cost = totalcost_arr[Wtag "|" S_cat]
	    E_cost = totalcost_arr[Wtag "|" E_cat]
	    M_cost = totalcost_arr[Wtag "|" M_cat]
	    I_cost = totalcost_arr[Wtag "|" I_cat]

	    csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f\n", sid, t21site, t21location, t21name, PROJECTdesc3, disp_project, ccpdesc, P_count, A_count + N_count, F_count, L_count, S_count + E_count, M_count, I_count, J_count + O_count, mround2(L_cost), mround2(S_cost + E_cost), mround2(M_cost), mround2(I_cost), mround2(totalcost))

	}

	if ( SERVTYPE == 2 )
		csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%0.2f\n", sid, t21site, t21location, t21name, PROJECTdesc3, disp_project, ccpdesc, mround2(totalcost))

	if ( SERVTYPE == 3 )
		csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%0.2f\n", sid, t21site, t21location, t21name, PROJECTdesc3, disp_project, ccpdesc, mround2(totalcost))

	if ( SERVTYPE == 4 )
		csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%0.2f\n", sid, t21site, t21location, t21name, PROJECTdesc3, disp_project, ccpdesc, mround2(totalcost))


        if ( SERVTYPE == 5 ) {  # account code summary
            P_cat = fixed_callcat_to_chg_cat["P"]
            A_cat = fixed_callcat_to_chg_cat["A"]
            N_cat = fixed_callcat_to_chg_cat["N"]
            F_cat = fixed_callcat_to_chg_cat["F"]
            L_cat = fixed_callcat_to_chg_cat["L"]
            S_cat = fixed_callcat_to_chg_cat["S"]
            E_cat = fixed_callcat_to_chg_cat["E"]
            M_cat = fixed_callcat_to_chg_cat["M"]
            I_cat = fixed_callcat_to_chg_cat["I"]
            J_cat = fixed_callcat_to_chg_cat["J"]
            O_cat = fixed_callcat_to_chg_cat["O"]

            P_count = totalcount_arr[Wtag "|" P_cat]
            A_count = totalcount_arr[Wtag "|" A_cat]
            N_count = totalcount_arr[Wtag "|" N_cat]
            F_count = totalcount_arr[Wtag "|" F_cat]
            L_count = totalcount_arr[Wtag "|" L_cat]
            S_count = totalcount_arr[Wtag "|" S_cat]
            E_count = totalcount_arr[Wtag "|" E_cat]
            M_count = totalcount_arr[Wtag "|" M_cat]
            I_count = totalcount_arr[Wtag "|" I_cat]
            J_count = totalcount_arr[Wtag "|" J_cat]
            O_count = totalcount_arr[Wtag "|" O_cat]
            L_cost = totalcost_arr[Wtag "|" L_cat]
            S_cost = totalcost_arr[Wtag "|" S_cat]
            E_cost = totalcost_arr[Wtag "|" E_cat]
            M_cost = totalcost_arr[Wtag "|" M_cat]
            I_cost = totalcost_arr[Wtag "|" I_cat]

            csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f\n", t21_acccode, acccode_to_desc_arr[t21_acccode], t21_extn, t21name, PROJECTdesc3, disp_project, ccpdesc, P_count, A_count + N_count, F_count, L_count, S_count + E_count, M_count, I_count, J_count + O_count, mround2(L_cost), mround2(S_cost + E_cost), mround2(M_cost), mround2(I_cost), mround2(totalcost))

        }

	if ( SERVTYPE == 10 ) {	#mobile service10/call breakdown/charge summary
		ccat = "Mobile Onnet"
		mob_onnet_count = totalcount_arr[Wtag "|" ccat]
		mob_onnet_duration = totalduration_arr[Wtag "|" ccat]
		mob_onnet_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile National"
		mob_national_count = totalcount_arr[Wtag "|" ccat]
		mob_national_duration = totalduration_arr[Wtag "|" ccat]
		mob_national_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile International"
		mob_international_count = totalcount_arr[Wtag "|" ccat]
		mob_international_duration = totalduration_arr[Wtag "|" ccat]
		mob_international_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Commerce"
		mob_commerce_count = totalcount_arr[Wtag "|" ccat]
		mob_commerce_duration = totalduration_arr[Wtag "|" ccat]
		mob_commerce_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Messaging"
		mob_messaging_count = totalcount_arr[Wtag "|" ccat]
		mob_messaging_duration = totalduration_arr[Wtag "|" ccat]
		mob_messaging_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Misc"
		mob_misc_count = totalcount_arr[Wtag "|" ccat]
		mob_misc_duration = totalduration_arr[Wtag "|" ccat]
		mob_misc_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "All_MOBILE_CDR"
		mob_cdr_totcount = totalcount_arr[Wtag "|" ccat]
		mob_cdr_totduration = totalduration_arr[Wtag "|" ccat]
		mob_cdr_totcost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		#---
		#ccat = "Mobile Rent"
		#mob_rent_cost = totalcost_arr[Wtag "|" ccat]
		#
		# CALL charge (incl. discount)
		#ccat = "Mobile Call"
		#mob_call_cost = totalcost_arr[Wtag "|" ccat]
		#
		#ccat = "Mobile Call Discount"
		#mob_call_discount_total_cost = totalcost_arr[Wtag "|" ccat]
		#ccat = "Mobile Recurring Discount"
		#mob_recurring_discount_total_cost=totalcost_arr[Wtag "|" ccat]
		#---

		ccat = "Mobile Equipment"
		mob_equipment_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Adjustment"
		mob_adjustment_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Other"
		mob_other_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		ccat = "Mobile Recurring"
		mob_recurring_cost = totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		# CALL charge (NOT incl. discount)
		ccat = "Mobile Call Total"
		mob_call_total_cost = totalcost_arr[Wtag "|" ccat]
		ccat = "Mobile Internet"
		mob_call_total_cost += totalcost_arr[Wtag "|" ccat]
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		#ccat = "All"
		#print "MOBDBG: totalcost_arr[" Wtag "|" ccat "] = [" totalcost_arr[Wtag "|" ccat] "]"

		csvstr = sprintf(",,,,,,,,,,")
		csvstr = csvstr sprintf("%s,%s,%s,%s,%s,%s,%s,%s,", sid, t21site, t21location, mobname, PROJECTdesc3, disp_project, ccpdesc, supplier)
		csvstr = csvstr sprintf("%d,%d,%0.2f,%d,%d,%0.2f,%d,%d,%0.2f,%d,%d,%0.2f,%d,%d,%0.2f,%d,%d,%0.2f,", mob_onnet_count, mob_onnet_duration, mround2(mob_onnet_cost), mob_national_count, mob_national_duration, mround2(mob_national_cost), mob_international_count, mob_international_duration, mround2(mob_international_cost), mob_commerce_count, mob_commerce_duration, mround2(mob_commerce_cost), mob_messaging_count, mob_messaging_duration, mround2(mob_messaging_cost), mob_misc_count, mob_misc_duration, mround2(mob_misc_cost))
		csvstr = csvstr sprintf("%d,%d,%0.2f,", mob_cdr_totcount, mob_cdr_totduration, mround2(mob_cdr_totcost))
		csvstr = csvstr sprintf("%0.2f,%0.2f,%0.2f,%0.2f,%0.2f,%0.2f\n", mround2(mob_equipment_cost), mround2(mob_adjustment_cost), mround2(mob_other_cost), mround2(mob_recurring_cost), mround2(mob_call_total_cost), mround2(totalcost))
	}

	# rjs9
	# tbs rest
	if ( SERVTYPE >= 100000 )
		csvstr = sprintf(",,,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%0.2f\n", sid, t21site, t21location, t21name, PROJECTdesc3, disp_project, ccpdesc, mround2(totalcost))

	#printf("%s", csvstr)
	printf("%s", csvstr) >>SERVTYPE_fname
}

#----------------------------------------------------------
#----------------------------------------------------------


function create_hi_sid_csv(hirepid, hirepdesc, N_HIGH, hi_in_arr, DISTID,fdistid, SERVTYPE, countcoldesc)
{
	HISID_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, hirepid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_HISID_fname_header_arr[HISID_fname] == "" ) {
		printf(">>>          HISID_fname = %s\n", HISID_fname)
		if ( (getline x < HISID_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(HISID_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,Name,Campus,Location,Description,Costcentre,%s,Cost:Float\n", hirepdesc, exbillperiod, "SDATE", "EDATE", hirepid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE, itemdesc, countcoldesc)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>HISID_fname

		}
		else {
			printf("WARNING %d: HISID_fname = %s exists.\n", NR, HISID_fname)
		}
		done_HISID_fname_header_arr[HISID_fname] = "1"
	}

	# spit records
	for ( i = 0; i < N_HIGH; ++i ) {
		htag = DISTID "|" SERVTYPE
		hitag = htag "|" i
		val_obj = hi_in_arr[hitag]

		if ( val_obj == "" )
			continue

		split(val_obj, a_arr, "|")
		hi_val = a_arr[1]
		hi_centre = a_arr[2]
		hi_project = a_arr[3]
		hi_sid = a_arr[4]
		hi_count = a_arr[5]
		hi_duration = a_arr[6]
		hi_cost = a_arr[7]

		# rjs9 centre|project has multiple egrids
		#t21_EGRID = CENTREPROJECT_to_EGRID_arr[hi_centre "|" hi_project]
		t21_EGRID = CENTREPROJECTSID_to_EGRID_arr[hi_centre "|" hi_project "|" hi_sid]

		if ( SERVTYPE == "10" ) {
			get_mobileinfo(2,SERVTYPE,hi_sid)
		}
		else {
			t21_extn = hi_sid
			get_t21info(SERVTYPE,t21_EGRID,t21_extn)
		}

		set_project_displayinfo(hi_centre, hi_project)

		csvstr = sprintf(",,,,,,,,,%s,%s,%s,%s,%s,%s,%d,%0.2f\n", hi_sid, t21name, t21site, t21location, ccp, ccpdesc, hi_count, mround2(hi_cost))
		
		#printf("%s", csvstr)
		printf("%s", csvstr) >>HISID_fname
	}
	close(HISID_fname)
}



function create_hi_call_csv(hirepid, hirepdesc, N_HIGH, hi_in_arr, DISTID,fdistid, SERVTYPE)
{
	HICALL_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, hirepid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_HICALL_fname_header_arr[HICALL_fname] == "" ) {
		printf(">>>          HICALL_fname = %s\n", HICALL_fname)
		if ( (getline x < HICALL_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(HICALL_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,Name,Campus,Location,Description,Costcentre,Dialled/CLI,Duration,Cost:Float\n", hirepdesc, exbillperiod, "SDATE", "EDATE", hirepid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE, itemdesc)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>HICALL_fname

		}
		else {
			printf("WARNING %d: HICALL_fname = %s exists.\n", NR, HICALL_fname)
		}
		done_HICALL_fname_header_arr[HICALL_fname] = "1"
	}

	# fixed
	#hi_call_by_cost_arr[mng1174|1|0]  = 38.72|23611|00000|1857|101|44018|out|05-10-2007|14:32:20|0414270400|M|Mobile Phone|123|38.72
	#hi_call_by_cost_arr[mng1174|10|0]  = 184.87|22107|00000|0420-946184|11|CDR|Mobile Commerce|MO|30-09-2007|17:22:22||vfint 18487Kb roam||123|187.87

	# mobile
	#hi_call_by_duration_arr[mng1174|1|11]  = 184184|20111|00000|5540|101|5257|out|22-10-2007|16:27:32|5257|J|Originating internal|321|0.0
	#hi_call_by_duration_arr[mng1174|10|0]  = 100219|23321|00000|0419-231473|169|CDR|Mobile Misc|PACKET DATA SESSIONS|08-09-2007|15:11:00|GIRRAWEEN|16 KB|BLACKBERRY.N|321|0.00

	# spit records
	for ( i = 0; i < N_HIGH; ++i ) {
		htag = DISTID "|" SERVTYPE
		hitag = htag "|" i
		val_obj = hi_in_arr[hitag]

		if ( val_obj == "" )
			continue

		split(val_obj, a_arr, "|")
		f = 0
		hi_val = a_arr[++f]
		hi_centre = a_arr[++f]
		hi_project = a_arr[++f]
		hi_sid = a_arr[++f]
		if ( SERVTYPE == "10" ) {
			mob_recno = a_arr[++f]
			mob_rectype = a_arr[++f]
			mob_cat = a_arr[++f]
			mob_recclass = a_arr[++f]
			date = a_arr[++f]
			ctimestr = a_arr[++f]
			mob_origin = a_arr[++f]
			expdialledno = a_arr[++f]
			mob_destination = a_arr[++f]
			duration = a_arr[++f]
			callcost = a_arr[++f]

			#chg_cat = mob_cat
			chg_duration = duration
			chg_cost = callcost
		}
		else {
			siteid = a_arr[++f]
			otherno = a_arr[++f]
			direction = a_arr[++f]
			date = a_arr[++f]
			endtimestr = a_arr[++f]
			expdialledno = a_arr[++f]
			callcat = a_arr[++f]
			calldesc = a_arr[++f]
			duration = a_arr[++f]
			callcost = a_arr[++f]

			#chg_cat = fixed_callcat_to_chg_cat[callcat]
			chg_duration = duration
			chg_cost = callcost
		}

		# rjs9 centre|project has multiple egrids
		#t21_EGRID = CENTREPROJECT_to_EGRID_arr[hi_centre "|" hi_project]
		t21_EGRID = CENTREPROJECTSID_to_EGRID_arr[hi_centre "|" hi_project "|" hi_sid]

		if ( SERVTYPE == "10" ) {
			get_mobileinfo(2,SERVTYPE,hi_sid)
		}
		else {
			t21_extn = hi_sid
			get_t21info(SERVTYPE,t21_EGRID,t21_extn)
		}

		set_project_displayinfo(hi_centre, hi_project)

		csvstr = sprintf(",,,,,,,,,%s,%s,%s,%s,%s,%s,%s,%s,%0.2f\n", hi_sid, t21name, t21site, t21location, ccp, ccpdesc, expdialledno, chg_duration, mround2(chg_cost))
		
		#printf("%s", csvstr)
		printf("%s", csvstr) >>HICALL_fname
	}
	close(HICALL_fname)
}



function create_hi_freqdial_csv(hirepid, hirepdesc, N_HIGH, hi_in_arr, DISTID,fdistid, SERVTYPE)
{
	HIFREQ_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, hirepid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_HIFREQ_fname_header_arr[HIFREQ_fname] == "" ) {
		printf(">>>          HIFREQ_fname = %s\n", HIFREQ_fname)
		if ( (getline x < HIFREQ_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(HIFREQ_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,Dialled Number,Onnet,Total Number of Calls,Total Duration,Total Cost:Float,Most Frequent %s,Costcentre for %s,Count for %s\n", hirepdesc, exbillperiod, "SDATE", "EDATE", hirepid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE, itemdesc, itemdesc, itemdesc)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>HIFREQ_fname

		}
		else {
			printf("WARNING %d: HIFREQ_fname = %s exists.\n", NR, HIFREQ_fname)
		}
		done_HIFREQ_fname_header_arr[HIFREQ_fname] = "1"
	}

	# fixed
	#hi_dist_freqdial_arr[mng1174|1|0]  = 4061|1800031037|947325|00000|9420|738
	# mobile
	#hi_dist_freqdial_arr[mng1174|10|0]  = 39006|Internet|20031|00000|0413-474744|2768

	htag = DISTID "|" SERVTYPE

	# spit records
	for ( i = 0; i < N_HIGH; ++i ) {
		hitag = htag "|" i
		val_obj = hi_in_arr[hitag]

		print "create_hi_freqdial_csv()  hi_in_arr[" hitag "] = [" hi_in_arr[hitag] "]"

		if ( val_obj == "" )
			continue

		split(val_obj, a_arr, "|")
		hi_val = a_arr[1]
		hi_dialno = a_arr[2]
		hi_sid_centre = a_arr[3]
		hi_sid_project = a_arr[4]
		hi_sid = a_arr[5]
		hi_sid_count = a_arr[6]

		onnet = (is_onnet(hi_dialno) != "") ? "Yes" : ""

		hi_count = hi_val
		hi_duration = dist_freq_numbers_duration_arr[htag "|" hi_dialno]
		hi_cost = dist_freq_numbers_cost_arr[htag "|" hi_dialno]

		#rjs4
		#hi_sid_costcentre = hi_sid_centre "-" hi_sid_project
		set_project_displayinfo(hi_sid_centre, hi_sid_project)
 		#rjs9 hi_sid_costcentre = ccp "-" ccpdesc

		csvstr = sprintf(",,,,,,,,,%s,%s,%s,%s,%0.2f,%s,%s,%s\n", hi_dialno,onnet,hi_count,hi_duration,mround2(hi_cost), hi_sid, hi_sid_costcentre, hi_sid_count)
		
		#printf("%s", csvstr)
		printf("%s", csvstr) >>HIFREQ_fname
	}
	close(HIFREQ_fname)
}


function create_call_distr_by_date_csv(repid, repdesc, DISTID,fdistid, SERVTYPE)
{
	CALLDISTR_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, repid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_CALLDISTR_fname_header_arr[CALLDISTR_fname] == "" ) {
		printf(">>>          CALLDISTR_fname = %s\n", CALLDISTR_fname)
		if ( (getline x < CALLDISTR_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(CALLDISTR_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,Day,Count,Duration,Cost:Float\n", repdesc, exbillperiod, "SDATE", "EDATE", repid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>CALLDISTR_fname

		}
		else {
			printf("WARNING %d: CALLDISTR_fname = %s exists.\n", NR, CALLDISTR_fname)
		}
		done_CALLDISTR_fname_header_arr[CALLDISTR_fname] = "1"
	}

	# get oldest and newest year
	oldyyyy = ""
	newyyyy = ""
	for ( Xtag in call_distribution_date_count_arr ) {
		split(Xtag, a_arr, "|")
		cdate = a_arr[3]
		cyyyy = 0 + substr(cdate,7,4)
		if ( oldyyyy == "" || cyyyy < oldyyyy )
			oldyyyy = cyyyy
		if ( newyyyy == "" || cyyyy > newyyyy )
			newyyyy = cyyyy
	}

	# spit records
	htag = DISTID "|" SERVTYPE
	for ( cyear = oldyyyy; cyear != "" && cyear <= newyyyy; ++cyear ) {
	    for ( cmonth = 1; cmonth <= 12; ++cmonth ) {
		for ( cday = 1; cday <= 31; ++cday ) {
			cddmmyyyy = sprintf("%02d-%02d-%04d",cday,cmonth,cyear);
			Xtag = htag "|" cddmmyyyy
			chg_count = call_distribution_date_count_arr[Xtag]
			if ( chg_count == "" )
				continue
			chg_duration = call_distribution_date_duration_arr[Xtag]
			chg_cost = call_distribution_date_cost_arr[Xtag]

			csvstr = sprintf(",,,,,,,,,%s,%d,%d,%0.2f\n", cddmmyyyy,chg_count,chg_duration,mround2(chg_cost))
			
			#printf("%s", csvstr)
			printf("%s", csvstr) >>CALLDISTR_fname
		}
	    }
	}
	close(CALLDISTR_fname)
}


function create_call_distr_by_hour_csv(repid, repdesc, DISTID,fdistid, SERVTYPE)
{
	CALLDISTR_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, repid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_CALLDISTR_fname_header_arr[CALLDISTR_fname] == "" ) {
		printf(">>>          CALLDISTR_fname = %s\n", CALLDISTR_fname)
		if ( (getline x < CALLDISTR_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(CALLDISTR_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,Hour,Count,Duration,Cost:Float\n", repdesc, exbillperiod, "SDATE", "EDATE", repid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>CALLDISTR_fname

		}
		else {
			printf("WARNING %d: CALLDISTR_fname = %s exists.\n", NR, CALLDISTR_fname)
		}
		done_CALLDISTR_fname_header_arr[CALLDISTR_fname] = "1"
	}

	htag = DISTID "|" SERVTYPE

	#ndays = days_in_period
	# count days with data
	ndays = 0
	for ( Atag in call_distribution_byhourdate_arr ) {
		split(Atag, a_arr, "|")
		aservtype = a_arr[1]
		adate = a_arr[2]
		if ( aservtype == SERVTYPE )
			++ndays
	}

	print "create_call_distr_by_hour_csv(" repid "," repdesc ", " DISTID ", " SERVTYPE ")  ndays = " ndays

	if ( ndays <= 0 )
		ndays = 1

	# spit records
	for ( chour = 0; chour <= 23; ++chour ) {
		chh = sprintf("%02d", chour);
		Xtag = htag "|" chh

		chg_count = call_distribution_hour_count_arr[Xtag] / ndays
		chg_duration = call_distribution_hour_duration_arr[Xtag] / ndays
		chg_cost = call_distribution_hour_cost_arr[Xtag] / ndays

		csvstr = sprintf(",,,,,,,,,%d,%d,%d,%0.2f\n", chour+1,chg_count,chg_duration,mround2(chg_cost))
		
		#printf("%s", csvstr)
		printf("%s", csvstr) >>CALLDISTR_fname
	}
	close(CALLDISTR_fname)
}


function create_call_distr_by_category_csv(repid, repdesc, DISTID,fdistid, SERVTYPE)
{
	CALLDISTR_fname = sprintf("topdat/%s/%s/data/mng/mngrep%s_%s.csv", monthdir, fdistid, repid, fdistid)

	itemdesc = "ServiceID"
	if ( SERVTYPE == "1" )
		itemdesc = "Extn"
	if ( SERVTYPE == "10" )
		itemdesc = "Mobile"

	if ( done_CALLDISTR_fname_header_arr[CALLDISTR_fname] == "" ) {
		printf(">>>          CALLDISTR_fname = %s\n", CALLDISTR_fname)
		if ( (getline x < CALLDISTR_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/%s/data/mng", monthdir, fdistid)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", newdir, newdir)
			system(cmd)
			add_fname_to_fnamelist(CALLDISTR_fname)
			# spit header
			csvstr = sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,Category,Count,Duration,Cost:Float\n", repdesc, exbillperiod, "SDATE", "EDATE", repid, DISTIDdesc, DISTID, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE)
			#printf("%s", csvstr)
			printf("%s", csvstr) >>CALLDISTR_fname

		}
		else {
			printf("WARNING %d: CALLDISTR_fname = %s exists.\n", NR, CALLDISTR_fname)
		}
		done_CALLDISTR_fname_header_arr[CALLDISTR_fname] = "1"
	}

	htag = DISTID "|" SERVTYPE

	# fixed/mobile Intra-Organisational (has same data)
	if ( repid == "101" || repid == "102" ) {
		fixedhtag = DISTID "|" "1"
		spit_call_distr_by_category(fixedhtag,"Extension to Extension")
		spit_call_distr_by_category(fixedhtag,"Extension to ONNET Mobile")
		mobhtag = DISTID "|" "10"
		spit_call_distr_by_category(mobhtag,"ONNET Mobile to ONNET Mobile")
		spit_call_distr_by_category(mobhtag,"ONNET Mobile to Extension")
	}

	# fixed by call category
	if ( repid == "111" ) {
		#fixed_callcat_to_chg_cat["P"]
		#fixed_callcat_to_chg_cat["A"]
		#fixed_callcat_to_chg_cat["N"]
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["L"])
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["S"])
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["I"])
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["M"])
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["E"])
		spit_call_distr_by_category(htag, fixed_callcat_to_chg_cat["F"])
		#fixed_callcat_to_chg_cat["J"]
		#fixed_callcat_to_chg_cat["O"]
	}

	# mobile by call category
	if ( repid == "112" ) {
		spit_call_distr_by_category(htag, "Mobile National")
		spit_call_distr_by_category(htag, "Mobile International")
		spit_call_distr_by_category(htag, "Mobile Messaging")
		spit_call_distr_by_category(htag, "Mobile Commerce")
		spit_call_distr_by_category(htag, "Mobile Onnet")
		spit_call_distr_by_category(htag, "Mobile Misc")
		#"All_MOBILE_CDR"
		## "Mobile Rent"
		## "Mobile Call"
		## "Mobile Call Discount"
		##"Mobile Recurring Discount"
		#"Mobile Equipment"
		#"Mobile Adjustment"
		#"Mobile Other"
		#"Mobile Recurring"
		#"Mobile Call Total"
		##"All"
	}

	close(CALLDISTR_fname)
}

function spit_call_distr_by_category(htag,category)
{
	Xtag = htag "|" category

	chg_count = call_distribution_category_count_arr[Xtag]
	chg_duration = call_distribution_category_duration_arr[Xtag]
	chg_cost = call_distribution_category_cost_arr[Xtag]

	csvstr = sprintf(",,,,,,,,,%s,%d,%d,%0.2f\n", category,chg_count,chg_duration,mround2(chg_cost))
	
	#printf("%s", csvstr)
	printf("%s", csvstr) >>CALLDISTR_fname
}




#----------------------------------------------------------
#----------------------------------------------------------

function spit_header_to_wbttopfile()
{
	wbttop_fname = sprintf("topdat/%s/data/wbttop.csv", monthdir)

	if ( retroBDL != "1" ) {
		# create wbttop csv file
		print "spit_header_to_wbttopfile() - wbttop_fname = " wbttop_fname
		csvstr = sprintf("%s,%s,%s,%s,UserID_DESC,UserID,DistID_DESC,DistID,BDMethod,BDType,RealeaseDate,RegenDate,LastSentDate\n", "User List", exbillperiod, "SDATE", "EDATE")
		#printf("%s", csvstr)
		printf("%s", csvstr) >wbttop_fname
	}
}

function spit_USER_to_wbttopfile()
{
	print "spit_USER_to_wbttopfile() - wbttop_fname = " wbttop_fname
	DISTIDdesc = distid_to_distiddesc_arr[DISTID]
	t21name = distid_to_t21name_arr[DISTID]
	t21userid = distid_to_userid_arr[DISTID]
	if ( t21userid == "" )
		t21userid = distid_to_directoryID_arr[DISTID]
	t21wbd_method = distid_to_wbd_method_arr[DISTID]
	t21wbd_type = distid_to_wbd_type_arr[DISTID]
	bm_releasedate = ""	# release date in wbttop (set by user later)
	bm_regendate = (retroBDL == "1") ? cur_dd_mm_yyyy : "" # gen/regen date
	bm_lastsentdate = ""	# last emailed date

	csvstr = sprintf(",,,,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", t21name, t21userid, DISTIDdesc, DISTID, t21wbd_method, t21wbd_type, bm_releasedate, bm_regendate, bm_lastsentdate)

	if ( retroBDL == "1" ) {

		save_wbttop_fname = sprintf("topdat/%s/data/orig_wbttop.csv", monthdir)
		# if not already saved, save original wbttop csv file
		if ( (getline x < save_wbttop_fname) < 0 ) {
			system("cp " wbttop_fname " " save_wbttop_fname)
		}
		close(save_wbttop_fname)

		# users in wbttop csv file
		tmp_wbttop_fname = sprintf("/tmp/%s_%s_wbttop.csv", monthdir, DISTID)
		print "replace DISTID=" DISTID " in " wbttop_fname
		replaced = 0
		while ( (getline wbttopline < wbttop_fname) > 0 ) {
			split(wbttopline, wbttop_arr, ",")
			adistid = clip(wbttop_arr[8])
			#print "  adistid = [" adistid "]"
			if ( adistid == DISTID ) {
				replaced = 1
				print "   replaced [" csvstr "]"
				printf("%s", csvstr) >>tmp_wbttop_fname
			}
			else {
				printf("%s\n", wbttopline) >>tmp_wbttop_fname
			}
		}
		if ( !replaced ) {	# must be new - so append
			print "   appending new [" csvstr "]"
			printf("%s", csvstr) >>tmp_wbttop_fname
		}
		close(wbttop_fname)
		close(tmp_wbttop_fname)
		system("cp " tmp_wbttop_fname " " wbttop_fname)
		system("rm " tmp_wbttop_fname)
	}
	else {
		# append user to wbttop csv file
		#printf("%s", csvstr)
		printf("%s", csvstr) >>wbttop_fname
	}
}


#----------------------------------------------------------
#----------------------------------------------------------

function set_project_displayinfo(centre,project)
{
	if ( centre != "All" && project == "All" ) {
		#grid = CENTRE_to_GGRID_arr[CENTRE]
		#childcount = childcount_arr[grid]
		#if ( childcount == 1 )
		if ( CHILDCOUNT == 1 )
			disp_project = PROJECT
		else
			disp_project = "All"
	}
	else {
		disp_project = project
	}
	if ( addstar != "" )
		disp_project = disp_project addstar

        if ( project == "All" ) {
                projectfilter = "All"
                #if ( centre == "All" )
                #       ccpdesc = "Your Cost Centres"
                #else
                #       ccpdesc = CENTRE_to_CENTREdesc_arr[centre]
		if ( addstar == "" ) {
			#rjsPTC ccpdesc = "All"	#rjs4 CENTRE_to_CENTREdesc_arr[centre]
			# rjs9
			#ccpdesc = CENTRE_to_CENTREdesc2_arr[CENTRE]

			## customer desc in desc
			#shipto = CENTRE_to_ShipTo_arr[CENTRE]
			#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]

			# tbs group desc in desc
			deptid = CENTRE_to_GGRID_arr[CENTRE]
			groupid = grid_to_parentgroupid_arr[deptid]
			groupdesc = grid_to_grname3_arr[groupid]
			ccpdesc = groupdesc

		}
		else {
			# rjs9
			#ccpdesc = CENTREPROJECT_to_PROJECTdesc_arr[centre "|" PROJECT]

			## customer desc in desc
			#shipto = CENTRE_to_ShipTo_arr[CENTRE]
			#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]

			# tbs group desc in desc
			deptid = CENTRE_to_GGRID_arr[CENTRE]
			groupid = grid_to_parentgroupid_arr[deptid]
			groupdesc = grid_to_grname3_arr[groupid]
			ccpdesc = groupdesc
		}
	}
	else {
		projectfilter = "List"
		# rjs9
		#ccpdesc = CENTREPROJECT_to_PROJECTdesc_arr[centre "|" project]

		## customer desc in desc
		#shipto = CENTRE_to_ShipTo_arr[CENTRE]
		#ccpdesc = ShipTo_to_CustomerDesc_arr[shipto]

		# tbs group desc in desc
		deptid = CENTRE_to_GGRID_arr[CENTRE]
		groupid = grid_to_parentgroupid_arr[deptid]
		groupdesc = grid_to_grname3_arr[groupid]
		ccpdesc = groupdesc
	}

	#rjs4
	#ccp = centre "-" disp_project
	ccpid = centre "|" disp_project

	division = CENTRE_to_ShipTo_arr[CENTRE]
	divisiondesc = ShipTo_to_CustomerDesc_arr[division]
print "XYZZY division = [" division "]" "  divisiondesc = [" divisiondesc "]"


	CENTREdesc = CENTRE_to_CENTREdesc_arr[CENTRE]
	PROJECTdesc3 = CENTREPROJECT_to_PROJECTdesc3_arr[CENTRE "|" PROJECT]

	if ( centre == "All" )
		display_centredesc = "All"
	else
		display_centredesc = CENTREdesc

	if ( disp_project == "All" )
		display_projectdesc = "All"
	else
		display_projectdesc = PROJECTdesc3

	ccp = ccpid "|" display_centredesc "-" display_projectdesc
}


#----------------------------------------------------------
#----------------------------------------------------------

function finish_proc_dist_lists()
{
	print ""
	print "finish_proc_dist_lists()"
	system("date")

	# process distribution lists

	spit_header_to_wbttopfile()

	for ( DISTID in distid_to_distiddesc_arr ) {
		DISTIDdesc = distid_to_distiddesc_arr[DISTID]
		t21name = distid_to_t21name_arr[DISTID]
		t21userid = distid_to_userid_arr[DISTID]
		if ( t21userid == "" )
			t21userid = distid_to_directoryID_arr[DISTID]
		t21wbd_method = distid_to_wbd_method_arr[DISTID]
		t21wbd_type = distid_to_wbd_type_arr[DISTID]

		if ( done_DISTID_totals_arr[DISTID] != "" ) {
			print "finish DISTID=[" DISTID "]" "  t21name=[" t21name "]" "  t21userid=[" t21userid "]" "  t21wbd_type=[" t21wbd_type "]"

			spit_USER_to_wbttopfile()

			# skip virtual management
			if ( virtual_management_distid_arr[DISTID] != "" )
				continue

			## vmng
			#svdistid = DISTID
			#if ( virtual_management_distid_arr[DISTID] != "" )
			#	DISTID = virtual_management_distid_arr[DISTID]

			#spit_DISTIDtotals_to_TOTALSfile()
			#gen_top_csv()
			#cpy_img(0)

			mk_dircsvfile()

			add_fname_to_fnamelist(fnamelist_fname)

			add_fname_to_fnamelist(wbttop_fname)

			mk_useridfile()

			# create distid file
			# for PERSONAL virtual
			# (configured list are done from distidfile_totals)
			if ( Vdistid_to_directoryID_arr[DISTID] )
				mk_distidfile()

			# create user html index file link
			if ( LinkUserHTMLindex )
				ln_userhtml_index()

			if ( retroBDL == "1" ) {
				# create index files
				cmd = sprintf("mkind \"topdat/%s/%s\"", monthdir, DISTID)
				print "run: cmd = " cmd
				system(cmd)
			}

			## vmng
			#DISTID = svdistid
		}
	}

	print ""
}


#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------

function get_t21info(servtype,egrid,sid)
{
        #if ( servtype == 5 ) { // account code
        #       t21name = ""
        #       t21surname = ""
        #       t21firstname = ""
        #       t21location = ""
        #       t21site = ""
        #       return
        #}

	#itag = egrid "|" sid
	itag = sid
	t21name = dirextn_to_t21name_arr[itag]
	t21surname = dirextn_to_t21surname_arr[itag]
	t21firstname = dirextn_to_t21firstname_arr[itag]
	t21location = dirextn_to_t21location_arr[itag]
	t21site = dirextn_to_t21site_arr[itag]

	# now set in get_mobileinfo
	#if ( SERVTYPE == 10 && sid == "" ) {	# mobile GROUP ASSIGNED
	#	t21location = ""
	#	t21site = egrid_to_t21site_arr[egrid]
	#}

	if ( t21name == "_blank_" )
		t21name = ""
	if ( t21surname == "_blank_" )
		t21surname = ""
	if ( t21firstname == "_blank_" )
		t21firstname = ""
	if ( t21location == "_blank_" )
		t21location = ""

	if ( t21site == "" && sid != "All" ) {
		#print "BLANK CAMPUS" "  extn_to_egridlist_arr[" sid "]=[" extn_to_egridlist_arr[sid] "]"
		if ( extn_to_egridlist_arr[sid] == "" )
			t21site = "NOT FOUND"
		else
			t21site = "MOVED"
	}

	#print "get_t21info() itag=" itag "  t21name=[" t21name "]  t21site=[" t21site "]"
}

#----------------------------------------------------------

function get_mobileinfo(a,servtype,sid)
{
	mobile = sid
	gsub(" ","",mobile)
	gsub("-","",mobile)
	if ( mobile == "_blank_" )
		mobile = ""
	mobname = mobile_to_name_arr[mobile]
	if ( mob_name == "_blank_" )
		mob_name = "BLANK NAME"

	directoryID = mobile_to_directoryID_arr[mobile]
	if ( directoryID <= 0 || directoryID == "" ) {	# GROUP ASSIGNED
		t21_extn = ""
		siteid = ""
		t21surname = ""
		t21firstname = ""
		t21name = ""
		t21site = egrid_to_t21site_arr[t21_EGRID]
		t21location = ""
		t21division = ""
	}
	else {
		t21_extn = recordno_to_extn_arr[directoryID]
		siteid = get_siteid(t21_extn)
		t21surname = recordno_to_t21surname_arr[recordno]
		t21firstname = recordno_to_t21firstname_arr[recordno]
		t21name = recordno_to_t21name_arr[directoryID]
		t21site = recordno_to_t21site_arr[directoryID]
		t21location = recordno_to_t21location_arr[directoryID]
		t21division = recordno_to_t21division_arr[recordno]
	}

	if ( t21_extn == "_blank_" )
		t21_extn = ""
	if ( mobname == "_blank_" )
		mobname = ""
	if ( t21name == "_blank_" )
		t21name = ""
	if ( t21surname == "_blank_" )
		t21surname = ""
	if ( t21firstname == "_blank_" )
		t21firstname = ""
	if ( t21site == "_blank_" )
		t21site = ""
	if ( t21location == "_blank_" )
		t21location = ""
	if ( t21division == "_blank_" )
		t21division = ""

	if ( a == 2 )
		print a " " "get_mobileinfo() mobile=[" mobile "]  mobname=[" mobname "]  directoryID=[" directoryID "]  t21_extn=[" t21_extn "]   siteid=[" siteid "]"
}



#----------------------------------------------------------

#rjs9 - called from ldt21detiail/ld_cde
function set_HIERIDx(servtype,centre,project,sid,supplier,rec_type,chg_cat)
{
	HIERIDx = HIERID "|"
	HIERID = servtype "|" centre "|" project
	HIERID = HIERID "|" sid
	HIERID = HIERID "|" supplier
	HIERID = HIERID "|" rec_type
	HIERID = HIERID "|" chg_cat
	#HIERIDxDUPcount = ++HIERIDxcount[HIERID]
	#HIERID = HIERID "|" HIERIDxDUPcount
	HIERIDx = HIERID "|"

	#print "set HIERIDx = " HIERIDx

	# for getting processing order
	#pipecmd = "sort >" logdir "/" "HIERIDx_" batchtag ".lst"
	#print HIERIDx | pipecmd
	HIERIDxsortcmd = "sort -u >" HIERIDxfile
	#print "HIERIDxsortcmd=[" HIERIDxsortcmd "]"
	print HIERIDx | HIERIDxsortcmd
}


function get_HIERIDx_info(HIERIDx,printflag)
{
	split(HIERIDx, HIERIDx_arr, "|")
	
	SERVTYPE = HIERIDx_arr[1]
	CENTRE = HIERIDx_arr[2]
	PROJECT = HIERIDx_arr[3]
	SID = HIERIDx_arr[4]
	SUPPLIER = HIERIDx_arr[5]
	REC_TYPE = HIERIDx_arr[6]
	CHG_CAT = HIERIDx_arr[7]
	#HIERIDxDUPcount = HIERIDx_arr[8]

	# rjs9-
	# if called from ld_cde()
	tascode = ""
	location = ""
	user = ""
	costcentre = ""
	sundry = ""
	invoiceno = ""
	from_tbs = 0
	if ( split(CHG_CAT, chgcat_arr, "~") == 6 ) {
		f = 0
		tascode = chgcat_arr[++f]
		location =chgcat_arr[++f]
		user =chgcat_arr[++f]
		costcentre =chgcat_arr[++f]
		sundry =chgcat_arr[++f]
		invoiceno =chgcat_arr[++f]
		from_tbs = 1
	}

	if ( from_tbs == 1 ) {
		rentcost = HIERIDx_to_rentcost_arr[HIERIDx]
		callcost = HIERIDx_to_callcost_arr[HIERIDx]
		othercost = HIERIDx_to_othercost_arr[HIERIDx]
	}
	else {
		rentcost = 0
		callcost = 0
		othercost = 0
	}
	#-rjs9

	totalcost = HIERIDx_to_totalcost_arr[HIERIDx]

	SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]

	CENTREdesc = CENTRE_to_CENTREdesc_arr[CENTRE]
	CENTREdesc1 = CENTRE_to_CENTREdesc1_arr[CENTRE]
	CENTREdesc2 = CENTRE_to_CENTREdesc2_arr[CENTRE]
	CENTREdesc3 = CENTRE_to_CENTREdesc3_arr[CENTRE]

	PROJECTdesc = CENTREPROJECT_to_PROJECTdesc_arr[CENTRE "|" PROJECT]
	PROJECTdesc1 = CENTREPROJECT_to_PROJECTdesc1_arr[CENTRE "|" PROJECT]
	PROJECTdesc2 = CENTREPROJECT_to_PROJECTdesc2_arr[CENTRE "|" PROJECT]
	PROJECTdesc3 = CENTREPROJECT_to_PROJECTdesc3_arr[CENTRE "|" PROJECT]

	GGRID = CENTRE_to_GGRID_arr[CENTRE]

	# rjs9 centre|project has multiple egrids
	#EGRID = CENTREPROJECT_to_EGRID_arr[CENTRE "|" PROJECT]
	EGRID = CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID]

	t21_GGRID = GGRID
	t21_EGRID = EGRID
	t21_SID = SID

	CHILDCOUNT = childcount_arr[GGRID]

	Xtag = "TOTAL" "|" SERVTYPE "|" CENTRE "|" PROJECT "|" SID "|" SUPPLIER "|" CHG_CAT
	totalcount = totalcount_arr[Xtag]
	totalduration = totalduration_arr[Xtag]
	totalcost = totalcost_arr[Xtag]

	#if ( 0 ) {
	if ( printflag > 1 ) {
		printf("\n")
		printf("get_HIERIDx_info()\n")
		printf("           HIERIDx = %s\n", HIERIDx)
		#printf("   HIERIDxDUPcount = %d\n", HIERIDxDUPcount)
		printf("           SERVTYPE = [(%s)%s]\n", SERVTYPE, SERVTYPEdesc)
		printf("            CENTRE = [(%s)%s]\n", CENTRE, CENTREdesc)
		printf("             GGRID = %s\n", GGRID)
		printf("        CHILDCOUNT = %d\n", CHILDCOUNT)
		printf("           PROJECT = [(%s)%s]\n", PROJECT, PROJECTdesc)
		printf("             EGRID = %s\n", EGRID)
		printf("               SID = %s\n", SID)
		printf("          SUPPLIER = %s\n", SUPPLIER)
		printf("          REC_TYPE = %s\n", REC_TYPE)
		printf("           CHG_CAT = %s\n", CHG_CAT)
		printf("              Xtag = [%s]\n", Xtag)
		printf("  rentcost   = [%s]\n", rentcost)
		printf("  callcost   = [%s]\n", callcost)
		printf("  othercost  = [%s]\n", othercost)
		printf("        totalcount = [%s]\n", totalcount)
		printf("     totalduration = [%s]\n", totalduration)
		printf("         totalcost = [%s]\n", totalcost)
	}
	if ( printflag ) {
		printf("get_HIERIDx_info()\n");
		printf("%d|%s (%s)%s (%s)%s %s (%s)%s %s %s %s|TOTAL = %f\n", HIERIDxDUPcount, GGRID, CENTRE, CENTREdesc, SERVTYPE, SERVTYPEdesc, EGRID, PROJECT, PROJECTdesc, SID, SUPPLIER, CHG_CAT, totalcost)
	}
}


# rjs9 victrack wb3 version
function VICTRACK_get_HIERIDx_info(HIERIDx,printflag)
{
	split(HIERIDx, HIERIDx_arr, "|")

	f = 0
	SERVTYPE = HIERIDx_arr[++f]
	DIVID = HIERIDx_arr[++f]
	DIVIDdesc1 = DIVID_to_DIVIDdesc1_arr[DIVID]
	DIVIDdesc2 = DIVID_to_DIVIDdesc2_arr[DIVID]
	ShipToDesc = ShipTo_to_CustomerDesc_arr[DIVID]
	SGID = HIERIDx_arr[++f]
	SGIDdesc = SGID_to_SGIDdesc_arr[SGID]
	SEID = HIERIDx_arr[++f]
	SEIDdesc = SEID_to_SEIDdesc_arr[SEID]
	DEPTID = HIERIDx_arr[++f]
	department = DEPTID_to_department_arr[DEPTID]
	SID = HIERIDx_arr[++f]
	tbsCENTREID = HIERIDx_arr[++f]
	supplier = HIERIDx_arr[++f]
	tascode = HIERIDx_arr[++f]
	location = HIERIDx_arr[++f]
	user = HIERIDx_arr[++f]
	costcentre = HIERIDx_arr[++f]
	sundry = HIERIDx_arr[++f]
	invoiceno = HIERIDx_arr[++f];
	
	HIERIDxDUPcount = HIERIDx_arr[++f]

	ORGELEMENTID = SEID_to_orgElementID_arr[SEID]

#rjs9
#	#itag = DIVID "|" sundry
#	itag = DIVID "|" sundry "|" ORGELEMENTID
#	platinv_batch = parent_sundry_to_platinv_batch_arr[itag]
	print "GHID: parent_sundry_to_platinv_batch_arr[" itag "]=[" parent_sundry_to_platinv_batch_arr[itag] "]"
#	if ( platinumBATCH != "all" ) {
#		# use customer invoice number for service group desc
#		# (instead of All)
#		SGIDdesc = invoiceno
#	}

	SIDdesc = user

	#sundry = HIERIDx_to_sundry_arr[HIERIDx]
	#
	#supplier = HIERIDx_to_supplier_arr[HIERIDx]
	#tascode = HIERIDx_to_tascode_arr[HIERIDx]
	#location = HIERIDx_to_location_arr[HIERIDx]
	#user = HIERIDx_to_user_arr[HIERIDx]
	#costcentre = HIERIDx_to_costcentre_arr[HIERIDx]

	idtag = sprintf("%s_%s", DIVID, monthtag);
	if ( printflag > 1 ) {
		printf("idtag = %s\n", idtag);
	}
	#pardir = idtag;
#rjs9
#	this_divgroup = exwebconf_parent_to_cdgroup_arr[DIVID]
#	if ( this_divgroup == "" )	# single div
#		this_divgroup = DIVID	# (force single to a divgroup)
#	if ( this_divgroup != "" )	# belongs to a cdgroup
#		pardir = monthtag "/" platinumBATCH "_" thisDIVID "/" this_divgroup "/" DIVID
#	else
#		pardir = monthtag "/" platinumBATCH "_" thisDIVID "/" DIVID
#	#printf("pardir = %s\n", pardir);
#-rjs9

	if ( printflag > 1 ) {
		printf("\n")
		printf("HIERIDxDUPcount = %d\n", HIERIDxDUPcount)
		printf("HIERIDx  = %s\n", HIERIDx)
		printf("platinv_batch                = [%s]\n", platinv_batch)
		printf("SID        = [%s]\n", SID)
		printf("invoiceno  = [%s]\n", invoiceno)
		printf("sundry     = [%s]\n", sundry)
		printf("supplier   = [%s]\n", supplier)
		printf("location   = [%s]\n", location)
		printf("user       = [%s]\n", user)
		printf("costcentre = [%s]\n", costcentre)
		printf("rentcost   = [%s]\n", rentcost)
		printf("callcost   = [%s]\n", callcost)
		printf("othercost  = [%s]\n", othercost)
		printf("totalcost  = [%s]\n", totalcost)
		printf("department = [(%d)%s]\n", DEPTID, department)
		printf("tascode    = [%s]\n", tascode)
		printf("ELEMENTID  = [%s]\n", ELEMENTID)
		printf("SEID       = [(%s)%s]\n", SEID, SEIDdesc)
		printf("SGID       = [(%d)%s]\n", SGID, SGIDdesc)
		printf("DIVID      = [(%s)%s|%s]\n", DIVID, DIVIDdesc1, ShipToDesc)
	}
	if ( 0 && printflag ) {
		printf("%d|%s|%s|%s|%s|%s|%s|%f|%f|%f|TOTAL = %f|>DEPT(%d)%s >%s >SEID(%d)%s >SGID(%d)%s >DIV:(%s)%s|%s\n", HIERIDxDUPcount, SID, sundry, supplier, location, user, costcentre, rentcost, callcost, othercost, totalcost, DEPTID, department, tascode, SEID, SEIDdesc, SGID, SGIDdesc, DIVID, DIVIDdesc1, ShipToDesc)
	}
}



#-----------------------------------------------------------

function test_grid1_belongs_to_grid2( grid1, grid2 )
{
	#print "    test_grid_belongs_to_grid(" grid1 "," grid2 ")"

	tstgrid = grid1

	#print "      testing tstgrid = [" tstgrid "]"
	#if ( tstgrid == grid2 )
	#	return 1

	while ( tstgrid != "" ) {
		#print "      testing tstgrid = [" tstgrid "]"
		if ( tstgrid == grid2 ) {
			#print "      matched tstgrid = [" tstgrid "]"
			return 1
		}
		tstgrid = grid_to_parentgroupid_arr[tstgrid]
	}

	#print "      NO MATCH for grid2 = [" grid2 "]"
	return 0
}


function test_exclude(servicetypeid, siteid, grid, extn)
{
	#print "test_exclude(" servicetypeid "," siteid "," grid "," extn ")"

	for ( exclude_tag in exclude_arr ) {
		#print "TEST exclude_arr[" exclude_tag "]=" exclude_arr[exclude_tag]

		do_exclude_servicetypeid = 0
		do_exclude_siteid = 0
		do_exclude_grid = 0
		do_exclude_extnlo = 0
		do_exclude_extnhi = 0
		do_exclude_extnrange = 0

		split(exclude_tag, exclude_entry_arr, "|")
		exclude_servicetypeid = exclude_entry_arr[1]
		exclude_siteid = exclude_entry_arr[2]
		exclude_grid = exclude_entry_arr[3]
		exclude_extnlo = exclude_entry_arr[4]
		exclude_extnhi = exclude_entry_arr[5]

		#print "      TEST exclude_servicetypeid=" "[" exclude_servicetypeid "]"
		#print "                  exclude_siteid=" "[" exclude_siteid "]"
		#print "                    exclude_grid=" "[" exclude_grid "]"
		#print "                  exclude_extnlo=" "[" exclude_extnlo "]" "  exclude_extnhi=" "[" exclude_extnhi "]"

		# not for this servicetype
		if ( exclude_servicetypeid != "" && exclude_servicetypeid == servicetypeid ) {
			print "      doexclude servicetype=" servicetype
			do_exclude_servicetypeid = 1
		}

		# Exclude if belongs to siteid exclude
		if ( exclude_siteid != "" && exclude_siteid == siteid ) {
			print "      doexclude siteid=" siteid
			do_exclude_siteid = 1
		}

		# Exclude if belongs to grid exclude
		if ( exclude_grid != "" && test_grid1_belongs_to_grid2(grid, exclude_grid) ) {
			print "      doexclude grid=" grid
			do_exclude_grid = 1
		}

		# Exclude if belongs to extn range excude
		excludeextn = 0
		if ( exclude_extnlo != "" && exclude_extnhi == "" && extn == exclude_extnlo ) {
			print "      doexclude exclude_extnlo=" exclude_extnlo
			do_exclude_extnlo = 1
		}
		if ( exclude_extnlo == "" && exclude_extnhi != "" && extn == exclude_extnhi ) {
			print "      doexclude exclude_extnhi=" exclude_extnhi
			do_exclude_extnhi = 1
		}
		if ( exclude_extnlo != "" && exclude_extnhi != "" && extn >= exclude_extnlo && extn <= exclude_extnhi ) {
			print "      doexclude extn=" extn "   BETWEEN " exclude_extnlo " and " exclude_extnhi
			do_exclude_extnrange = 1
		}

		#print " do_exclude_servicetypeid=" "[" do_exclude_servicetypeid "]"
		#print "        do_exclude_siteid=" "[" do_exclude_siteid "]"
		#print "          do_exclude_grid=" "[" do_exclude_grid "]"
		#print "        do_exclude_extnlo=" "[" do_exclude_extnlo "]"
		#print "        do_exclude_extnhi=" "[" do_exclude_extnhi "]"
		#print "     do_exclude_extnrange=" "[" do_exclude_extnrange "]"

		# if more than one condition in the same row is specified
		# then AND applies
		if ( (exclude_servicetypeid == "" || do_exclude_servicetypeid) && (exclude_siteid == "" || do_exclude_siteid) && (exclude_grid == "" || do_exclude_grid) && ((exclude_extnlo == "" || exclude_extnhi != "" ) || do_exclude_extnlo) && ((exclude_extnhi == "" || exclude_extnlo != "" ) || do_exclude_extnhi) && ((exclude_extnlo == "" && excludeextnhi == "") || do_exclude_extnrange)) {
			print "  DOEXCLUDE test_exclude(" servicetypeid "," siteid "," grid "," extn ")    exclude_arr[" exclude_tag "]=" exclude_arr[exclude_tag]
			return 1
		}
	}

	return 0
}

#----------------------------------------------------------
#----------------------------------------------------------

function get_ggname(gggrid) {
	# get group name
	ggname = grid_to_grname3_arr[gggrid]
	#printf("get_ggname(): gggrid = %s  ggname = %s\n", gggrid, ggname)
	return
}


function get_egname(eggrid) {
	# get group name
	egname = grid_to_grname3_arr[eggrid]
	egccp = grid_to_ccp_arr[eggrid]
	#printf("get_egname(): eggrid = %s  egname = %s  egccp = %s\n", eggrid, egname, egccp)
	return
}


function get_dirname(siteid,eggrid,extn) {
	# get name from directory
	#itag = eggrid "|" extn
	itag = extn
	t21surname = dirextn_to_t21surname_arr[itag]
	t21firstname = dirextn_to_t21firstname_arr[itag]
	#printf("get_dirname(" siteid "," eggrid "," extn "): eggrid=%s  extn=%s  t21surname = %s  t21firstname = %s\n", eggrid, extn, t21surname, t21firstname)
	t21name = dirextn_to_t21name_arr[itag]
	if ( t21name == "_blank_" )
		t21name = ""
	if ( t21surname == "_blank_" )
		t21surname = ""
	if ( t21firstname == "_blank_" )
		t21firstname = ""
	#printf("get_dirname(): siteid = %d  eggrid= %s extn = %s  t21name = %s\n", siteid, eggrid, extn, t21name)
	return t21name
}


function get_t21_upper_info(gggrid, eggrid)
{
	t21_SERVTYPE = SERVTYPE
	t21_SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[t21_SERVTYPE]

	#t21_CENTRE = gggrid
	t21_CENTRE = grid_to_centre_arr[gggrid]
	t21_EGRID = eggrid

	t21_CENTREdesc1 = CENTRE_to_CENTREdesc1_arr[t21_CENTRE]
	t21_CENTREdesc2 = CENTRE_to_CENTREdesc2_arr[t21_CENTRE]
	t21_CENTREdesc3 = CENTRE_to_CENTREdesc3_arr[t21_CENTRE]
	t21_CENTREdesc = CENTRE_to_CENTREdesc_arr[t21_CENTRE]

	t21_PROJECT = grid_to_project_arr[t21_EGRID]
	t21_PROJECTdesc = grid_to_grname3_arr[t21_EGRID]
	t21_CCPdesc = grid_to_grname2_arr[t21_EGRID]	# Cost Centre
	## rjs9
	#pargrid = grid_to_parentgroupid_arr[t21_EGRID]
	#t21_PROJECT = grid_to_project_arr[pargrid]
	#t21_PROJECTdesc = grid_to_grname3_arr[pargrid]
	#t21_CCPdesc = grid_to_grname2_arr[pargrid]	# Cost Centre

	printf("get_t21_upper_info(%s,%s): %s|%s|(%s) %s\n", gggrid, eggrid, t21_EGRID, serviceprovider, t21_CENTRE, t21_CENTREdesc)
}


#####################################

function spit_totals_csvdata()
{
	if ( last_SERVTYPE == 10 ) {
		#totcsvfile = totalscsvfile "_" last_SERVTYPE ".csv"
		totcsvfile = totalscsvfile "_" "mobiles" ".csv"
	}
	else {
		totcsvfile = totalscsvfile ".csv"
	}


	Xsid = "All"
	Xsupplier = "All"
	Xcat = "All"

	one_line_per_servicetype = 0
	if ( last_SERVTYPE == 10 )
		one_line_per_servicetype = 1

	if ( one_line_per_servicetype ) {
		Xtotalcost = totalcost_arr["TOTAL" "|" last_SERVTYPE "|" last_CENTRE "|" last_PROJECT "|" Xsid "|" Xsupplier "|" Xcat]
		if ( Xtotalcost != 0 ) {
			print "spit_totals_csvdata() - totcsvfile=" totcsvfile " - for " last_SERVTYPE "  " last_CENTRE "  " last_PROJECT "  " totalcost_arr["TOTAL" "|" last_SERVTYPE "|" last_CENTRE "|" last_PROJECT "|" Xsid "|" Xsupplier "|" Xcat]

			printf("%s,%s,%s,%s,%s,%s,%s,%0.2f\r\n", SERVTYPE_to_SERVTYPEdesc_arr[last_SERVTYPE], CENTRE_to_CENTEdesc_arr[last_CENTRE], CENEPROJECT_to_PROJECTdesc3_arr[last_CENTRE "|" last_PROJECT], CENTREPROJECT_to_PROJECTdesc2_arr[last_CENTRE "|" last_PROJECT], CENTREPROJECT_to_PROJECTdesc3_arr[last_CENTRE "|" last_PROJECT], last_GGRID, last_EGRID, mround2(Xtotalcost)) >>totcsvfile
		}
	}
	else {
		# totals for servicetypes in separate cols
		if ( done_CENTRE_PROJECT_totcsv_arr[last_CENTRE "|" last_PROJECT] != 1 ) {
			done_CENTRE_PROJECT_totcsv_arr[last_CENTRE "|" last_PROJECT] = 1
			tot_overheads_cost = 0 + totalcost_arr["TOTAL" "|" "4" "|" last_CENTRE "|" last_PROJECT "|" "All" "|" "All" "|" "All"]
			tot_calls_cost = 0 + totalcost_arr["TOTAL" "|" "1" "|" last_CENTRE "|" last_PROJECT "|" "All" "|" "All" "|" "All"]
			tot_misc_cost = 0 + totalcost_arr["TOTAL" "|" "3" "|" last_CENTRE "|" last_PROJECT "|" "All" "|" "All" "|" "All"]
			#tot_cost = 0 + totalcost_arr["TOTAL" "|" "All" "|" last_CENTRE "|" last_PROJECT "|" "All" "|" "All" "|" "All"]
			Xtotalcost = tot_overheads_cost + tot_calls_cost + tot_misc_cost
			if ( Xtotalcost != 0 ) {
				print "spit_totals_csvdata() - " totcsvfile " - for " last_CENTRE "  " last_PROJECT "  " tot_overheads_cost "  " tot_calls_cost "  " tot_misc_cost "  " Xtotalcost

				# cost for ovheads/calls/misc and total
				printf("%s,%s,%s,%s,%s,%0.2f,%0.2f,%0.2f,%0.2f\r\n", CENTRE_to_CENTREdesc_arr[last_CENTRE], CENTREPROJECT_to_PROJECTdesc3_arr[last_CENTRE "|" last_PROJECT], CENTREPROJECT_to_PROJECTdesc2_arr[last_CENTRE "|" last_PROJECT], last_GGRID, last_EGRID, mround2(tot_overheads_cost), mround2(tot_calls_cost), mround2(tot_misc_cost), mround2(Xtotalcost)) >>totcsvfile
			}
		}

	}
}

###-------------

function spit_totals_rep_all()
{
	print "spit_totals_rep_all() - " totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	printf("             Grand Total                                   $%9.2f\r\n", mround2(totalcost_arr["TOTAL" "|" "All" "|" "All" "|" "All" "|" "All" "|" "All" "|" "All"])) >>totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	close(totalsrepfile)
}

function spit_totals_rep_servtype()
{
	print "spit_totals_rep_servtype() - " totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	printf("    %-40.40s   Total        $%9.2f\r\n", SERVTYPE_to_SERVTYPEdesc_arr[last_SERVTYPE], mround2(totalcost_arr["TOTAL" "|" last_SERVTYPE "|" "All" "|" "All" "|" "All" "|" "All" "|" "All"])) >>totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	close(totalsrepfile)
}


function spit_totals_rep_centre()
{
	print "spit_totals_rep_centre() - " totalsrepfile
	printf("%-8.8s Total - %-40.40s   $%9.2f\r\n", last_GGRID, CENTRE_to_CENTREdesc_arr[last_CENTRE], mround2(totalcost_arr["TOTAL" "|" last_SERVTYPE "|" last_CENTRE "|" "All" "|" "All" "|" "All" "|" "All"])) >>totalsrepfile
	printf("\r\n\r\n") >>totalsrepfile
	close(totalsrepfile)
}


function spit_totals_rep_project()
{
	print "spit_totals_rep_project() - " totalsrepfile

	printf("%-8.8s %-8.8s  %-40.40s $%9.2f\r\n", last_GGRID, last_EGRID, CENTREPROJECT_to_PROJECTdesc_arr[last_CENTRE "|" last_PROJECT], mround2(totalcost_arr["TOTAL" "|" last_SERVTYPE "|" last_CENTRE "|" last_PROJECT "|" "All" "|" "All" "|" "All"])) >>totalsrepfile
	close(totalsrepfile)
}



#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------




# Mobile Call Details
#####################################################
#####################################################
#####################################################
#####################################################

function create_mobile_detail_file()
{
	if ( testmobdet == 1 || retroBDL != "1" ) {
		if ( mobile_fname != "" ) {	# close previous file
			close(mobile_fname)
			mobile_fname = ""
		}
	}
	mobile_fname = sprintf("topdat/%s/data/mobile%s/mobile_%s_%s_%s_%s.csv", monthdir, SERVTYPE, CENTRE, PROJECT, SERVTYPE, SID)
	fname_to_SERVTYPECENTREPROJECT_arr[mobile_fname] = SERVTYPE "|" CENTRE "|" PROJECT
	if ( testmobdet == 0 && retroBDL == "1" )
		return
	printf(">>>            mobile_fname = %s\n", mobile_fname)
	if ( (getline x < mobile_fname) < 0 ) {
		# create file and csv header
		newdir = sprintf("topdat/%s/data/mobile%s", monthdir, SERVTYPE)
		cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
		#print "system 3 [" cmd "]"
		system(cmd)

		CCPdesc = CENTREPROJECT_to_PROJECTdesc_arr[CENTRE "|" PROJECT]
		PROJECTdesc = CENTREPROJECT_to_PROJECTdesc3_arr[CENTRE "|" PROJECT]

		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "ServiceID Detail", exbillperiod, "SDATE", "EDATE", CENTRE_to_CENTREdesc_arr[CENTRE], CENTRE, SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE], SERVTYPE, PROJECTdesc " / " CCPdesc, PROJECT, SID, serviceprovider, mobname "|" mobmanufacturer "|" mobmodel) >mobile_fname
		printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", "RecNo", "RecType", "ChargeCategory", "RecClass", "Date","Time","Origin","Dialled Number","Description","Duration","Cost:Float") >>mobile_fname
	}
	else {
		printf("WARNING %d: mobile_fname = %s exists.\n", NR, mobile_fname)
	}
}


function spit_mdrrec_tomobilefile()
{
	# append mobile call record data to mobile file

	if ( testmobdet == 1 || retroBDL != "1" ) {
		csvstr = sprintf(",,,,,,,,,,,,,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%0.4f\n", mob_recno, mob_rectype, mob_cat, mob_recclass, date, ctimestr, mob_origin, expdialledno, mob_destination, mob_durstr, mround4(mob_cost))

		#printf("%s", csvstr)
		printf("%s", csvstr) >>mobile_fname
	}

}


#################################################################


function domobdetfile(mobcallsfile,servtype,servtypedesc)
{
	printf("domobdet(%s)  servtype=%s\n", mobcallsfile, servtype)
	system("date")

	CENTRE = ""
	PROJECT = ""
	SID = ""

	SERVTYPE_fname = ""
	#CENTRE_fname = ""
	mobile_fname = ""

	SERVTYPE = servtype
	SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]
	print "SERVTYPE = " SERVTYPE "  SERVTYPEdesc = " SERVTYPEdesc

	last_gggrid = "First Time"
	last_eggrid = "First Time"
	last_extn = -1
	last_siteid = -1

	last_SERVTYPE = ""
	last_CENTRE = ""
	last_PROJECT = ""
	last_SID = ""
	last_directoryID = ""

	while ( (getline mobline < mobcallsfile) > 0 ) {
		#print "MOBDET mobline = " mobline
		split(mobline, a_arr, "|")
		mob_sundry = clip(a_arr[1])
		mob_mobile = clip(a_arr[2])
		mob_carrier = toupper(clip(a_arr[3]))
		mob_rectype = clip(a_arr[4])
		mob_recclass = clip(a_arr[5])
		mob_billperiod = clip(a_arr[6])
		mob_cdate = clip(a_arr[7])
		mob_ctime = clip(a_arr[8])
		mob_origin = clip(a_arr[9])
		mob_destination = clip(a_arr[10])
		mob_dialled = clip(a_arr[11])
		mob_rate = clip(a_arr[12])
		mob_duration = clip(a_arr[13])
		mob_cost = clip(a_arr[14])
		mob_newcost = clip(a_arr[15])

		if ( mob_newcost != "" ) {
			mob_carrier_cost = mob_cost
			mob_cost = mob_newcost
		}

		# skip error recs
		if ( mob_rectype == "ERROR" ) {
			continue
		}

		# skip config validation recs
		if ( mob_rectype == "CONFIG" ) {
			continue
		}

		# skip invoice grand total rec
		if ( mob_rectype == "CHARGE_DESC_INFO" && mob_recclass == "TOTAL" ) {
			continue
		}

		supplier = mob_carrier

		carriercode = mobile_to_mob_carriercode_arr[mob_mobile]
		#print "rjs mc: mob_mobile=[" mob_mobile "]" "  carriercode=[" carriercode "}"
		if ( carriercode == "" ) {
			if ( carriercode_err_arr[mob_mobile] == "" ) {
				#print "ERROR: can't get carriercode for mob_mobile=[" mob_mobile "]" " ufid=[" mob_sundry "]" " carrier=[" mob_carrier "]"
				print "ERROR: can't get carriercode for mob_mobile=[" mob_mobile "]" " ufid=[" mob_sundry "]" " carrier=[" mob_carrier "]"
				carriercode_err_arr[mob_mobile] = "1"

				# default lower cased first char of carrier
				carriercode = tolower(substr(mob_carrier,1,1))
				mobile_to_mob_carriercode_arr[mob_mobile] = carriercode
			}
			#continue
		}

		Ctag = carriercode "|" mob_rectype "|" mob_recclass
		if ( mob_recclass == "X" ) {	# dummy cdr from config
			mob_cat = "X"
		}
		else {
			mob_cat = carriercode_chargeclasstype_to_chargecat_arr[Ctag]
		}
		if ( mob_cat == "" ) {
			mob_cat = "Mobile Misc"
			print "WARNING: default mobile charge category " mob_cat " set for Ctag=[" Ctag "]" "  supplier = [" supplier "]" "  mob_cost = [" mob_cost "]" "  mob_mobile = [" mob_mobile "]"
		}
		#print "mobcat: " mob_cat " set for Ctag=[" Ctag "]" "  supplier = [" supplier "]" "  mob_cost = [" mob_cost "]" "  mob_mobile = [" mob_mobile "]"

		rec_type = "MOBILE_" mob_rectype
		chg_cat = mob_cat
		if ( chg_cat == "X" )	# dummy categroy
			chg_count = 0
		else
			chg_count = 1
		chg_duration = mob_duration
		chg_cost = mob_cost

		#print "rec_type=[" rec_type "]  mob_recclass=[" mob_recclass "]"
		mobSERVTYPE = SERVTYPE
		mobSERVTYPEdesc = SERVTYPEdesc

		mobSID = substr(mob_mobile,1,4) "-" substr(mob_mobile,5)

		mobmanufacturer = mobile_to_manufacturer_arr[mob_mobile]
		mobmodel = mobile_to_model_arr[mob_mobile]

		#-----

		mobdirectoryID = mobile_to_directoryID_arr[mob_mobile]
		#print "mobile_to_directoryID_arr[" mob_mobile "] = [" mobile_to_directoryID_arr[mob_mobile] "]"

		eggrid = mobile_to_grid_arr[mob_mobile]
		if ( eggrid == "" ) {
			eggrid = recordno_to_eggrid_arr[mobdirectoryID]
			if ( Testing >= 2 && eggrid != "" )
				print "PERSONAL ASSIGNED recordno_to_eggrid_arr[" mobdirectoryID "] = [" recordno_to_eggrid_arr[mobdirectoryID] "]"
		}
		else {
			if ( Testing >= 2 && eggrid != "" )
				print "GROUP ASSIGNED mobile_to_grid_arr[" mob_mobile "] = [" mobile_to_grid_arr[mob_mobile] "]"
		}

		if ( eggrid == "" ) {
			print "WARNING: mobile [" mob_mobile "] not assigned to directoryID or groupID"
			eggrid = "UN_MOB"
			#continue
		}

		gggrid = grid_to_parentgroupid_arr[eggrid]
		#print "grid_to_parentgroupid_arr[" eggrid "] = [" grid_to_parentgroupid_arr[eggrid] "]"

		# rjs9
		#mobCENTRE = grid_to_centre_arr[eggrid]
		#mobPROJECT = grid_to_project_arr[eggrid]
		mobCENTRE = grid_to_centre_arr[gggrid]
		mobPROJECT = grid_to_project_arr[gggrid]

		# now set in get_mobileinfo()
		#extn = recordno_to_extn_arr[mobdirectoryID]
		##print "recordno_to_extn_arr[" mobdirectoryID "] = [" recordno_to_extn_arr[mobdirectoryID] "]"

		#print "MOBDETmobline = " mobline
		#printf("MOBDET: %s|%s|%s|%s|%s|%s|%s|%s|%s|%d|%0.4f\n", mobCENTRE, mobPROJECT, mobdirectoryID, mobSERVTYPE, mob_sundry, mobSID, mob_carrier, mob_cdate, mob_ctime, mob_duration, mround4(mob_cost))

		serviceprovider = mob_carrier
		#printf("   serviceprovider=%s\n", serviceprovider)

		######################

		# Testing
	        if ( Testing >= 2 && ! (gggrid == "ANN" || gggrid == "VLP") ) {
			#print "MOB TESTING... SKIP  gggrid = " gggrid "  eggrid = " eggrid
			continue
		}

		######################

		if ( mobSID <= 0 ) {
			print "WARNING: MOBILE SKIPPING mobSID = " mobSID
			continue
		}

		# set servicetype
		SERVTYPE = servtype
		SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]
		#print "SERVTYPE = " SERVTYPE "  SERVTYPEdesc = " SERVTYPEdesc

		if ( gggrid == "" )
			gggrid="XXX"

		if ( eggrid == "" )
			eggrid = "YYY"

		t21_GGRID = gggrid
		GGRID = t21_GGRID

		t21_EGRID = eggrid
		EGRID = t21_EGRID

		# get mobile info (name, extn and siteid)
		get_mobileinfo(0,SERVTYPE,mobSID)
		extn = t21_extn

		CENTRE = mobCENTRE
		PROJECT = mobPROJECT

		SID = mobSID

		#if ( SID != last_SID ) {
		#	print "Do mobdetfile eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  SID = " SID
		#}

		######################################
		# test if grids from summary data not in hierarchy
		if ( CENTRE == ""  || PROJECT == "" ) {
			print "WARNING: MOBILE SKIPPING BAD CENTRE/PROJECT" " eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  SID = " SID
			continue
		}

		# only doing thisCENTRE
		if ( thisCENTRE != "all" && gggrid != thisCENTRE )
			continue

		######################################
		if (SERVTYPE == "" || CENTRE == "" || PROJECT == "" || SID == "") {
			#print "WARNING: ERROR: MOBILE BAD HIERIDx = " HIERIDx
			print "WARNING: ERROR: MOBILE BAD"
			print "            SERVTYPE = " SERVTYPE
			print "             CENTRE = " CENTRE
			print "            PROJECT = " PROJECT
			print "                SID = " SID
			continue
		}


		# rjs9 - called also in ld_cde()
		set_HIERIDx(SERVTYPE,CENTRE,PROJECT,SID,supplier,rec_type,chg_cat)
		# rjs9
		CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] = EGRID

		# now set in get_mobileinfo
		#get_t21info(SERVTYPE,t21_EGRID,extn)

		######################################
		# exclude data
		if ( test_exclude(SERVTYPE, siteid, eggrid, extn) )
			continue

		######################################
		#printf("mobline=[%s]\n", mobline)

		#handle_mobile_change()

		# new mobile
		if ( SID != last_SID || eggrid != last_eggrid || gggrid != last_gggrid ) {
			printf("T21 new mobile: eggrid=[%s]  SID=[%s]  mobname=[%s]  extn=[%s] t21name=[%s]\n", eggrid, SID, mobname, extn, t21name)
			if ( !dot21verify ) {
				create_mobile_detail_file()
			}
			#nsids_arr["TOTAL" "|" SERVTYPE "|" CENTRE "|" PROJECT] += 1
		}

		date = fixdate(mob_cdate)
		endtime = mob_ctime

		if (mob_duration == "") 
			mob_duration = 0

		durhh = int(mob_duration / 3600)
		remd = mob_duration - (durhh * 3600)
		durmm = int(remd / 60)
		remd = remd - (durmm * 60)
		durss = remd
		mob_durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

		hh = substr(endtime,1,2)
		mm = substr(endtime,3,2)
		ss = substr(endtime,5,2)
		ctimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

		# set dialled/description info
		if ( mob_dialled == mob_destination )
			mob_destination = ""
		# remove dialled number from start of destination
		if ( mob_dialled != "" ) {
			#sub(mob_dialled,"",mob_destination)
			if ( substr(mob_destination,1,length(mob_dialled)) == mob_dialled )
				mob_destination = substr(mob_destination,length(mob_dialled)+1)
		}
		# dialno_desc = sprintf("%s", mob_dialled)
		# if ( mob_destination != "" )
		# 	dialno_desc = sprintf("%s %s", dialno_desc, mob_destination)

		dialledno = mob_dialled
		#printf("noddsuparr[%s] = %d\n", gggrid, noddsuparr[gggrid])
		if ( 1 || noddsuparr[gggrid] == 0 ) {	# group has NO digit suppression
			expdialledno = dialledno
		}
		else {
			# xx for last 2 digits in dialledno if length >= 0
			## supress for these callcategories only
			#if ( index("JALMESIOF", callcat) ) {
				dnl = length(dialledno)
				dnpreflen = dnl - 2
				if ( dnpreflen < 0 )
					dnpreflen = 0
				if ( dnl >= 0 ) {
					dnpref = substr(dialledno, 1, dnpreflen)
					expdialledno = sprintf("%sxx", dnpref)
				}
			#}
			#else {
			#	expdialledno = dialledno
			#}
		}

		if ( mdrrec_recno[mobile_fname] == "" )
			mdrrec_recno[mobile_fname] = 1
		else
			mdrrec_recno[mobile_fname] += 1
		mob_recno = mdrrec_recno[mobile_fname]

		if ( testmobdet == 1 || retroBDL != "1" ) {
			if ( !dot21verify ) {
				# skip dummy records (allows for 0 totals in summary data)
				if ( chg_cat != "X" && !dot21verify )
					spit_mdrrec_tomobilefile()
				else
					print "skipping dummy mdrrec"
			}
		}

		######################
		# add to upper totals
		#print "addup rec_type=[" rec_type "]"
		#print "  mob_recclass=[" mob_recclass "]"
		#print "  SERVTYPE=[" SERVTYPE "]"
		#print "  CENTRE=[" CENTRE "]"
		#print "  PROJECT=[" PROJECT "]"
		#print "  supplier=[" supplier "]"
		#print "  chg_cat=[" chg_cat "]"
		#print "  SID=[" SID "]"
		#print "  mob_cost = " mob_cost

		# add up mobile 
		add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID, supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

		# add up dummy mobile cost
		if ( SID == "0400-000000" ) {
			mobdummy_cost += chg_cost
		}

		##########################################
		# handle management reports for configured distribution lists
		if ( !dot21verify ) {
		    hsid = CENTRE "|" PROJECT "|" SID

		    # calls
		    if ( mob_rectype == "CDR" && chg_cat != "X") {
			new_expdialledno = expdialledno
			#if ( substr(new_expdialledno,1,8) == "Internet" )
			#	new_expdialledno = "Internet"
			#if ( substr(new_expdialledno,1,10) == "Blackberry" )
			#	new_expdialledno = "Blackberry"
			# remove nKb from diall no
			gsub(/[0-9]+[kK][bB]/,"", new_expdialledno)

			if ( chg_count > 0 && new_expdialledno != "" ) {
				# most frequently dialled numbers for sid
				sid_freq_numbers_count_arr[SERVTYPE "|" hsid "|" new_expdialledno] += chg_count

				# premium service for sid
				if ( is_premium_service(new_expdialledno, SERVTYPE) ) {
					sid_premserv_count_arr[SERVTYPE "|" hsid] += chg_count
					sid_premserv_duration_arr[SERVTYPE "|" hsid] += chg_duration
					sid_premserv_cost_arr[SERVTYPE "|" hsid] += chg_cost
				}

				# Intra-Organisational Call Distribution
				onnettype = is_onnet(new_expdialledno)
			}

			# all global roaming mobile users
			Ctag = carriercode "|" mob_rectype "|" mob_recclass
			if ( gloroam_class_arr[Ctag] != "" ) {
				gloroam_users_count_arr[hsid] += chg_count
				gloroam_users_duration_arr[hsid] += chg_duration
				gloroam_users_cost_arr[hsid] += chg_cost
			}

			distidlist = mng_egrid_distidlist_arr[EGRID]
			#print "  distidlist=[" distidlist "]"
			split(distidlist, distid_arr, "|")
			for ( i in distid_arr ) {
				DISTID = distid_arr[i]

				htag = DISTID "|" SERVTYPE
				hobj = hsid "|" mob_recno "|" mob_rectype "|" mob_cat "|" mob_recclass "|" date "|" ctimestr "|" mob_origin "|" new_expdialledno "|" mob_destination "|" chg_duration "|" chg_cost

				# most expensiove call
				hval = chg_cost
				hi_in( htag, 20, hi_call_by_cost_arr, hobj, hval )

				if ( chg_count > 0 && new_expdialledno != "" ) {
					# most frequently dialled numbers for distid
					dist_freq_numbers_count_arr[htag "|" new_expdialledno] += chg_count
					dist_freq_numbers_duration_arr[htag "|" new_expdialledno] += chg_duration
					dist_freq_numbers_cost_arr[htag "|" new_expdialledno] += chg_cost
					# Intra-Organisational Call Distribution
					if ( onnettype != "" ) {
						intracat = "ONNET Mobile to " onnettype
						Xtag = htag "|" intracat
						call_distribution_category_count_arr[Xtag] += chg_count
						call_distribution_category_duration_arr[Xtag] += chg_duration
						call_distribution_category_cost_arr[Xtag] += chg_cost
					}
				}

				# longest duration call
				hval = chg_duration
				hi_in( htag, 20, hi_call_by_duration_arr, hobj, hval )
				# call distribution by date
				#cddmm = substr(date,1,5)
				Xtag = htag "|" date
				call_distribution_date_count_arr[Xtag] += chg_count
				call_distribution_date_duration_arr[Xtag] += chg_duration
				call_distribution_date_cost_arr[Xtag] += chg_cost

				if ( is_weekday(date) ) {
					# call distribution by hour of day
					chh = substr(endtime,1,2)
					Xtag = htag "|" chh
					call_distribution_hour_count_arr[Xtag] += chg_count
					call_distribution_hour_duration_arr[Xtag] += chg_duration
					call_distribution_hour_cost_arr[Xtag] += chg_cost
					call_distribution_byhourdate_arr[SERVTYPE "|" date] = 1
				}

				# call distribution by call category
				Xtag = htag "|" chg_cat
				call_distribution_category_count_arr[Xtag] += chg_count
				call_distribution_category_duration_arr[Xtag] += chg_duration
				call_distribution_category_cost_arr[Xtag] += chg_cost
			}
		    }

		    # all internet users
		    if ( mob_rectype == "CHARGE_DESC_INFO" && mob_recclass == "INTERNET" ) {
			internet_users_arr[hsid] = 1
			internet_users_kbytes_arr[hsid] += mob_rate
			#print "mobdet: internet_users_kbytes_arr[" hsid "]=[" internet_users_kbytes_arr[hsid] "]"
			internet_users_cost_arr[hsid] += chg_cost
			#print "mobdet: internet_users_cost_arr[" hsid "]=[" internet_users_cost_arr[hsid] "]"
		    }

		}

		######################################
		last_gggrid = gggrid
		last_eggrid = eggrid
		last_extn = extn
		last_siteid = siteid
		last_SERVTYPE = SERVTYPE
		last_CENTRE = CENTRE
		last_PROJECT = PROJECT
		last_SID = SID
		last_directoryID = directoryID

	}
	close(mobcallsfile)

	###############################################
	# finish up
	print ""
	print "finished domobdetfile() - " mobcallsfile


}

# END Mobile Call Details
#####################################################
#####################################################
#----------------------------------------------------------


# T21ACCOUNTCODECALLS
#####################################################
#####################################################
#####################################################
#####################################################

##############################################################

function spit_cdarec_to_acccodedetfile()
{
	# append call record data to acccodedet file
	printf(",,,,,,,,,,,,") >>acccodedet_fname
	printf("%s,%s,%s,%s,%s,%s,%s,%0.2f\n", date, endtimestr, t21_extn, t21name, expdialledno, calldesc, durstr, mround2(callcost)) >> acccodedet_fname
}


################################################
################################################


function handle_acccodedet_change()
{
	# start new acccodedet
	if ( acccode != last_acccode || eggrid != last_eggrid || gggrid != last_gggrid ) {
		get_t21_upper_info(gggrid, eggrid)
		printf("T21 acccodedet_change(): eggrid=%s  acccode=%s  extn=%s  t21surname=%s  t21firstname=%s  t21name=%s\n", eggrid, acccode, extn, t21surname, t21firstname, t21name)
		if ( acccodedet_fname != "" ) {	# close previous acccodedet file
			if ( !dot21verify ) {
				close(acccodedet_fname)
			}
			acccodedet_fname = ""
		}
		acccodedet_fname = sprintf("topdat/%s/data/acccodedet%s/acccodedet_%s_%s_%s_%s.csv", monthdir, SERVTYPE, CENTRE, PROJECT, SERVTYPE, acccode)
		fname_to_SERVTYPECENTREPROJECT_arr[acccodedet_fname] = SERVTYPE "|" CENTRE "|" PROJECT
		get_ggname(gggrid)
		get_egname(eggrid)
		get_dirname(siteid,eggrid,extn)
		if ( dot21verify )
			return
		printf("    >>> acccodedet_fname = %s\n", acccodedet_fname)
		if ( (getline x < acccodedet_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/data/acccodedet%s", monthdir, SERVTYPE)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
			system(cmd)

			printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "Account Code Call Details", exbillperiod, sdate, edate, t21_CENTREdesc, t21_CENTRE, t21_SERVTYPEdesc, t21_SERVTYPE, t21_PROJECTdesc " / " t21_CCPdesc, t21_PROJECT, acccode, acccode_to_desc_arr[acccode]) >>acccodedet_fname

			printf("Date,End Time,Extn,Name,Dialled Number,Description,Duration,Total:Float\n") >>acccodedet_fname
		}
		else {
			printf("WARNING %d: acccodedet_fname = %s exists.\n", NR, acccodedet_fname)
		}

	}
}



################################################################
# process T21 account code detail calls file

function dot21acccodecallsfile(t21acccodecallsfile,servtype)
{
	printf("dot21acccodecallsfile(%s)  servtype=%s\n", t21acccodecallsfile, servtype)
	system("date")

	serviceprovider = t21serviceprovider
	printf("   serviceprovider=%s\n", serviceprovider)

	CENTRE = ""
	PROJECT = ""
	SID = ""

	SERVTYPE_fname = ""
	#CENTRE_fname = ""

	SERVTYPE = servtype
	SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]
	print "SERVTYPE = " SERVTYPE "  SERVTYPEdesc = " SERVTYPEdesc

	tmpt21acccodecallsfile = t21acccodecallsfile

	ggname = ""
	egname = ""
	egccp = ""
	t21name = ""

	last_gggrid = "First Time"
	last_eggrid = "First Time"
	last_acccode = -1
	last_extn = -1
	last_siteid = -1

	last_ggname = ""
	last_egname = ""
	last_egccp = ""
	last_t21surname = ""
	last_t21firstname = ""
	last_t21name = ""

	acccodedet_fname = ""

	###############################################
	# process each T21 call

	while ( (getline cdaline < tmpt21acccodecallsfile) > 0 ) {
		split(cdaline, cda_arr, ",")
		##printf("cdaline=%s\n", cdaline)

		gggrid = fixforfname(cda_arr[1])
		eggrid = fixforfname(cda_arr[2])

		######################

		# Testing
		######################
	        if ( Testing >= 2 && ! (gggrid == "ANN" || gggrid == "VLP") ) {
			#print "    TESTING... SKIPPING  gggrid = " gggrid "  eggrid = " eggrid
			continue
		}

		######################

		acccode = cda_arr[3]
		extn = cda_arr[3+1]
		date = cda_arr[4+1]
		endtime = cda_arr[5+1]
		siteid = cda_arr[6+1]
		otherno = cda_arr[7+1]
		direction = cda_arr[8+1]
		dialledno = cda_arr[9+1]
		callcat = cda_arr[10+1]
		calldesc = cda_arr[11+1]
		dur = cda_arr[12+1]
		callcost = cda_arr[13+1]

		supplier = "Fixed Line"
		rec_type = "FIXED_CDA"
		chg_cat = fixed_callcat_to_chg_cat[callcat]
		if ( chg_cat == "" )
			chg_cat = "Fixed Other"
		if ( chg_cat == "X" )	# dummy categroy
			chg_count = 0
		else
			chg_count = 1
		chg_duration = dur
		chg_cost = callcost

		if ( acccode <= 0 ) {
			print "WARNING: SKIPPING acccode = " acccode
			continue
		}

		if ( gggrid == "" )
			gggrid="XXX"

		if ( eggrid == "" )
			eggrid = "YYY"

		t21_GGRID = gggrid
		GGRID = t21_GGRID

		t21_EGRID = eggrid
		EGRID = t21_EGRID

		t21_SID = acccode
		SID = t21_SID

		t21_extn = extn

		SID = t21_SID
		CENTRE = grid_to_centre_arr[eggrid]
		PROJECT = grid_to_project_arr[eggrid]
		## rjs9
		#pargrid = grid_to_parentgroupid_arr[eggrid]
		#CENTRE = grid_to_centre_arr[pargrid]
		#PROJECT = grid_to_project_arr[pargrid]

		#if ( SID != last_SID ) {
		#	print "Do t21acccodecallsfile  eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  SID = " SID
		#}

		######################################
		# test if grids from summary data not in hierarchy
		if ( CENTRE == ""  || PROJECT == "" ) {
			print "WARNING:     SKIPPING BAD CENTRE/PROJECT" " eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  acccode = " acccode
			continue
		}

		# only doing thisCENTRE
		if ( thisCENTRE != "all" && gggrid != thisCENTRE )
			continue

		######################################
		if (SERVTYPE == "" || CENTRE == "" || PROJECT == "" || SID == "") {
			#print "WARNING: ERROR: BAD HIERIDx = " HIERIDx
			print "WARNING: ERROR: BAD"
			print "            servtype = " SERVTYPE
			print "             CENTRE = " CENTRE
			print "            project = " PROJECt
			print "                sid = " SID
			continue
		}

		# rjs9 - called also in ld_cde()
		set_HIERIDx(SERVTYPE,CENTRE,PROJECT,SID,supplier,rec_type,chg_cat)
		# rjs9
		CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] = EGRID


		get_t21info(1,t21_EGRID,t21_extn)

		######################################
		# exclude data
		if ( test_exclude(SERVTYPE, siteid, eggrid, acccode) )
			continue

		######################################
		#printf("cdaline=[%s]\n", cdaline)

		# set correct call category for internal call
		if ( direction == "in" && callcat == "J" ) {
			callcat = "A"
			calldesc = "Incoming Internal"
		}

		# force dialledno to other extn for Answering Internal KB
		if ( callcat == "A" )
			dialledno = otherno
		# force dialledno to other extn for originating Internal KB
		if ( callcat == "J" )
			dialledno = otherno

		#if ( callcat == "O" ) {	# Outgoing N/W (Tie not shown)
		#	continue
		#}
		#if ( callcat != "F" ) {	# FREE not shown
		#	continue
		#}

		date = fixdate(date)

		durhh = int(dur / 3600)
		remd = dur - (durhh * 3600)
		durmm = int(remd / 60)
		remd = remd - (durmm * 60)
		durss = remd
		durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

		hh = substr(endtime,1,2)
		mm = substr(endtime,3,2)
		ss = substr(endtime,5,2)
		endtimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

		#printf("noddsuparr[%s] = %d\n", gggrid, noddsuparr[gggrid])
		if ( dot21verify || noddsuparr[gggrid] == 0 ) {
			# group has no digit suppression
			expdialledno = dialledno
		}
		else {			# xx for last 2 digits in dialledno if length >= 0
			# supress for these callcategories only
			if ( index("JALMESIOF", callcat) ) {
				dnl = length(dialledno)
				dnpreflen = dnl - 2
				if ( dnpreflen < 0 )
					dnpreflen = 0
				if ( dnl >= 0 ) {
					dnpref = substr(dialledno, 1, dnpreflen)
					expdialledno = sprintf("%sxx", dnpref)
				}
			}
			else {
				expdialledno = dialledno
			}
		}

		handle_acccodedet_change()

		# skip dummy records (allows for 0 totals in summary data)
		if ( callcat != "X" && !dot21verify )
			spit_cdarec_to_acccodedetfile()

		######################
		# add to upper totals
		if ( callcat != "X" ) { # ignore account code config recs
			# account code - extn totals
			add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID ":" extn, supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

			# All extn totals
			add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID ":" "All", supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

			# store list of extns for each account code
			acccode_extn_arr[SID  "|" extn] = 1
		}

		######################################
		last_gggrid = gggrid
		last_eggrid = eggrid
		last_extn = extn
		last_acccode = acccode
		last_siteid = siteid

		last_SID = SID
		last_ggname = ggname
		last_egname = egname
		last_egccp = egccp
		last_t21surname = t21surname
		last_t21firstname = t21firstname
		last_t21name = t21name

	}
	close(tmpt21acccodecallsfile)

	###############################################
	# finish up

	print ""
	print "finished dot21acccodecallsfile() - " tmpt21acccodecallsfile

}


# END T21ACCOUNTCODECALLS
#####################################################
#####################################################
#----------------------------------------------------------



# T21OVERHEADS
#####################################################
#####################################################
#####################################################
#####################################################

function spit_header_to_ovhextnfile()
{
	#print "spit_header_to_ovhextnfile() - " ovhextn_fname
	if ( SERVTYPE == 2 )
		reportdesc = "Equipment Details"
	if ( SERVTYPE == 3 )
		reportdesc = "Miscellaneous Details"
	if ( SERVTYPE == 4 )
		reportdesc = "Overhead Details"
	printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,Code,Item,Reference,Description,FromDate,ToDate,Total Cost:Float\n", reportdesc, exbillperiod, sdate, edate, t21_CENTREdesc, t21_CENTRE, t21_SERVTYPEdesc, t21_SERVTYPE, t21_PROJECTdesc " / " t21_CCPdesc, t21_PROJECT, extn, t21name, t21site, t21location) >>ovhextn_fname
}

function spit_odrrec_to_ovhextnfile()
{
	# append call record data to overheads extn file
	printf(",,,,,,,,,,,,,,%s,%s,%s,%s,%s,%s,%0.2f\n", ovhcode, ovhitem, ovhreference, ovhdescription, assosdate, assoedate, mround2(ovhcost)) >> ovhextn_fname
}


################################################
################################################

function handle_ovhextn_change()
{
	# start new extn
	if ( extn != last_extn || eggrid != last_eggrid || gggrid != last_gggrid || SERVTYPE != last_SERVTYPE ) {
		get_t21_upper_info(gggrid, eggrid)
		printf("T21 ovhextn_change(): eggrid=%s  extn=%s  t21surname=%s  t21firstname=%s  t21name=%s\n", eggrid, extn, t21surname, t21firstname, t21name)
		if ( retroBDL != "1" ) {
			if ( ovhextn_fname != "" ) {	# close previous extn file
				if ( !dot21verify ) {
					close(ovhextn_fname)
				}
				ovhextn_fname = ""
			}
		}
		ovhextn_fname = sprintf("topdat/%s/data/extn%s/extn_%s_%s_%s_%s.csv", monthdir, SERVTYPE, CENTRE, PROJECT, SERVTYPE, extn)
		fname_to_SERVTYPECENTREPROJECT_arr[ovhextn_fname] = SERVTYPE "|" CENTRE "|" PROJECT
		get_ggname(gggrid)
		get_egname(eggrid)
		get_dirname(siteid,eggrid,extn)

		#nsids_arr["TOTAL" "|" SERVTYPE "|" CENTRE "|" PROJECT] += 1

		if ( dot21verify )
			return
		if ( retroBDL == "1" )
			return
		printf("    >>> ovhextn_fname = %s\n", ovhextn_fname)
		if ( (getline x < ovhextn_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/data/extn%s", monthdir, SERVTYPE)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
			system(cmd)

			spit_header_to_ovhextnfile()
		}
		else {
			printf("WARNING %d: ovhextn_fname = %s exists.\n", NR, ovhextn_fname)
		}

	}

}


################################################################
# process T21 detail overheads file

function dot21ovhfile(t21ovhfile, Eservtype, Mservtype, Oservtype)
{
	printf("dot21ovhfile(%s)  Eservtype=%s  Mservtype=%s  Oservtype=%s \n", t21ovhfile, Eservtype, Mservtype, Oservtype)
	system("date")

	serviceprovider = t21serviceprovider
	printf("   serviceprovider=%s\n", serviceprovider)

	CENTRE = ""
	PROJECT = ""
	SID = ""

	SERVTYPE_fname = ""
	#CENTRE_fname = ""

	tmpt21ovhfile = t21ovhfile

	ggname = ""
	egname = ""
	egccp = ""
	t21name = ""

	last_gggrid = "First Time"
	last_eggrid = "First Time"
	last_extn = -1
	last_siteid = -1

	last_ggname = ""
	last_egname = ""
	last_egccp = ""
	last_t21surname = ""
	last_t21firstname = ""
	last_t21name = ""
	last_SERVTYPE = ""

	ovhextn_fname = ""

	###############################################
	# process each T21 overhead

	while ( (getline ovhline < tmpt21ovhfile) > 0 ) {
		split(ovhline, ovh_arr, "|")
		##printf("ovhline=%s\n", ovhline)

		# ggrid|egrid|extn|siteid|ovhtype|ovhorder|ovhcode|ovhitem|ovhreference|ovhdescription|assosdate|assoedate|ovhcost|
		# 20001|CP001013|7801|101|E|10|STANDARD_CHARGE|Standard Charge|STANDARD|Standard Charge|01/09/2003||1.44|

		gggrid = fixforfname(ovh_arr[1])
		eggrid = fixforfname(ovh_arr[2])

		######################

		# Testing
	        if ( Testing >= 2 && ! (gggrid == "ANN" || gggrid == "VLP") ) {
			#print "OVH TESTING... SKIP  gggrid = " gggrid "  eggrid = " eggrid
			continue
		}

		######################

		extn = ovh_arr[3]
		siteid = ovh_arr[4]
		ovhtype = ovh_arr[5]
		ovhorder = ovh_arr[6]
		ovhcode = ovh_arr[7]
		ovhitem = ovh_arr[8]
		ovhreference = ovh_arr[9]
		ovhdescription = ovh_arr[10]
		assosdate = ovh_arr[11]
		assoedate = ovh_arr[12]
		ovhcost = ovh_arr[13]

		supplier = "Overheads"
		rec_type = "OVHEXTN_CHARGE_DESC"
		chg_cat = ovhcode
		if ( chg_cat == "X" )	# dummy categroy
			chg_count = 0
		else
			chg_count = 1
		chg_duration = 0
		chg_cost = ovhcost

		#if ( extn <= 0 ) {
		#	print "WARNING: OVH SKIPPING extn = " extn
		#	continue
		#}

		# set servicetype from ovhtype and params
		if ( ovhtype == "E" )
			servtype = Eservtype
		if ( ovhtype == "M" )
			servtype = Mservtype
		if ( ovhtype == "O" )
			servtype = Oservtype

		SERVTYPE = servtype
		SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]
		#print "SERVTYPE = " SERVTYPE "  SERVTYPEdesc = " SERVTYPEdesc

		if ( gggrid == "" )
			gggrid="XXX"

		if ( eggrid == "" )
			eggrid = "YYY"

		t21_GGRID = gggrid
		GGRID = t21_GGRID

		t21_EGRID = eggrid
		EGRID = t21_EGRID

		t21_SID = extn
		SID = t21_SID

		CENTRE = grid_to_centre_arr[eggrid]
		PROJECT = grid_to_project_arr[eggrid]
		## rjs9
		#pargrid = grid_to_parentgroupid_arr[eggrid]
		#CENTRE = grid_to_centre_arr[pargrid]
		#PROJECT = grid_to_project_arr[pargrid]

		#if ( SID != last_SID ) {
		#	print "Do t21ovhfile eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  Extn = " extn
		#	print "       ovhtype=" ovhtype "  SERVTYPE=" SERVTYPE
		#}

		######################################
		# test if grids from summary data not in hierarchy
		if ( CENTRE == ""  || PROJECT == "" ) {
			print "WARNING: OVH SKIPPING BAD CENTRE/PROJECT" " eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  Extn = " extn
			continue
		}

		# only doing thisCENTRE
		if ( thisCENTRE != "all" && gggrid != thisCENTRE )
			continue

		######################################
		if (SERVTYPE == "" || CENTRE == "" || PROJECT == "" || SID == "") {
			#print "WARNING: ERROR: OVH BAD HIERIDx = " HIERIDx
			print "WARNING: ERROR: OVH BAD"
			print "            servtype = " servtype
			print "             CENTRE = " centre
			print "            project = " project
			print "                sid = " sid
			continue
		}

		# rjs9 - called also in ld_cde()
		set_HIERIDx(SERVTYPE,CENTRE,PROJECT,SID,supplier,rec_type,chg_cat)
		# rjs9
		CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] = EGRID


		get_t21info(SERVTYPE,t21_EGRID,extn)

		######################################
		# exclude data
		if ( test_exclude(SERVTYPE, siteid, eggrid, extn) )
			continue

		######################################
		#printf("ovhline=[%s]\n", ovhline)

		assosdate = fixdate(assosdate)
		assoedate = fixdate(assoedate)

		handle_ovhextn_change()

		if ( retroBDL != "1" ) {
			if ( !dot21verify )
				spit_odrrec_to_ovhextnfile()
		}

		######################
		# add to upper totals
		add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID, supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

		######################################
		last_gggrid = gggrid
		last_eggrid = eggrid
		last_extn = extn
		last_siteid = siteid

		last_ggname = ggname
		last_egname = egname
		last_egccp = egccp
		last_t21surname = t21surname
		last_t21firstname = t21firstname
		last_t21name = t21name
		last_SERVTYPE = SERVTYPE
		last_SID = SID

	}
	close(tmpt21ovhfile)

	###############################################
	# finish up

	print ""
	print "finished dot21ovhfile() - " tmpt21ovhcallsfile

}


# END T21COVERHEADS
#####################################################
#####################################################
#----------------------------------------------------------




# T21CALLS
#####################################################
#####################################################
#####################################################
#####################################################

##############################################################

function spit_cdrrec_to_extnfile()
{ 
	# append call record data to extn file
	printf(",,,,,,,,,,,,,,") >>extn_fname
	printf("%s,%s,%s,%s,%s,%0.2f\n", date, endtimestr, expdialledno, calldesc, durstr, mround2(callcost)) >> extn_fname
}


################################################
################################################


function handle_extn_change()
{
	# start new extn
	if ( extn != last_extn || eggrid != last_eggrid || gggrid != last_gggrid ) {
		get_t21_upper_info(gggrid, eggrid)
		printf("T21 extn_change(): eggrid=%s  extn=%s  t21surname=%s  t21firstname=%s  t21name=%s\n", eggrid, extn, t21surname, t21firstname, t21name)
		if ( retroBDL != "1" ) {
			if ( extn_fname != "" ) {	# close previous extn file
				if ( !dot21verify ) {
					close(extn_fname)
				}
				extn_fname = ""
			}
		}
		extn_fname = sprintf("topdat/%s/data/extn%s/extn_%s_%s_%s_%s.csv", monthdir, SERVTYPE, CENTRE, PROJECT, SERVTYPE, extn)
		fname_to_SERVTYPECENTREPROJECT_arr[extn_fname] = SERVTYPE "|" CENTRE "|" PROJECT
		get_ggname(gggrid)
		get_egname(eggrid)
		get_dirname(siteid,eggrid,extn)

		#nsids_arr["TOTAL" "|" SERVTYPE "|" CENTRE "|" PROJECT] += 1

		if ( dot21verify )
			return
		if ( retroBDL == "1" )
			return
		printf("    >>> extn_fname = %s\n", extn_fname)
		if ( (getline x < extn_fname) < 0 ) {
			# create file and csv header
			newdir = sprintf("topdat/%s/data/extn%s", monthdir, SERVTYPE)
			cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p %s", newdir, newdir)
			system(cmd)

			printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,", "Extension Call Details", exbillperiod, sdate, edate, t21_CENTREdesc, t21_CENTRE, t21_SERVTYPEdesc, t21_SERVTYPE, t21_PROJECTdesc " / " t21_CCPdesc, t21_PROJECT, extn, t21name, t21site, t21location) >>extn_fname

			printf("Date,End Time,Dialled Number,Description,Duration,Total:Float\n") >>extn_fname
		}
		else {
			printf("WARNING %d: extn_fname = %s exists.\n", NR, extn_fname)
		}

	}


}


################################################################
# process T21 detail calls file

function dot21callsfile(t21callsfile,servtype)
{
	printf("dot21callsfile(%s)  servtype=%s\n", t21callsfile, servtype)
	system("date")

	serviceprovider = t21serviceprovider
	printf("   serviceprovider=%s\n", serviceprovider)

	CENTRE = ""
	PROJECT = ""
	SID = ""

	SERVTYPE_fname = ""
	#CENTRE_fname = ""

	SERVTYPE = servtype
	SERVTYPEdesc = SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]
	print "SERVTYPE = " SERVTYPE "  SERVTYPEdesc = " SERVTYPEdesc

	tmpt21callsfile = t21callsfile

	ggname = ""
	egname = ""
	egccp = ""
	t21name = ""

	last_gggrid = "First Time"
	last_eggrid = "First Time"
	last_extn = -1
	last_siteid = -1

	last_ggname = ""
	last_egname = ""
	last_egccp = ""
	last_t21surname = ""
	last_t21firstname = ""
	last_t21name = ""

	extn_fname = ""

	###############################################
	# process each T21 call

	while ( (getline cdrline < tmpt21callsfile) > 0 ) {
		split(cdrline, cdr_arr, ",")
		##printf("cdrline=%s\n", cdrline)

		#NEG,2672SSA,1,12124,02/06/1996,124820, ,indial,536,0.0

		gggrid = fixforfname(cdr_arr[1])
		eggrid = fixforfname(cdr_arr[2])

		######################

		# Testing
		######################
	        if ( Testing >= 2 && ! (gggrid == "ANN" || gggrid == "VLP") ) {
			#print "    TESTING... SKIPPING  gggrid = " gggrid "  eggrid = " eggrid
			continue
		}

		######################

		extn = cdr_arr[3]
		date = cdr_arr[4]
		endtime = cdr_arr[5]
		siteid = cdr_arr[6]
		otherno = cdr_arr[7]
		direction = cdr_arr[8]
		dialledno = cdr_arr[9]
		callcat = cdr_arr[10]
		calldesc = cdr_arr[11]
		dur = cdr_arr[12]
		callcost = cdr_arr[13]
                accesscode = trim(cdr_arr[14])

                # outgoing calls with account codes
                if ( direction == "out" && accesscode != "" ) {
                        calldesc = "ACODE " accesscode ":" callcost " " calldesc

			callcost = 0.0  # 0 cost - now in Account Code Charges
                        #continue       # skip
                }

		if ( callcat == "X" )	# dummy categroy
			chg_count = 0
		else
			chg_count = 1

		supplier = "Fixed Line"
		rec_type = "FIXED_CDR"
		chg_cat = fixed_callcat_to_chg_cat[callcat]
		if ( chg_cat == "" )
			chg_cat = "Fixed Other"
		chg_duration = dur
		chg_cost = callcost

		if ( extn <= 0 ) {
			print "WARNING: SKIPPING extn = " extn
			continue
		}

		if ( gggrid == "" )
			gggrid="XXX"

		if ( eggrid == "" )
			eggrid = "YYY"

		t21_GGRID = gggrid
		GGRID = t21_GGRID

		t21_EGRID = eggrid
		EGRID = t21_EGRID

		t21_SID = extn
		SID = t21_SID

		CENTRE = grid_to_centre_arr[eggrid]
		PROJECT = grid_to_project_arr[eggrid]
		## rjs9
		#pargrid = grid_to_parentgroupid_arr[eggrid]
		#CENTRE = grid_to_centre_arr[pargrid]
		#PROJECT = grid_to_project_arr[pargrid]

		if ( SID != last_SID ) {
			print "Do t21callsfile  eggrid = " eggrid "  pargrid = " pargrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  SID = " SID
		}

		######################################
		# test if grids from summary data not in hierarchy
		if ( CENTRE == ""  || PROJECT == "" ) {
			print "WARNING:     SKIPPING BAD CENTRE/PROJECT" " eggrid = " eggrid "  CENTRE = " CENTRE "  PROJECT = "  PROJECT "  Extn = " extn
			continue
		}

		# only doing thisCENTRE
		if ( thisCENTRE != "all" && gggrid != thisCENTRE )
			continue

		######################################
		if (SERVTYPE == "" || CENTRE == "" || PROJECT == "" || SID == "") {
			#print "WARNING: ERROR: BAD HIERIDx = " HIERIDx
			print "WARNING: ERROR: BAD"
			print "            servtype = " servtype
			print "             CENTRE = " centre
			print "            project = " project
			print "                sid = " sid
			continue
		}

		# rjs9 - called also in ld_cde()
		set_HIERIDx(SERVTYPE,CENTRE,PROJECT,SID,supplier,rec_type,chg_cat)
		# rjs9
		CENTREPROJECTSID_to_EGRID_arr[CENTRE "|" PROJECT "|" SID] = EGRID


		get_t21info(SERVTYPE,t21_EGRID,extn)

		######################################
		# exclude data
		if ( test_exclude(SERVTYPE, siteid, eggrid, extn) )
			continue

		######################################
		#printf("cdrline=[%s]\n", cdrline)

		# set correct call category for internal call
		if ( direction == "in" && callcat == "J" ) {
			callcat = "A"
			calldesc = "Incoming Internal"
		}

		# force dialledno to other extn for Answering Internal KB
		if ( callcat == "A" )
			dialledno = otherno
		# force dialledno to other extn for originating Internal KB
		if ( callcat == "J" )
			dialledno = otherno

		#if ( callcat == "O" ) {	# Outgoing N/W (Tie not shown)
		#	continue
		#}
		#if ( callcat != "F" ) {	# FREE not shown
		#	continue
		#}

		date = fixdate(date)

		durhh = int(dur / 3600)
		remd = dur - (durhh * 3600)
		durmm = int(remd / 60)
		remd = remd - (durmm * 60)
		durss = remd
		durstr = sprintf("%03d:%02d:%02d", durhh, durmm, durss)

		hh = substr(endtime,1,2)
		mm = substr(endtime,3,2)
		ss = substr(endtime,5,2)
		endtimestr = sprintf("%2s:%2s:%2s",hh, mm, ss)

		# remove routetrunk strippdd and ovrcars from dialledno
		origdialledno = dialledno
		if ( direction == "out" && dialledno != "" )
			dialledno = rtdialno(siteid,otherno,dialledno)

		#printf("noddsuparr[%s] = %d\n", gggrid, noddsuparr[gggrid])
		if ( dot21verify || noddsuparr[gggrid] == 0 ) {
			# group has no digit suppression
			expdialledno = dialledno
		}
		else {			# xx for last 2 digits in dialledno if length >= 0
			# supress for these callcategories only
			if ( index("JALMESIOF", callcat) ) {
				dnl = length(dialledno)
				dnpreflen = dnl - 2
				if ( dnpreflen < 0 )
					dnpreflen = 0
				if ( dnl >= 0 ) {
					dnpref = substr(dialledno, 1, dnpreflen)
					expdialledno = sprintf("%sxx", dnpref)
				}
			}
			else {
				expdialledno = dialledno
			}
		}

		handle_extn_change()

		if ( retroBDL != "1" ) {
			if ( !dot21verify ) {
				# skip dummy records (allows for 0 totals in summary data)
				if ( callcat != "X" && !dot21verify )
					spit_cdrrec_to_extnfile()
			}
		}

		######################
		# add to upper totals
		add_totals("TOTAL", SERVTYPE, CENTRE, PROJECT, SID, supplier, rec_type, chg_cat, chg_count, chg_duration, chg_cost)

		##########################################
		# handle management reports for configured distribution lists

		if ( !dot21verify ) {
		    hsid = CENTRE "|" PROJECT "|" SID
		    new_expdialledno = expdialledno
		    if ( chg_count > 0 && new_expdialledno != "" ) {
			if ( callcat == "L" || callcat == "M" || callcat == "E" || callcat == "S" || callcat == "I" || callcat == "F" ) {
				# most frequently dialled numbers for sid
				sid_freq_numbers_count_arr[SERVTYPE "|" hsid "|" new_expdialledno] += chg_count

				# premium service for sid
				if ( is_premium_service(new_expdialledno, SERVTYPE) ) {
					sid_premserv_count_arr[SERVTYPE "|" hsid] += chg_count
					sid_premserv_duration_arr[SERVTYPE "|" hsid] += chg_duration
					sid_premserv_cost_arr[SERVTYPE "|" hsid] += chg_cost
				}
				# Intra-Organisational Call Distribution
				onnettype = is_onnet(new_expdialledno)
			}
			if ( callcat == "O" || callcat == "J" ) {
				# Intra-Organisational Call Distribution
				onnettype = is_onnet(new_expdialledno)
			}
		    }

		    distidlist = mng_egrid_distidlist_arr[EGRID]
		    #print "  distidlist=[" distidlist "]"
		    split(distidlist, distid_arr, "|")
		    for ( i in distid_arr ) {
			DISTID = distid_arr[i]

			htag = DISTID "|" SERVTYPE
			hobj = hsid "|" siteid "|" otherno "|" direction "|" date "|" endtimestr "|" expdialledno "|" callcat "|" calldesc "|" chg_duration "|" chg_cost

			if ( callcat == "L" || callcat == "M" || callcat == "E" || callcat == "S" || callcat == "I" || callcat == "F" ) {
				# most expensiove call
				hval = chg_cost
				hi_in( htag, 20, hi_call_by_cost_arr, hobj, hval )

				if ( chg_count > 0 && new_expdialledno != "" ) {
					# most frequently dialled numbers for distid
					dist_freq_numbers_count_arr[htag "|" new_expdialledno] += chg_count
					dist_freq_numbers_duration_arr[htag "|" new_expdialledno] += chg_duration
					dist_freq_numbers_cost_arr[htag "|" new_expdialledno] += chg_cost
				}

				# call distribution by date
				#cddmm = substr(date,1,5)
				Xtag = htag "|" date
				call_distribution_date_count_arr[Xtag] += chg_count
				call_distribution_date_duration_arr[Xtag] += chg_duration
				call_distribution_date_cost_arr[Xtag] += chg_cost

				if ( is_weekday(date) ) {
					# call distribution by hour of day
					chh = substr(endtime,1,2)
					Xtag = htag "|" chh
					call_distribution_hour_count_arr[Xtag] += chg_count
					call_distribution_hour_duration_arr[Xtag] += chg_duration
					call_distribution_hour_cost_arr[Xtag] += chg_cost
					call_distribution_byhourdate_arr[SERVTYPE "|" date] = 1
				}

				# call distribution by call category
				Xtag = htag "|" chg_cat
				call_distribution_category_count_arr[Xtag] += chg_count
				call_distribution_category_duration_arr[Xtag] += chg_duration
				call_distribution_category_cost_arr[Xtag] += chg_cost

			}
			# Intra-Organisational Call Distribution
			if ( onnettype != "" ) {
				intracat = "Extension to " onnettype
				Xtag = htag "|" intracat
				call_distribution_category_count_arr[Xtag] += chg_count
				call_distribution_category_duration_arr[Xtag] += chg_duration
				call_distribution_category_cost_arr[Xtag] += chg_cost
			}

			# longest duration call
			hval = chg_duration
			hi_in( htag, 20, hi_call_by_duration_arr, hobj, hval )
		    }
		}

		######################################
		last_gggrid = gggrid
		last_eggrid = eggrid
		last_extn = extn
		last_siteid = siteid

		last_SID = SID
		last_ggname = ggname
		last_egname = egname
		last_egccp = egccp
		last_t21surname = t21surname
		last_t21firstname = t21firstname
		last_t21name = t21name

	}
	close(tmpt21callsfile)

	###############################################
	# finish up

	print ""
	print "finished dot21callsfile() - " tmpt21callsfile

}


# END T21CALLS
#####################################################
#####################################################
#----------------------------------------------------------


#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
#----------------------------------------------------------
# main


BEGIN {
	if ( logdir == "" )
		logdir = "./"
	Testing = 2
	testmobdet = 0
	LinkUserHTMLindex = 0

	# set bill period vars
	MMYYYY_to_billperiod(MMYYYY,"_")

	YYYYMM = substr(MMYYYY,3,4) substr(MMYYYY,1,2)

	print "Begin wb2 - dot21verify=" dot21verify "  thisCENTRE=" thisCENTRE
#rjs9
        print "          -             RESTcde = " RESTcde
        print "          -       platinumBATCH = " platinumBATCH
        print "          - switchboardcallcost = " switchboardcallcost
        print "          -   voicemailcallcost = " voicemailcallcost
 	print "          -              MMYYYY = " MMYYYY
 	print "          -          billperiod = " billperiod
 	print "          -              YYYYMM = " YYYYMM

        if ( thisDIVID == "" ) {
		thisDIVID = "all"
	}

        if ( platinumBATCH == "" ) {
                platinumBATCH = "all"
        }

        inp_platinumBATCH = platinumBATCH
        #rjs9batchtag = billperiod "_" inp_platinumBATCH "_" thisDIVID
        #batchtag = billperiod "_" "all" "_" thisCENTRE
        #batchtag = "all" "_" thisCENTRE
        batchtag = thisCENTRE

	system("date")

	"date '+%d/%m/%Y'" | getline cur_dd_mm_yyyy

	#------------------------
	t21serviceprovider = "TELMAX21"
        t21_supplier = "VICTRACK"
        t21_sundry = ""
        t21_elementid = ""
#rjs9

	#------------------------
	sdate = fixdate(sdate)
	edate = fixdate(edate)

	days_in_period = 0 + substr(edate,1,2)

	monthdir = monthtag
	printf("monthdir = %s\n", monthdir)


#rjs9
	if ( ! dot21verify ) {
		#------------------------
		# load platinv file
		ld_platinv(platinvfile)

		print "platinumBATCH = " platinumBATCH
		if ( platinumBATCH != "all" ) {
			# Division and/or sundry specified
			if (thisDIVID == "all" && length(platinumBATCH) <= 6) {
				# get platinum BATCH for this sundry
				sundryBATCH = platinumBATCH
				platinumBATCH = ""
				print "  Get Platinum Batch for Specified Sundry = " sundryBATCH

				for (cstr in parent_sundry_to_platinv_batch_arr)
				{
					split(cstr, cstr_arr, "|")
					parent = cstr_arr[1]
					sundry = cstr_arr[2]
					elementid = cstr_arr[3]

A
					if ( sundry != sundryBATCH )
						continue

					# Division (ShipTo) & sundry specified
					if ( thisDIVID != "all" && thisDIVID != parent )
						continue

					foundpB = parent_sundry_to_platinv_batch_arr[parent "|" sundry "|" elementid]
					print "  found ... parent_sundry_to_platinv_batch_arr[" parent "|" sundry "|" elementid "] = " parent_sundry_to_platinv_batch_arr[parent "|" sundry "|" elementid]
					if ( platinumBATCH != "" && platinumBATCH != foundpB ) {
						print "FATAL ERROR: Non Unique Platinum BATCH for Specified Sundry = " sundryBATCH
						exit 1
					}
					platinumBATCH = foundpB
				
				}
				if ( platinumBATCH == "" ) {
					print "FATAL ERROR: Can't get Platinum BATCH for Specified Sundry = " sundryBATCH
					exit 1
				}
			}

			# invoicenumber specified
			if (length(platinumBATCH) >= 7 && length(platinumBATCH) <= 10) {
				# get platinum BATCH for this invoicenumber
				invoicenumberBATCH = platinumBATCH
				platinumBATCH = ""
				print "  Get Platinum Batch for Specified Invoicenumber =  " invoicenumberBATCH
				for (cstr in parent_invoicenumber_to_platinv_batch_arr)
				{
					split(cstr, cstr_arr, "|")
					parent = cstr_arr[1]
					invoiceno = cstr_arr[2]
					if ( invoiceno != invoicenumberBATCH )
						continue
					foundpB = parent_invoicenumber_to_platinv_batch_arr[parent "|" invoiceno]
					print "  found ... parent_invoicenumber_to_platinv_batch_arr[" parent "|" invoiceno "] = " parent_invoicenumber_to_platinv_batch_arr[parent "|" invoiceno]
					if ( platinumBATCH != "" && platinumBATCH != foundpB ) {
						print "FATAL ERROR: Non Unique Platinum BATCH for Specified Invoicenumber = " invoicenumberBATCH
						exit 1
					}
					platinumBATCH = foundpB
				
				}
				if ( platinumBATCH == "" ) {
					print "FATAL ERROR: Can't get Platinum BATCH for Specified Invoicenumber = " invoicenumberBATCH
					exit 1
				}
			}

		}
	}

#rjs9
#	this_divgroup = exwebconf_parent_to_cdgroup_arr[DIVID]
#	if ( this_divgroup != "" )	# belongs to a cdgroup
#		act_targdir = "topdat" "/" billperiod "/" platinumBATCH "_" this_divgroup
#	else
#		act_targdir = "topdat" "/" billperiod "/" platinumBATCH "_" thisDIVID

# rjs9
#	if ( ! dot21verify ) {
#		lokfile = act_targdir ".lok"
#		if ( (getline x < lokfile) < 0 ) {
#			print "Running" > lokfile
#		}
#		else {
#			print "FATAL ERROR: already running lokfile = " lokfile
#			exit 1
#		}
#	}

#rjs9-
#	# make symlink if batch run with invoice number or div/sundry
#	if ( platinumBATCH != inp_platinumBATCH ) {
#		dirloc = "topdat" "/" monthtag
#		this_divgroup = exwebconf_parent_to_cdgroup_arr[thisDIVID]
#		if ( this_divgroup != "" ) {	# belongs to a cdgroup
#			relact_targdir = platinumBATCH "_" this_divgroup
#			symlink = inp_platinumBATCH "_" this_divgroup
#		}
#		else {
#			relact_targdir = platinumBATCH "_" thisDIVID
#			symlink = inp_platinumBATCH "_" thisDIVID
#		}
#		print "Make symlink  dirloc=" dirloc "  relact_targdir=" relact_targdir "  symlink=" symlink
#		cmd = "cd " dirloc ";" "ln -s \"" relact_targdir "\" \"" symlink "\""
#		system(cmd)
#	}
#-rjs9

	if ( platinumBATCH == "all" ) {
		print "INFO: Running for all platinum batch filenames"
	}
	else {
		print "INFO: Running for platinum batch filename = " platinumBATCH
	}
#rjs9



	#------------------------
        # load account code conf data
        ld_acccodeconf(acccodeconffile)

	#------------------------
	# load mobile conf data
	ld_mobconf(mobconffile)

	#------------------------
	# load chargecat data
	ld_chargecat(chargecatfile)

	#------------------------
	# load t21 route trunk data
	ld_t21rt(t21rtfile)

	#------------------------
	# load t21 extranges data
	ld_t21extranges(t21extrangesfile)

	#------------------------
	# load t21 groups data
	ld_t21groups4(t21groups4file)

	#------------------------
	# load t21 directory data
	ld_t21dircsvfile(t21dircsvfile)

	grid_to_parentgroupid_arr["XXX"] = "ZZZ"
	grid_to_grtype_arr["XXX"] = "G"
	grid_to_grname1_arr["XXX"] = "XXX Group Not Found"
	grid_to_grname2_arr["XXX"] = "XXX Group Not Found"
	grid_to_grname3_arr["XXX"] = "XXX Group Not Found"
	grid_to_ccp_arr["XXX"] = "XXXXX.XXXXX"
	grid_to_centre_arr["XXX"] = "XXXXX"
	grid_to_project_arr["XXX"] = "XXXXX"
	childcount_arr["XXX"] = 1

	grid_to_parentgroupid_arr["YYY"] = "XXX"
	grid_to_grtype_arr["YYY"] = "E"
	grid_to_grname1_arr["YYY"] = "YYY Group Not Found"
	grid_to_grname2_arr["YYY"] = "YYY Group Not Found"
	grid_to_grname3_arr["YYY"] = "YYY Group Not Found"
	grid_to_ccp_arr["YYY"] = "YYYYY.YYYYY"
	grid_to_centre_arr["YYY"] = "YYYYY"
	grid_to_project_arr["YYY"] = "YYYYY"

	#------------------------
	# load t21 Web Billing Distribution Lists
	ld_t21WBDL(t21WBDLfile)

	#------------------------
	# load t21 Web Billing Distribution site/grid/extn Eclusion List
	ld_t21wbdexclude(t21wbdexcludefile)

	#------------------------------------------------
	system("date")

	totsprefix = "ex2_"
	if ( dot21verify ) {
		totsprefix = "ex2a_"
	}
	if ( retroBDL == "1" ) {
		totsprefix = "ex2r_"
	}
	totalscsvfile = totsprefix "totcsv_" thisCENTRE
	totalsrepfile = totsprefix "totrep_" thisCENTRE ".txt"

	cmd=sprintf("rm -f %s %s*.csv", totalsrepfile, totalscsvfile)
	print "removeing: cmd=" cmd
	system(cmd)

	printf("Bilmax21 Web Billing Extraction-2%s (%s)  Totals For %s\r\n\r\n", dot21verify ? "a (VERIFY)" : ((retroBDL == "1") ? "r (Retrospective)" : ""), thisCENTRE, exbillperiod) >>totalsrepfile
        #rjs9 printf("VICTRACK Web Billing3 (%s) %s Totals For %s\r\n\r\n", dot21verify ? "a (VERIFY)" : "", batchtag, exbillperiod) >>totalsrepfile
        if ( !dot21verify ) {
                printf("Invoice Batch: %s\r\n", platinumBATCH) >>totalsrepfile;
                printf("Switchboard Call Cost: %s\r\n", switchboardcallcost) >>totalsrepfile;
                printf("\r\n") >>totalsrepfile
                printf("CDE Data\r\n") >>totalsrepfile
                printf("\r\n") >>totalsrepfile
        }
	close(totalsrepfile)

	if ( !dot21verify ) {
		printf("Totals Report\r\n") >>totalsrepfile
		printf("=============\r\n") >>totalsrepfile
		printf("\r\n") >>totalsrepfile
	}
	else {
		printf("Verify Data Totals Report\r\n") >>totalsrepfile
		printf("=========================\r\n") >>totalsrepfile
		printf("\r\n") >>totalsrepfile
	}
	close(totalsrepfile)

	####################################################################
	## generate t21 verification report and csv
	#system("date")
	if ( dot21verify ) {
#rjs9
		print ""
		print "Doing T21 Verification Report/CSV and Back Billing"
		print ""
		domobdetfile(mobcallssfile,10)
                #dot21acccodecallsfile(t21acccodecallsfile,5)
		#dot21ovhfile(t21ovhfile,2,3,-1)
		dot21callsfile(t21callsfile,1)
		exit 0

	}

	#-----------------------------------------------------
	system("date")
	HIERIDx = ""
#rjs9
	if ( retroBDL != "1" )
		HIERIDxfile = "HIERIDx_" batchtag ".lst"
	else
		HIERIDxfile = "HIERIDx_" batchtag ".rlst"
        #system("rm -f HIERIDx_" batchtag ".lst")
        system("rm -f sundrys_" batchtag ".uniq")
        system("rm -f DEPTID_" batchtag ".lst")


	####################################################################

	#-----------------------------------------------------------------
	# load exwebconffile - get groups with NO dialled digit suppression
	ld_exwebconf(exwebconffile)

	#-----------------------------------------------------------------
#rjs9
	# tbsdata database
	ld_tbsdata_customer(tbsCustomerfile)
	ld_tbsdata_servicetype(tbsServiceTypefile)
	ld_tbsdata_element(tbsElementfile)
	ld_tbsdata_supplier(tbsSupplierfile)

# rjs9
	## to translate VRT seid for drill down
	#ld_seidtranslate("indata/" monthtag "/seidtranslate.csv")
	#------------------------

	# person service list data
	ld_tbsdata_personservicelist(tbsPersonServiceListfile)
	#------------------------

	got_cde_data = 0

	# now data comes from tbsdata (see getcde scripts)
#rjs9
	ld_cde(cdefile)

	if ( got_cde_data != 1 ) {
		print "FATAL ERROR: NO CDE data loaded (error in CDE or NO matching invoice data)"
		exit 1
	}
#-rjs9

	#-----------------------------------------------------------------
	if ( !dot21verify ) {
		# create egrid distid list array
		create_egrid_distidlist()

		print ""
		system("date")
		print "standard/admin egrid distid lists"
		for (egrid in egrid_distidlist_arr) {
			print "egrid_distidlist_arr[" egrid "]=[" egrid_distidlist_arr[egrid] "]"
		}

		print ""
		system("date")

		print "management egrid distid lists"
		for (egrid in mng_egrid_distidlist_arr) {
			print "mng_egrid_distidlist_arr[" egrid "]=[" mng_egrid_distidlist_arr[egrid] "]"
		}
	}

	#-----------------------------------------------------------------
	if ( !dot21verify ) {
		# create virtual user distribution list entries
		if ( retroBDL != "1" )
			create_virtual_user_dist_lists()
	}

	####################################################################
	# create billperiod/data
	top_data_dir = sprintf("topdat/%s/data", monthdir)
	cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", top_data_dir, top_data_dir)
	system(cmd)

	####################################################################
	# clear releasedate and remove any old data for retrospective lists

	if ( !dot21verify ) {
	    if ( retroBDL == "1" ) {
		print "BMRETRO: Retrospective Generation/Regeneration of Distribution List(s)"
		print "BMRETRO: "
		for ( DISTID in distid_to_distiddesc_arr ) {
			DISTIDdesc = distid_to_distiddesc_arr[DISTID]
			t21name = distid_to_t21name_arr[DISTID]
			t21userid = distid_to_userid_arr[DISTID]
			print "BMRETRO: DISTID: " DISTID " " DISTIDdesc " for " t21name " (" t21userid ")"
			# clear releasedate
			spit_header_to_wbttopfile()
			spit_USER_to_wbttopfile()
			# remove data
			cmd=sprintf("rm -fr topdat/%s/%s", billperiod, DISTID)
			printf("Running [%s]\n", cmd)
			system(cmd)
		}
	    }
	}

	#-----------------------------------------------------
	# setup service type desc array

	SERVTYPE_to_SERVTYPEdesc_arr["All"] = "All Service Types"

	st = 10
	SERVTYPE_to_GLcode_arr[st] = 0
	SERVTYPE_to_SERVTYPEdesc_arr[st] = "Mobile Calls and Charges"
	if ( SERVTYPE_to_GLcode_arr[st] != 0 )
		SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"
	mobdummy_cost = 0

        st = 5
        SERVTYPE_to_GLcode_arr[st]  = 0
        SERVTYPE_to_SERVTYPEdesc_arr[st] = "Account Code Charges"
        if ( SERVTYPE_to_GLcode_arr[st] != 0 )
                SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"

	st = 4
	SERVTYPE_to_GLcode_arr[st]  = 0
	SERVTYPE_to_SERVTYPEdesc_arr[st] = "Overhead Charges"
	if ( SERVTYPE_to_GLcode_arr[st] != 0 )
		SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"

	st = 3
	SERVTYPE_to_GLcode_arr[st]  = 0
	SERVTYPE_to_SERVTYPEdesc_arr[st] = "Miscellaneous Charges"
	if ( SERVTYPE_to_GLcode_arr[st] != 0 )
		SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"

	st = 2
	SERVTYPE_to_GLcode_arr[st]  = 0
	SERVTYPE_to_SERVTYPEdesc_arr[st] = "Equipment and Service Charges"
	#SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] "EXTNCNT"
	if ( SERVTYPE_to_GLcode_arr[st] != 0 )
		SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"

	st = 1
	SERVTYPE_to_GLcode_arr[st]  = 0
	SERVTYPE_to_SERVTYPEdesc_arr[1] = "Fixed Line Call Charges"
	if ( SERVTYPE_to_GLcode_arr[st] != 0 )
		SERVTYPE_to_SERVTYPEdesc_arr[st] = SERVTYPE_to_SERVTYPEdesc_arr[st] " (" SERVTYPE_to_GLcode_arr[st] ")"

	#-----------------------------------------------------
	# tims fixed call categories
	fixed_callcat_to_chg_cat["J"] = "Fixed Originating Internal"
	fixed_callcat_to_chg_cat["A"] = "Fixed Answering Internal"
	fixed_callcat_to_chg_cat["L"] = "Fixed To Local"
	fixed_callcat_to_chg_cat["M"] = "Fixed To Mobile"
	fixed_callcat_to_chg_cat["E"] = "Fixed To Information"
	fixed_callcat_to_chg_cat["S"] = "Fixed To STD"
	fixed_callcat_to_chg_cat["I"] = "Fixed To IDD"
	fixed_callcat_to_chg_cat["N"] = "Fixed Incoming Network"
	fixed_callcat_to_chg_cat["P"] = "Fixed Incoming Public"
	fixed_callcat_to_chg_cat["O"] = "Fixed Outgoing Network"
	fixed_callcat_to_chg_cat["F"] = "Fixed Free"
	fixed_callcat_to_chg_cat["X"] = "Fixed From Directory"

#rjs9here upto here (see 3.a)
	#-----------------------------------------------------
	#-----------------------------------------------------
	# process MOBILE calls file
	# Testing
	#domobdetfile(mobcallsfile, 10)

	#-----------------------------------------------------
	# process T21 access/account code calls file
	dot21acccodecallsfile(t21acccodecallsfile,5)

	#-----------------------------------------------------
	# process T21 overheads file E/M/O
	#dot21ovhfile(t21ovhfile, 2, 3, 4)

	#-----------------------------------------------------
	# process T21 calls file
	dot21callsfile(t21callsfile, 1)

	if ( !dot21verify ) {
	    #-----------------------------------------------------
	    # process management highest usage frequently dialled number lists
	    # create freq dial numbers for each distid
	    for ( hdistdialtag in dist_freq_numbers_count_arr ) {
		dialcnt = dist_freq_numbers_count_arr[hdistdialtag]
		split(hdistdialtag, a_arr, "|")
		DISTID = a_arr[1]
		SERVTYPE = a_arr[2]
		dialledno = a_arr[3]

		htag = DISTID "|" SERVTYPE
		hobj = dialledno
		hval = dialcnt
		hi_in( htag, 20, hi_dist_freqdial_arr, hobj, hval )
	    }

	    # create list of servtype, freq dials
	    # to speed up next loop
	    for ( Htag in hi_dist_freqdial_arr ) {
		split(Htag, a_arr, "|")
		distid = a_arr[1]
		dist_servtype = a_arr[2]
		hi_idx = a_arr[3]
		split(hi_dist_freqdial_arr[Htag], a_arr, "|")
		dist_dialcnt = a_arr[1]
		dist_dialno = a_arr[2]
		hi_freq_dial[dist_servtype "|" dist_dialno] = 1
	    }

	    # get sid with highest usage for each distid's freq dial numbers
	    print "get sid for freq dial"
	    system("date")
	    for ( Stag in sid_freq_numbers_count_arr ) {
		split(Stag, a_arr, "|")
		servtype = a_arr[1]
		sid_centre = a_arr[2]
		sid_project = a_arr[3]
		sid = a_arr[4]
		dialno = a_arr[5]

		# speed up
		if ( hi_freq_dial[servtype "|" dialno] != 1 )
			continue

		dialcnt = sid_freq_numbers_count_arr[Stag]

		# rjs9 centre|project has multiple egrids
		#egrid = CENTREPROJECT_to_EGRID_arr[sid_centre "|" sid_project]
		egrid = CENTREPROJECTSID_to_EGRID_arr[sid_centre "|" sid_projectn "|" sid]

		for ( Htag in hi_dist_freqdial_arr ) {
			split(Htag, a_arr, "|")
			distid = a_arr[1]
			dist_servtype = a_arr[2]
			hi_idx = a_arr[3]

			# test if egrid for sid belongs distid freq list
			if ( distid_allegrid_arr[distid "|" egrid] != 1 )
				continue

			split(hi_dist_freqdial_arr[Htag], a_arr, "|")
			dist_dialcnt = a_arr[1]
			dist_dialno = a_arr[2]
			dist_sid_centre = a_arr[3]
			dist_sid_project = a_arr[4]
			dist_sid = a_arr[5]
			dist_sid_dialcnt = a_arr[6]

			if ( servtype == dist_servtype && ("x" dialno) == ("x" dist_dialno) ) {
				if ( dialcnt > dist_sid_dialcnt ) {
					hi_dist_freqdial_arr[Htag] = dist_dialcnt "|" dist_dialno "|" sid_centre "|" sid_project "|" sid "|" dialcnt

				}
			}
		}
	    }
	    system("date")
	}

	#-----------------------------------------------------
	#-----------------------------------------------------
	print "get processing order from sorted HIERIDx file"
	print "and generate distid totals"
	system("date")

	close(HIERIDxsortcmd)
	HIERIDxorder = 0
	while ( (getline HIERIDx < HIERIDxfile) > 0 ) {
		HIERIDxorder_to_HIERIDx_arr[++HIERIDxorder] = HIERIDx
		#print HIERIDxorder "  HIERIDx = " HIERIDx
		if ( !dot21verify ) {
			# generate distid totals
			add_distid_totals()
		}
	}
	close(HIERIDxfile)
	HIERIDxmaxorder = HIERIDxorder
	print "HIERIDxmaxorder = " HIERIDxmaxorder


	#-----------------------------------------------------
	print "generate upper data files"
	system("date")

	#last_HIERIDxDUPcount = ""
	last_HIERIDx = ""
	last_serviceprovider = ""
	last_SERVTYPE = ""
	last_CENTRE = ""
	last_PROJECT = ""
	last_GGRID = ""
	last_EGRID = ""
	last_SID = ""

	disp_project = ""
	addstar = ""
	projectfilter = ""
	ccpdesc = ""

	#########################

	printf("\n")
	for ( HIERIDxorder = 1; HIERIDxorder <= HIERIDxmaxorder; ++HIERIDxorder ) {
		HIERIDx = HIERIDxorder_to_HIERIDx_arr[HIERIDxorder]

		print ""
		print "DO HIERIDx = " HIERIDx

		get_HIERIDx_info(HIERIDx, 2)

                # do this to set t21_extn, before call to get_t21info()
                if ( SERVTYPE == 10 )
                        get_mobileinfo(1,SERVTYPE,t21_SID)
                else
                if ( SERVTYPE == 5 ) {
                        t21_acccode = t21_SID
                        t21_extn = "All"
                }
                else {
                        t21_extn = t21_SID
                }

                get_t21info(SERVTYPE,t21_EGRID,t21_extn)

		if ( HIERIDx == last_HIERIDx ) {	# skip duplicates
			print "WARNING: duplicate HIERIDx: " HIERIDx
			continue
		}


		################

		print_totals(SERVTYPE, CENTRE, PROJECT, SID)

		if ( dot21verify && retroBDL != "1" ) {
		    # do extension totals to back billing
		    ###################################
		    # new bb1
		    # - includes all service types
		    # newbb1 BBBBBB

                    # except account codes
                    if ( SERVTYPE != "5" ) {
			# test CENTRE/PROJECT changed
			if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT ) {
				# - spit invoice GST CENTRE totals
				if ( newlast_inv_grid != "" ) {
					spit_newbb1_inv_totGST()
				}
			}
			if ( !done_newbb1_egid_sid_servtype_arr[EGRID "|" SID "|" SERVTYPE] ) {
				# - spit sid total
				spit_newbb1(EGRID, SID, SERVTYPE)
				done_newbb1_egid_sid_servtype_arr[EGRID "|" SID "|" SERVTYPE] = 1
			}
		    }
		}


		##################
		
		# do project totals csv data and totals report
		if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT ) {
			if ( last_PROJECT != "" ) {
				spit_totals_rep_project()
				spit_totals_csvdata()
				print_totals(last_SERVTYPE, last_CENTRE, last_PROJECT, "All")
			}
		}

		# do totals report for centre 
		if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE ) {
			if ( last_CENTRE != "" ) {
				spit_totals_rep_centre()
				print_totals(last_SERVTYPE, last_CENTRE, "All", "All")
			}
		}

		# do totals report for servicetype 
		if ( last_SERVTYPE != SERVTYPE ) {
			if ( last_SERVTYPE != "" ) {
				spit_totals_rep_servtype()
				print_totals(last_SERVTYPE, last_CENTRE, "All", "All")
			}
			if ( SERVTYPE != "" ) {
				printf("\r\n", SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]) >>totalsrepfile
				printf("Service Type: %s\r\n", SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]) >>totalsrepfile
				printf("======================================================\r\n", SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]) >>totalsrepfile
				printf("\r\n\r\n", SERVTYPE_to_SERVTYPEdesc_arr[SERVTYPE]) >>totalsrepfile
			}
		}

		################

		#for ( cstr in donetotal_arr ) {
		#	delete donetotals_arr[Xtotid]
		#}

		##############################

		if ( !dot21verify ) {

		    print ""
		    print "process configured distribution lists"
		    distidlist = egrid_distidlist_arr[EGRID]
		    print "  distidlist=[" distidlist "]"
		    split(distidlist, distid_arr, "|")
		    for ( i in distid_arr ) {
			DISTID = distid_arr[i]

			#DISTIDdesc = distid_to_distiddesc_arr[DISTID]
			#t21_dist_name = distid_to_t21name_arr[DISTID]
			#t21userid = distid_to_userid_arr[DISTID]
			#if ( t21userid == "" )
			#	t21userid = distid_to_directoryID_arr[DISTID]

			print "  HANDLE DISTID = " DISTID
			print "      GGRID = " GGRID "  EGRID = " EGRID
			print "      CHILDCOUNT = " CHILDCOUNT

			DISP_PROJECT = PROJECT
			addstar = ""

			# check if EGRID is in distid's distgrid list and
			# is 1 of many egrids(projects) in centre then addstar
 			if ( distid_egrid_arr[DISTID "|" EGRID] == 1 ) {
				if ( is_CENTRE_dot_PROJECT_arr[EGRID] ) {
					# more than 1 project in centre
					if ( CHILDCOUNT > 1 ) {
						addstar = "*"
						print "        ADDSTAR"
						DISP_PROJECT = PROJECT addstar
					}
				}
			}

			print "    PROJECT=" PROJECT "  DISP_PROJECT=" DISP_PROJECT

			# sid totals to distidfile
			if ( done_distidfile_totals_arr[DISTID "|" SERVTYPE "|" CENTRE "|" PROJECT "|" SID] == "" ) {
				distidfile_totals()
				done_distidfile_totals_arr[DISTID "|" SERVTYPE "|" CENTRE "|" PROJECT "|" SID] = 1
			}

			if ( distid_to_wbd_type_arr[DISTID] == "MANAGEMENT" ) {
				# do highest usage for distid
				if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT || last_SID != SID) {
					# do highest user
					do_highest_usage(DISTID,SERVTYPE,CENTRE,PROJECT,EGRID,SID)
				}
				done_DISTID_totals_arr[DISTID] = "1"
				continue
			}

			handle_DISTID_datafile()

			#handle_CENTRE_datafile()

			handle_SERVTYPE_datafile()

			if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT ) {
				detail_fnames_to_fnamelist(SERVTYPE "|" CENTRE "|" PROJECT)
			}

			done_DISTID_totals_arr[DISTID] = "1"
		    }
		    print ""
		}

		if ( !dot21verify ) {
		    print ""
		    print "process management distribution lists"
		    distidlist = mng_egrid_distidlist_arr[EGRID]
		    print "  distidlist=[" distidlist "]"
		    split(distidlist, distid_arr, "|")
		    for ( i in distid_arr ) {
			DISTID = distid_arr[i]

			#DISTIDdesc = distid_to_distiddesc_arr[DISTID]
			#t21_dist_name = distid_to_t21name_arr[DISTID]
			#t21userid = distid_to_userid_arr[DISTID]
			#if ( t21userid == "" )
			#	t21userid = distid_to_directoryID_arr[DISTID]

			print "  HANDLE MANANGEMENT DISTID = " DISTID
			print "      GGRID = " GGRID "  EGRID = " EGRID
			print "      CHILDCOUNT = " CHILDCOUNT

			DISP_PROJECT = PROJECT
			addstar = ""

			# check if EGRID is in distid's distgrid list and
			# is 1 of many egrids(projects) in centre then addstar
 			if ( distid_egrid_arr[DISTID "|" EGRID] == 1 ) {
				if ( is_CENTRE_dot_PROJECT_arr[EGRID] ) {
					# more than 1 project in centre
					if ( CHILDCOUNT > 1 ) {
						addstar = "*"
						print "        ADDSTAR"
						DISP_PROJECT = PROJECT addstar
					}
				}
			}

			print "    PROJECT=" PROJECT "  DISP_PROJECT=" DISP_PROJECT
			# do highest usage for distid
			if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT || last_SID != SID) {
				# do highest user
				do_highest_usage(DISTID,SERVTYPE,CENTRE,PROJECT,EGRID,SID)
			}
			done_DISTID_totals_arr[DISTID] = "1"
		    }
		    print ""
		}


		#-------------------#

		if ( !dot21verify ) {
		    if ( retroBDL != "1" ) {
			print ""
			print "process virtual distribution list"
			Stag = EGRID "|" SERVTYPE "|" SID
			Vdistid = personal_egrid_servtype_SID_to_distid_arr[Stag]
			print "  personal_egrid_servtype_SID_to_distid_arr[" Stag "] = [" personal_egrid_servtype_SID_to_distid_arr[Stag] "]"
			if ( Vdistid != "" ) {
				DISTID = Vdistid
				#DISTIDdesc = distid_to_distiddesc_arr[DISTID]
				#t21_dist_name = distid_to_t21name_arr[DISTID]
				#t21userid = distid_to_userid_arr[DISTID]
				#if ( t21userid == "" )
				#	t21userid = distid_to_directoryID_arr[DISTID]

				print "  HANDLE PERSONAL DISTID = " DISTID
				print "      GGRID = " GGRID "  EGRID = " EGRID
				print "      CHILDCOUNT = " CHILDCOUNT

				addstar = "*"
				DISP_PROJECT = PROJECT addstar

				handle_DISTID_datafile()

				#handle_CENTRE_datafile()

				handle_SERVTYPE_datafile()

				if ( last_SERVTYPE != SERVTYPE || last_CENTRE != CENTRE || last_PROJECT != PROJECT ) {
					detail_fnames_to_fnamelist(SERVTYPE "|" CENTRE "|" PROJECT)
				}

				done_DISTID_totals_arr[DISTID] = "1"
			}

			print ""
		    }
		}



		################

		#last_HIERIDxDUPcount = HIERIDxDUPcount
		last_serviceprovider = serviceprovider
		last_SERVTYPE = SERVTYPE
		last_CENTRE = CENTRE
		last_PROJECT = PROJECT
		last_GGRID = GGRID
		last_EGRID = EGRID
		last_SID = SID
		last_HIERIDx = HIERIDx

	}

	system("date")

	#########################
	# do last_ totals

	if ( dot21verify ) {
		# newbb1 BBBBBB
		# - spit invoice GST CENTRE totals
		if ( newlast_inv_grid != "" ) {
			spit_newbb1_inv_totGST()
		}
	}

	if ( last_PROJECT != "" ) {
		spit_totals_rep_project()
		spit_totals_csvdata()
		print_totals(last_SERVTYPE, last_CENTRE, last_PROJECT, "All")
	}
	if ( last_CENTRE != "" ) {
		spit_totals_rep_centre()
		print_totals(last_SERVTYPE, last_CENTRE, "All", "All")
	}
	if ( last_SERVTYPE != "" ) {
		spit_totals_rep_servtype()
		print_totals(last_SERVTYPE, last_CENTRE, "All", "All")
	}

	spit_totals_rep_all()
	print_totals("All", "All", "All", "All")

	#-----------------------------------------------------
	# create network average csv
	if ( !dot21verify && retroBDL != 1 ) {
		avgcsv = "networkaverage.csv"
		# remove old
		networkavg_fname = sprintf("topdat/%s/data/%s", monthdir, avgcsv)
		cmd=sprintf("rm -f %s", networkavg_fname)
		system(cmd)
		# create header
		printf("%s,%s,%s,%s,servicetypeDESC,servicetypeID,ServiceidCount:Int,totcount:Int,totduration:Int,totcost:Float,avgcost:Float\n", "Network Average", exbillperiod, "SDATE", "EDATE") >networkavg_fname
		close(networkavg_fname)
		# for each servicetypeid
		for ( servtype in SERVTYPE_to_SERVTYPEdesc_arr ) {
			if ( servtype == "All" )
				continue
			servtypedesc = SERVTYPE_to_SERVTYPEdesc_arr[servtype]
			sidcount = nsids_arr["TOTAL|" servtype]
			totXtag = "TOTAL|10|All|All|All|All|All"
			totcost = totalcost_arr[totXtag]
			totcount = totalcount_arr[totXtag]
			avg_cost = totcost
			if ( servtype == "10" ) {
			    totduration = totalduration_arr[totXtag "_MOBILE_CDR"]
			    if ( mobdummy_cost > 0 ) {
				sidcount = sidcount - 1
				avg_cost = avg_cost - mobdummy_cost
				print "AVGDUMMY 0: mobdummy_cost=[" mobdummy_cost "]" "  avg_cost=[" avg_cost "]" "  sidcount=[" sidcount "]"
				totcost = avg_cost
			    }
			}
			else {
			    totduration = totalduration_arr[totXtag]
			}
			
			if ( sidcount > 0 )
			    avgcost = sprintf("%0.2f", mround2(avg_cost / sidcount))
			else
			    avgcost = 0

			print "AVG: "
			print "AVG: servtypedesc=[" servtypedesc "]"
			print "AVG: servtype=[" servtype "]"
			print "AVG: sidcount=[" sidcount "]"
			print "AVG: totXtag=[" totXtag "]"
			print "AVG: totcount=[" totcount "]"
			print "AVG: totduration=[" totduration "]"
			print "AVG: totcost=[" totcost "]"
			print "AVG: avgcost=[" avgcost "]"

			printf(",,,,%s,%s,%d,%d,%d,%0.2f,%0.2f\n", servtypedesc, servtype, sidcount, totcount, totduration, mround2(totcost), mround2(avgcost)) >>networkavg_fname
		}
		close(networkavg_fname)
	}

	#-----------------------------------------------------
	#-----------------------------------------------------
	# create management distribution list data files

	if ( !dot21verify ) {
	    print "create management dist lists data files"
	    system("date")
	    for ( DISTID in distid_to_distiddesc_arr ) {
		DISTIDdesc = distid_to_distiddesc_arr[DISTID]
		t21name = distid_to_t21name_arr[DISTID]
		t21userid = distid_to_userid_arr[DISTID]
		if ( t21userid == "" )
			t21userid = distid_to_directoryID_arr[DISTID]
		t21wbd_method = distid_to_wbd_method_arr[DISTID]
		t21wbd_type = distid_to_wbd_type_arr[DISTID]

		# create management dist list data
		if ( distid_to_wbd_type_arr[DISTID] == "MANAGEMENT" ) {
			print "Create data for Management DISTID=[" DISTID "]" "  t21name=[" t21name "]" "  t21userid=[" t21userid "]" "  t21wbd_type=[" t21wbd_type "]"
			# vmng
			fdistid = DISTID
			if ( virtual_management_distid_arr[DISTID] != "" ) {
				# virtual managment list
				real_distid = virtual_management_distid_arr[DISTID]
				real_distiddir = sprintf("topdat/%s/%s", monthdir, real_distid)
				# vmng
				#cmd = sprintf("[ ! -d \"%s\" ] && mkdir -p \"%s\"", real_distiddir, real_distiddir)
				#system(cmd)
				## sym link to virtual managment distid dir
				#cmd = sprintf("cd \"topdat/%s\"; [ ! -L \"%s\" ] && ln -s \"%s\" \"%s\"", monthdir, DISTID, real_distid, DISTID)
				#print "mngsym: [" cmd "]"
				#system(cmd)
				fdistid = real_distid
			}

			print "generate data files from hi_sid_by_cost_arr"
			create_hi_sid_csv("011","Highest Fixed Line Users by Cost", 20, hi_sid_by_cost_arr,DISTID,fdistid,1,"Call Count")
			create_hi_sid_csv("012","Highest Mobile Users by Cost", 20, hi_sid_by_cost_arr,DISTID,fdistid,10,"Call Count")


			print "generate data files from hi_sid_mobile_messaging_by_count_arr"
			create_hi_sid_csv("052","Highest SMS Users by Number Sent", 20, hi_sid_mobile_messaging_by_count_arr,DISTID,fdistid,10,"SMS Count")


			print "generate data files from hi_sid_mobile_messaging_by_cost_arr"
			create_hi_sid_csv("062","Highest SMS Users by Cost", 20, hi_sid_mobile_messaging_by_cost_arr,DISTID,fdistid,10,"SMS Count")


			print "generate data files from hi_call_by_cost_arr"
			create_hi_call_csv("021","Most Expensive Fixed Line Calls", 20, hi_call_by_cost_arr,DISTID,fdistid,1)
			create_hi_call_csv("022","Most Expensive Mobile Calls", 20, hi_call_by_cost_arr,DISTID,fdistid,10)

			print "generate data files from hi_call_by_duration_arr"
			create_hi_call_csv("031","Longest Duration Fixed Line Calls", 20, hi_call_by_duration_arr,DISTID,fdistid,1)
			create_hi_call_csv("032","Longest Duration Mobile Calls", 20, hi_call_by_duration_arr,DISTID,fdistid,10)


			print "generate data files from hi_dist_freqdial_arr"
			create_hi_freqdial_csv("041","Most Frequently Dialled Numbers from Fixed Line Phones", 20, hi_dist_freqdial_arr,DISTID,fdistid,1)
			create_hi_freqdial_csv("042","Most Frequently Dialled Numbers from Mobile Phones", 20, hi_dist_freqdial_arr,DISTID,fdistid,10)


			print "generate data files from hi_gloroam_users_by_cost_arr"
			create_hi_sid_csv("072","All Global Roaming Mobile Users", 2000, hi_gloroam_users_by_cost_arr,DISTID,fdistid,10,"Call Count")


			print "generate data files from hi_internet_users_by_cost_arr"
			create_hi_sid_csv("132","All Internet Users", 2000, hi_internet_users_by_cost_arr,DISTID,fdistid,10,"KBytes")


			print "generate data files from hi_premserv_users_by_cost_arr"
			create_hi_sid_csv("121","Highest 19XXXX... Service Fixed Line Users By Cost", 20, hi_premserv_users_by_cost_arr,DISTID,fdistid,1,"Call Count")
			create_hi_sid_csv("122","Highest Premium 19XXXXxx Service Mobile Users By Cost", 20, hi_premserv_users_by_cost_arr,DISTID,fdistid,10,"Call Count")

			print "generate data files for call distribution by date"
			create_call_distr_by_date_csv("081","Fixed Line Call Distribution By Date", DISTID,fdistid,1)
			create_call_distr_by_date_csv("082","Mobile Call Distribution By Date", DISTID,fdistid,10)

			print "generate data files for call distribution by hour of day"
			create_call_distr_by_hour_csv("091","Fixed Line Call Distribution By Hour of the Day", DISTID,fdistid,1)
			create_call_distr_by_hour_csv("092","Mobile Call Distribution By Hour of the Day", DISTID,fdistid,10)

			print "generate data files for Intra-Organisational call distribution"
			create_call_distr_by_category_csv("101","Intra-Organisational Call Distribution", DISTID,fdistid,1)
			create_call_distr_by_category_csv("102","Intra-Organisational Call Distribution", DISTID,fdistid,10)

			print "generate data files for call distribution by category"
			create_call_distr_by_category_csv("111","Fixed Line Call Distribution By Call Type", DISTID,fdistid,1)
			create_call_distr_by_category_csv("112","Mobile Call Distribution By Call Type", DISTID,fdistid,10)


			done_DISTID_totals_arr[DISTID] = "1"
		}
	    }
	    print ""
	    system("date")
	}
			
	#-----------------------------------------------------
	#-----------------------------------------------------
	# finish up processing off distribution lists

	if ( !dot21verify )
		finish_proc_dist_lists()


	#-----------------------------------------------------
	#-----------------------------------------------------
	print ""
	system("date")
	for ( Xtag in totalcost_arr ) {
		print "DEBUGTOTALS: totalcost_arr[" Xtag "] = " totalcost_arr[Xtag] "  count=" totalcount_arr[Xtag]
	}
	print ""

	#-----------------------------------------------------
	#-----------------------------------------------------
	print ""
	print "highest usage debug..."
	system("date")
	print "hi_sid_by_cost_arr"
	for ( Htag in hi_sid_by_cost_arr ) {
		print "DEBUGHU: hi_sid_by_cost_arr[" Htag "]  = " hi_sid_by_cost_arr[Htag] 
	}
	print ""
	print "hi_sid_mobile_messaging_by_count_arr"
	for ( Htag in hi_sid_mobile_messaging_by_count_arr ) {
		print "DEBUGHU: hi_sid_mobile_messaging_by_count_arr[" Htag "]  = " hi_sid_mobile_messaging_by_count_arr[Htag] 
	}
	print ""
	print "hi_sid_mobile_messaging_by_cost_arr"
	for ( Htag in hi_sid_mobile_messaging_by_cost_arr ) {
		print "DEBUGHU: hi_sid_mobile_messaging_by_cost_arr[" Htag "]  = " hi_sid_mobile_messaging_by_cost_arr[Htag] 
	}
	print ""
	print "hi_call_by_duration_arr"
	for ( Htag in hi_call_by_duration_arr ) {
		print "DEBUGHU: hi_call_by_duration_arr[" Htag "]  = " hi_call_by_duration_arr[Htag] 
	}
	print ""
	print "hi_call_by_cost_arr"
	for ( Htag in hi_call_by_cost_arr ) {
		print "DEBUGHU: hi_call_by_cost_arr[" Htag "]  = " hi_call_by_cost_arr[Htag] 
	}
	print ""
	print "hi_dist_freqdial_arr"
	for ( Htag in hi_dist_freqdial_arr ) {
		print "DEBUGHU: hi_dist_freqdial_arr[" Htag "]  = " hi_dist_freqdial_arr[Htag] 
	}
	print ""
	print "sid_freq_numbers_count_arr"
	for ( Htag in sid_freq_numbers_count_arr ) {
		print "DEBUGHU: sid_freq_numbers_count_arr[" Htag "]  = " sid_freq_numbers_count_arr[Htag] 
	}
	print ""
	print "dist_freq_numbers_count_arr"
	for ( Htag in dist_freq_numbers_count_arr ) {
		print "DEBUGHU: dist_freq_numbers_count_arr[" Htag "]  = " dist_freq_numbers_count_arr[Htag] 
	}
	print ""
	print "gloroam_users_cost_arr"
	for ( Htag in gloroam_users_cost_arr ) {
		print "DEBUGHU: gloroam_users_cost_arr[" Htag "]  = " gloroam_users_cost_arr[Htag] 
	}
	print ""
	print "hi_gloroam_users_by_cost_arr"
	for ( Htag in hi_gloroam_users_by_cost_arr ) {
		print "DEBUGHU: hi_gloroam_users_by_cost_arr[" Htag "]  = " hi_gloroam_users_by_cost_arr[Htag] 
	}
	print ""
	print "internet_users_cost_arr"
	for ( Htag in internet_users_cost_arr ) {
		print "DEBUGHU: internet_users_cost_arr[" Htag "]  = " internet_users_cost_arr[Htag] 
	}
	print ""
	print "hi_internet_users_by_cost_arr"
	for ( Htag in hi_internet_users_by_cost_arr ) {
		print "DEBUGHU: hi_internet_users_by_cost_arr[" Htag "]  = " hi_internet_users_by_cost_arr[Htag] 
	}
	print ""
	print "sid_premserv_count_arr"
	for ( Htag in sid_premserv_count_arr ) {
		print "DEBUGHU: sid_premserv_count_arr[" Htag "]  = " sid_premserv_count_arr[Htag] 
	}
	print ""
	print "hi_premserv_users_by_cost_arr"
	for ( Htag in hi_premserv_users_by_cost_arr ) {
		print "DEBUGHU: hi_premserv_users_by_cost_arr[" Htag "]  = " hi_premserv_users_by_cost_arr[Htag] 
	}
	print ""

	print ""
	print "call_distribution_date_count_arr"
	for ( Htag in call_distribution_date_count_arr ) {
		print "DEBUGCALLDISTR: call_distribution_date_count_arr[" Htag "]  = " call_distribution_date_count_arr[Htag] "  duration  = " call_distribution_date_duration_arr[Htag] "  cost  = " call_distribution_date_cost_arr[Htag] 
	}
	print ""

	print ""
	print "call_distribution_hour_count_arr"
	for ( Htag in call_distribution_hour_count_arr ) {
		print "DEBUGCALLDISTR: call_distribution_hour_count_arr[" Htag "]  = " call_distribution_hour_count_arr[Htag] "  duration  = " call_distribution_hour_duration_arr[Htag] "  cost  = " call_distribution_hour_cost_arr[Htag] 
	}
	print ""

	print ""
	print "call_distribution_category_count_arr"
	for ( Htag in call_distribution_category_count_arr ) {
		print "DEBUGCALLDISTR: call_distribution_category_count_arr[" Htag "]  = " call_distribution_category_count_arr[Htag] "  duration  = " call_distribution_category_duration_arr[Htag] "  cost  = " call_distribution_category_cost_arr[Htag] 
	}
	print ""

	print ""
	print "nsids_arr"
	for ( Htag in nsids_arr ) {
		print "DEBUGNSIDS: nsids_arr[" Htag "] = " nsids_arr[Htag]
	}
	print ""

	#-----------------------------------------------------
	#-----------------------------------------------------
	print ""
	print "Finish wb2 - " thisCENTRE
	system("date")

	# End BEGIN
	exit 0
}


END {
}