deprecated gl_control and some rewrites
diff --git a/accounts/doctype/budget_control/budget_control.py b/accounts/doctype/budget_control/budget_control.py
index 4a5aff4..dcab3ac 100644
--- a/accounts/doctype/budget_control/budget_control.py
+++ b/accounts/doctype/budget_control/budget_control.py
@@ -74,7 +74,7 @@
 				end_date = webnotes.conn.sql("select LAST_DAY('%s')" % gle['posting_date'])
 			
 				# get Actual
-				actual = webnotes.get_obj('GL Control').get_period_difference(gle['account'] + 
+				actual = self.get_period_difference(gle['account'] + 
 					'~~~' + cstr(start_date) + '~~~' + cstr(end_date[0][0]), gle['cost_center'])
 		
 				# Get Monthly	budget
@@ -89,3 +89,22 @@
 			webnotes.conn.sql("""update `tabBudget Detail` set actual = ifnull(actual,0) + %s 
 				where account = '%s' and fiscal_year = '%s' and parent = '%s'""" % 
 				(curr_amt, gle['account'],gle['fiscal_year'], gle['cost_center']))
+
+
+	def get_period_difference(self, arg, cost_center =''):
+		# used in General Ledger Page Report
+		# used for Budget where cost center passed as extra argument
+		acc, f, t = arg.split('~~~')
+		c, fy = '', get_defaults()['fiscal_year']
+
+		det = webnotes.conn.sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc)
+		if f: c += (' and t1.posting_date >= "%s"' % f)
+		if t: c += (' and t1.posting_date <= "%s"' % t)
+		if cost_center: c += (' and t1.cost_center = "%s"' % cost_center)
+		bal = webnotes.conn.sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' %s" % (acc, c))
+		bal = bal and flt(bal[0][0]) or 0
+
+		if det[0][0] != 'Debit':
+			bal = (-1) * bal
+
+		return flt(bal)
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/__init__.py b/accounts/doctype/gl_control/__init__.py
deleted file mode 100644
index baffc48..0000000
--- a/accounts/doctype/gl_control/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from __future__ import unicode_literals
diff --git a/accounts/doctype/gl_control/gl_control.py b/accounts/doctype/gl_control/gl_control.py
deleted file mode 100644
index 2a7d284..0000000
--- a/accounts/doctype/gl_control/gl_control.py
+++ /dev/null
@@ -1,164 +0,0 @@
-# ERPNext - web based ERP (http://erpnext.com)
-# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
-# 
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-from __future__ import unicode_literals
-import webnotes
-
-from webnotes.utils import cstr, flt, get_defaults
-from webnotes.model.doc import addchild
-from webnotes.model.wrapper import getlist
-from webnotes.model.code import get_obj
-from webnotes import msgprint
-
-class DocType:
-	def __init__(self,d,dl):
-		self.doc, self.doclist = d, dl
-		self.entries = []
-
-	def get_period_difference(self,arg, cost_center =''):
-		# used in General Ledger Page Report
-		# used for Budget where cost center passed as extra argument
-		acc, f, t = arg.split('~~~')
-		c, fy = '', get_defaults()['fiscal_year']
-
-		det = webnotes.conn.sql("select debit_or_credit, lft, rgt, is_pl_account from tabAccount where name=%s", acc)
-		if f: c += (' and t1.posting_date >= "%s"' % f)
-		if t: c += (' and t1.posting_date <= "%s"' % t)
-		if cost_center: c += (' and t1.cost_center = "%s"' % cost_center)
-		bal = webnotes.conn.sql("select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) from `tabGL Entry` t1 where t1.account='%s' %s" % (acc, c))
-		bal = bal and flt(bal[0][0]) or 0
-
-		if det[0][0] != 'Debit':
-			bal = (-1) * bal
-
-		return flt(bal)
-
-	def add_ac(self,arg):
-		ac = webnotes.model_wrapper(eval(arg))
-		ac.doc.doctype = "Account"
-		ac.doc.old_parent = ""
-		ac.doc.freeze_account = "No"
-		ac.ignore_permissions = 1
-		ac.insert()
-
-		return ac.doc.name
-
-	def add_cc(self,arg):
-		cc = webnotes.model_wrapper(eval(arg))
-		cc.doc.doctype = "Cost Center"
-		cc.doc.old_parent = ""
-		cc.ignore_permissions = 1
-		cc.insert()
-
-		return cc.doc.name
-	
-	def get_advances(self, obj, account_head, table_name,table_field_name, dr_or_cr):
-		jv_detail = webnotes.conn.sql("""select t1.name, t1.remark, t2.%s, t2.name 
-			from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 
-			where t1.name = t2.parent 
-			and (t2.against_voucher is null or t2.against_voucher = '')
-			and (t2.against_invoice is null or t2.against_invoice = '') 
-			and (t2.against_jv is null or t2.against_jv = '') 
-			and t2.account = '%s' and t2.is_advance = 'Yes' and t1.docstatus = 1 
-			order by t1.posting_date""" % (dr_or_cr,account_head))
-		# clear advance table
-		obj.doclist = obj.doc.clear_table(obj.doclist,table_field_name)
-		# Create advance table
-		for d in jv_detail:
-			add = addchild(obj.doc, table_field_name, table_name, obj.doclist)
-			add.journal_voucher = d[0]
-			add.jv_detail_no = d[3]
-			add.remarks = d[1]
-			add.advance_amount = flt(d[2])
-			add.allocate_amount = 0
-			
-		return obj.doclist
-
-	def clear_advances(self, obj,table_name,table_field_name):
-		for d in getlist(obj.doclist,table_field_name):
-			if not flt(d.allocated_amount):
-				webnotes.conn.sql("update `tab%s` set parent = '' where name = '%s' \
-					and parent = '%s'" % (table_name, d.name, d.parent))
-				d.parent = ''
-
-	def reconcile_against_document(self, args):
-		"""
-			Cancel JV, Update aginst document, split if required and resubmit jv
-		"""
-		
-		for d in args:
-			self.check_if_jv_modified(d)
-
-			against_fld = {
-				'Journal Voucher' : 'against_jv',
-				'Sales Invoice' : 'against_invoice',
-				'Purchase Invoice' : 'against_voucher'
-			}
-			
-			d['against_fld'] = against_fld[d['against_voucher_type']]
-
-			# cancel JV
-			jv_obj = get_obj('Journal Voucher', d['voucher_no'], with_children=1)
-			self.make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj =1)
-
-			# update ref in JV Detail
-			self.update_against_doc(d, jv_obj)
-
-			# re-submit JV
-			jv_obj = get_obj('Journal Voucher', d['voucher_no'], with_children =1)
-			self.make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj =1)
-
-	def update_against_doc(self, d, jv_obj):
-		"""
-			Updates against document, if partial amount splits into rows
-		"""
-
-		webnotes.conn.sql("""
-			update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2	
-			set t1.%(dr_or_cr)s = '%(allocated_amt)s', 
-			t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now() 
-			where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
-		
-		if d['allocated_amt'] < d['unadjusted_amt']:
-			jvd = webnotes.conn.sql("select cost_center, balance, against_account, is_advance from `tabJournal Voucher Detail` where name = '%s'" % d['voucher_detail_no'])
-			# new entry with balance amount
-			ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
-			ch.account = d['account']
-			ch.cost_center = cstr(jvd[0][0])
-			ch.balance = cstr(jvd[0][1])
-			ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
-			ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
-			ch.against_account = cstr(jvd[0][2])
-			ch.is_advance = cstr(jvd[0][3])
-			ch.docstatus = 1
-			ch.save(1)
-
-	def check_if_jv_modified(self, args):
-		"""
-			check if there is already a voucher reference
-			check if amount is same
-			check if jv is submitted
-		"""
-		ret = webnotes.conn.sql("""
-			select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 
-			where t1.name = t2.parent and t2.account = '%(account)s' 
-			and ifnull(t2.against_voucher, '')='' and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
-			and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
-			and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s
-		""" % (args))
-		
-		if not ret:
-			msgprint("Payment Entry has been modified after you pulled it. Please pull it again.", raise_exception=1)
diff --git a/accounts/doctype/gl_control/gl_control.txt b/accounts/doctype/gl_control/gl_control.txt
deleted file mode 100644
index 7e0710c..0000000
--- a/accounts/doctype/gl_control/gl_control.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-[
- {
-  "owner": "Administrator", 
-  "docstatus": 0, 
-  "creation": "2012-03-27 14:35:42", 
-  "modified_by": "Administrator", 
-  "modified": "2012-03-27 14:35:42"
- }, 
- {
-  "section_style": "Simple", 
-  "name": "__common__", 
-  "colour": "White:FFF", 
-  "module": "Accounts", 
-  "show_in_menu": 0, 
-  "version": 288, 
-  "server_code_error": " ", 
-  "doctype": "DocType", 
-  "issingle": 1
- }, 
- {
-  "name": "GL Control", 
-  "doctype": "DocType"
- }
-]
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/_messages_doc.json b/accounts/doctype/gl_control/locale/_messages_doc.json
deleted file mode 100644
index e7bfed9..0000000
--- a/accounts/doctype/gl_control/locale/_messages_doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-[
- "GL Control", 
- "Accounts"
-]
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/ar-doc.json b/accounts/doctype/gl_control/locale/ar-doc.json
deleted file mode 100644
index 779b94f..0000000
--- a/accounts/doctype/gl_control/locale/ar-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "\u062d\u0633\u0627\u0628\u0627\u062a", 
- "GL Control": "GL \u0627\u0644\u062a\u062d\u0643\u0645"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/es-doc.json b/accounts/doctype/gl_control/locale/es-doc.json
deleted file mode 100644
index f7a8eee..0000000
--- a/accounts/doctype/gl_control/locale/es-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "Cuentas", 
- "GL Control": "GL control"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/fr-doc.json b/accounts/doctype/gl_control/locale/fr-doc.json
deleted file mode 100644
index a7d3b17..0000000
--- a/accounts/doctype/gl_control/locale/fr-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "Comptes", 
- "GL Control": "GL contr\u00f4le"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/hi-doc.json b/accounts/doctype/gl_control/locale/hi-doc.json
deleted file mode 100644
index ab677fa..0000000
--- a/accounts/doctype/gl_control/locale/hi-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "\u0932\u0947\u0916\u093e", 
- "GL Control": "\u091c\u0940\u090f\u0932 \u0928\u093f\u092f\u0902\u0924\u094d\u0930\u0923"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/nl-doc.json b/accounts/doctype/gl_control/locale/nl-doc.json
deleted file mode 100644
index af964d5..0000000
--- a/accounts/doctype/gl_control/locale/nl-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "Accounts", 
- "GL Control": "GL Controle"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/pt-doc.json b/accounts/doctype/gl_control/locale/pt-doc.json
deleted file mode 100644
index bac28e1..0000000
--- a/accounts/doctype/gl_control/locale/pt-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "Contas", 
- "GL Control": "GL Controle"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/sr-doc.json b/accounts/doctype/gl_control/locale/sr-doc.json
deleted file mode 100644
index 23ccd3e..0000000
--- a/accounts/doctype/gl_control/locale/sr-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "\u0420\u0430\u0447\u0443\u043d\u0438", 
- "GL Control": "\u0413\u041b \u041a\u043e\u043d\u0442\u0440\u043e\u043b\u0430"
-}
\ No newline at end of file
diff --git a/accounts/doctype/gl_control/locale/ta-doc.json b/accounts/doctype/gl_control/locale/ta-doc.json
deleted file mode 100644
index 3a8afb9..0000000
--- a/accounts/doctype/gl_control/locale/ta-doc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "Accounts": "\u0b95\u0ba3\u0b95\u0bcd\u0b95\u0bc1\u0b95\u0bb3\u0bcd", 
- "GL Control": "\u0b9c\u0bc0 \u0b95\u0b9f\u0bcd\u0b9f\u0bc1\u0baa\u0bcd\u0baa\u0bbe\u0b9f\u0bc1"
-}
\ No newline at end of file
diff --git a/accounts/doctype/journal_voucher/journal_voucher.py b/accounts/doctype/journal_voucher/journal_voucher.py
index 62546d0..0a4a1a1 100644
--- a/accounts/doctype/journal_voucher/journal_voucher.py
+++ b/accounts/doctype/journal_voucher/journal_voucher.py
@@ -245,7 +245,7 @@
 						d.against_voucher, "debit_to") != d.account:
 				msgprint("Credit account is not matching with Purchase Invoice", raise_exception=1)
 
-	def make_gl_entries(self, cancel=0):
+	def make_gl_entries(self, cancel=0, adv_adj=0):
 		from accounts.general_ledger import make_gl_entries
 		gl_map = []
 		for d in self.doclist.get({"parentfield": "entries"}):
@@ -264,7 +264,7 @@
 				}, cancel)
 			)
 			
-		make_gl_entries(gl_map, cancel=cancel)
+		make_gl_entries(gl_map, cancel=cancel, adv_adj=adv_adj)
 
 	def get_outstanding(self, args):
 		args = eval(args)
diff --git a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
index 3978688..d585cea 100644
--- a/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
+++ b/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
@@ -20,7 +20,6 @@
 from webnotes.utils import flt
 from webnotes.model.doc import addchild
 from webnotes.model.wrapper import getlist
-from webnotes.model.code import get_obj
 from webnotes import msgprint
 
 class DocType:
@@ -137,7 +136,8 @@
 				lst.append(args)
 		
 		if lst:
-			get_obj('GL Control').reconcile_against_document(lst)
+			from accounts.utils import reconcile_against_document
+			reconcile_against_document(lst)
 			msgprint("Successfully allocated.")
 		else:
 			msgprint("No amount allocated.", raise_exception=1)
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.py b/accounts/doctype/purchase_invoice/purchase_invoice.py
index 45b154d..0db7ea8 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -20,7 +20,7 @@
 from webnotes.utils import add_days, cint, cstr, flt, formatdate, get_defaults
 from webnotes.model.wrapper import getlist
 from webnotes.model.code import get_obj
-from webnotes import msgprint
+from webnotes import msgprint, _
 from setup.utils import get_company_currency
 
 sql = webnotes.conn.sql
@@ -99,11 +99,9 @@
 				d.expense_head = item and item[0]['purchase_account'] or ''
 				d.cost_center = item and item[0]['cost_center'] or ''
 
-	# Advance Allocation
-	# -------------------
 	def get_advances(self):
-		self.doclist = get_obj('GL Control').get_advances(self, self.doc.credit_to, 'Purchase Invoice Advance','advance_allocation_details','debit')
-		
+		super(DocType, self).get_advances(self.doc.credit_to, 
+			"Purchase Invoice Advance", "advance_allocation_details", "debit")
 		
 	def get_rate(self,arg):
 		return get_obj('Purchase Common').get_rate(arg,self)
@@ -187,16 +185,7 @@
 	# ---------------------
 	def validate_bill_no_date(self):
 		if self.doc.bill_no and not self.doc.bill_date and self.doc.bill_no.lower().strip() not in ['na', 'not applicable', 'none']:
-			msgprint("Please enter Bill Date")
-			raise Exception					
-
-
- 
-	# Clear Advances
-	# ---------------
-	def clear_advances(self):
-		get_obj('GL Control').clear_advances( self, 'Purchase Invoice Advance','advance_allocation_details')
-
+			msgprint(_("Please enter Bill Date"), raise_exception=1)
 
 	# 1. Credit To Account Exists
 	# 2. Is a Credit Account
@@ -326,8 +315,6 @@
 		if self.doc.write_off_amount and not self.doc.write_off_account:
 			msgprint("Please enter Write Off Account", raise_exception=1)
 
-	# VALIDATE
-	# ====================================================================================
 	def validate(self):
 		super(DocType, self).validate()
 		
@@ -338,8 +325,8 @@
 		self.validate_bill_no_date()
 		self.validate_bill_no()
 		self.validate_reference_value()
-		self.clear_advances()
 		self.validate_credit_acc()
+		self.clear_unallocated_advances("Purchase Invoice Advance", "advance_allocation_details")
 		self.check_for_acc_head_of_supplier()
 		self.check_for_stopped_status()
 
@@ -406,8 +393,8 @@
 				lst.append(args)
 		
 		if lst:
-			get_obj('GL Control').reconcile_against_document(lst)
-
+			from accounts.utils import reconcile_against_document
+			reconcile_against_document(lst)
 
 	def on_submit(self):
 		purchase_controller = webnotes.get_obj("Purchase Common")
diff --git a/accounts/doctype/sales_invoice/sales_invoice.py b/accounts/doctype/sales_invoice/sales_invoice.py
index 0e5276c..7cb165b 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/accounts/doctype/sales_invoice/sales_invoice.py
@@ -50,13 +50,15 @@
 		sales_com_obj.check_stop_sales_order(self)
 		sales_com_obj.check_active_sales_items(self)
 		sales_com_obj.check_conversion_rate(self)
-		sales_com_obj.validate_max_discount(self, 'entries')	 #verify whether rate is not greater than tolerance
-		sales_com_obj.get_allocated_sum(self)	# this is to verify that the allocated % of sales persons is 100%
-		sales_com_obj.validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
+		sales_com_obj.validate_max_discount(self, 'entries')
+		sales_com_obj.get_allocated_sum(self)
+		sales_com_obj.validate_fiscal_year(self.doc.fiscal_year, 
+			self.doc.posting_date,'Posting Date')
 		self.validate_customer()
 		self.validate_customer_account()
 		self.validate_debit_acc()
 		self.validate_fixed_asset_account()
+		self.clear_unallocated_advances("Sales Invoice Advance", "advance_adjustment_details")
 		self.add_remarks()
 		if cint(self.doc.is_pos):
 			self.validate_pos()
@@ -71,7 +73,6 @@
 		if not self.doc.is_opening:
 			self.doc.is_opening = 'No'
 		self.set_aging_date()
-		self.clear_advances()
 		self.set_against_income_account()
 		self.validate_c_form()
 		self.validate_recurring_invoice()
@@ -90,12 +91,13 @@
 		else:
 			# Check for Approving Authority
 			if not self.doc.recurring_id:
-				get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, self.doc.company, self.doc.grand_total, self)
+				get_obj('Authorization Control').validate_approving_authority(self.doc.doctype, 
+				 	self.doc.company, self.doc.grand_total, self)
 
 		self.check_prev_docstatus()
 		get_obj("Sales Common").update_prevdoc_detail(1,self)
 		
-		# this sequence because outstanding may get -ve		
+		# this sequence because outstanding may get -ve
 		self.make_gl_entries()
 
 		if not cint(self.doc.is_pos) == 1:
@@ -194,13 +196,17 @@
 
 	def get_cust_and_due_date(self):
 		"""Set Due Date = Posting Date + Credit Days"""
-		credit_days = 0
-		if self.doc.debit_to:
-			credit_days = webnotes.conn.get_value("Account", self.doc.debit_to, "credit_days")
-		if self.doc.company and not credit_days:
-			credit_days = webnotes.conn.get_value("Company", self.doc.company, "credit_days")
-
-		self.doc.due_date = add_days(cstr(self.doc.posting_date), credit_days)
+		if self.doc.posting_date:
+			credit_days = 0
+			if self.doc.debit_to:
+				credit_days = webnotes.conn.get_value("Account", self.doc.debit_to, "credit_days")
+			if self.doc.company and not credit_days:
+				credit_days = webnotes.conn.get_value("Company", self.doc.company, "credit_days")
+				
+			if credit_days:
+				self.doc.due_date = add_days(self.doc.posting_date, credit_days)
+			else:
+				self.doc.due_date = self.doc.posting_date
 		
 		if self.doc.debit_to:
 			self.doc.customer = webnotes.conn.get_value('Account',self.doc.debit_to,'master_name')
@@ -326,8 +332,9 @@
 
 
 	def get_advances(self):
-		self.doclist = get_obj('GL Control').get_advances(self, self.doc.debit_to, 'Sales Invoice Advance', 'advance_adjustment_details', 'credit')
-
+		super(DocType, self).get_advances(self.doc.debit_to, 
+			"Sales Invoice Advance", "advance_adjustment_details", "credit")
+		
 	def get_company_abbr(self):
 		return webnotes.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
 		
@@ -368,7 +375,8 @@
 				lst.append(args)
 		
 		if lst:
-			get_obj('GL Control').reconcile_against_document(lst)
+			from accounts.utils import reconcile_against_document
+			reconcile_against_document(lst)
 	
 	
 	def validate_customer(self):
@@ -418,10 +426,6 @@
 				msgprint("Please select income head with account type 'Fixed Asset Account' as Item %s is an asset item" % d.item_code)
 				raise Exception
 
-	def clear_advances(self):
-		get_obj('GL Control').clear_advances(self, 'Sales Invoice Advance','advance_adjustment_details')
-
-
 	def set_aging_date(self):
 		if self.doc.is_opening != 'Yes':
 			self.doc.aging_date = self.doc.posting_date
diff --git a/accounts/page/accounts_browser/accounts_browser.js b/accounts/page/accounts_browser/accounts_browser.js
index da045a6..6fd0c66 100644
--- a/accounts/page/accounts_browser/accounts_browser.js
+++ b/accounts/page/accounts_browser/accounts_browser.js
@@ -236,12 +236,15 @@
 			v.master_type = '';
 			v.company = me.company;
 			
-		    $c_obj('GL Control', 'add_ac', v, 
-				function(r,rt) { 
+			wn.call({
+				args: v,
+				method:'accounts.utils.add_ac',
+				callback: function(r) {
 					$(btn).done_working();
 					d.hide();
-					node.trigger('reload'); 	
-				});
+					node.trigger('reload');
+				}
+			});
 		});
 		
 		// show
@@ -280,12 +283,15 @@
 			v.parent_cost_center = node.data('label');
 			v.company_name = me.company;
 			
-		    $c_obj('GL Control', 'add_cc', v, 
-				function(r,rt) { 
+			wn.call({
+				args: v,
+				method:'accounts.utils.add_cc',
+				callback: function(r) {
 					$(btn).done_working();
 					d.hide();
-					node.trigger('reload'); 	
-				});
+					node.trigger('reload');
+				}
+			});
 		});
 		d.show();
 	}
diff --git a/accounts/utils.py b/accounts/utils.py
index 8ad1899..b2a2b2c 100644
--- a/accounts/utils.py
+++ b/accounts/utils.py
@@ -17,7 +17,9 @@
 from __future__ import unicode_literals
 
 import webnotes
-from webnotes.utils import nowdate
+from webnotes.utils import nowdate, cstr, flt
+from webnotes.model.doc import addchild
+from webnotes import msgprint, _
 
 class FiscalYearError(webnotes.ValidationError): pass
 
@@ -96,4 +98,102 @@
 		bal = -bal
 
 	# if bal is None, return 0
-	return bal or 0
\ No newline at end of file
+	return bal or 0
+
+@webnotes.whitelist()
+def add_ac(args=None):
+	if not args:
+		args = webnotes.form_dict
+		args.pop("cmd")
+	
+	ac = webnotes.model_wrapper(args)
+	ac.doc.doctype = "Account"
+	ac.doc.old_parent = ""
+	ac.doc.freeze_account = "No"
+	ac.ignore_permissions = 1
+	ac.insert()
+	return ac.doc.name
+
+@webnotes.whitelist()
+def add_cc(args=None):
+	if not args:
+		args = webnotes.form_dict
+		args.pop("cmd")
+		
+	cc = webnotes.model_wrapper(args)
+	cc.doc.doctype = "Cost Center"
+	cc.doc.old_parent = ""
+	cc.ignore_permissions = 1
+	cc.insert()
+	return cc.doc.name
+
+def reconcile_against_document(args):
+	"""
+		Cancel JV, Update aginst document, split if required and resubmit jv
+	"""
+	for d in args:
+		check_if_jv_modified(d)
+
+		against_fld = {
+			'Journal Voucher' : 'against_jv',
+			'Sales Invoice' : 'against_invoice',
+			'Purchase Invoice' : 'against_voucher'
+		}
+		
+		d['against_fld'] = against_fld[d['against_voucher_type']]
+
+		# cancel JV
+		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
+		jv_obj.make_gl_entries(cancel=1, adv_adj=1)
+		
+		# update ref in JV Detail
+		update_against_doc(d, jv_obj)
+
+		# re-submit JV
+		jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
+		jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
+
+
+def check_if_jv_modified(args):
+	"""
+		check if there is already a voucher reference
+		check if amount is same
+		check if jv is submitted
+	"""
+	ret = webnotes.conn.sql("""
+		select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 
+		where t1.name = t2.parent and t2.account = '%(account)s' 
+		and ifnull(t2.against_voucher, '')='' 
+		and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
+		and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
+		and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
+	
+	if not ret:
+		msgprint(_("""Payment Entry has been modified after you pulled it. 
+			Please pull it again."""), raise_exception=1)
+
+def update_against_doc(d, jv_obj):
+	"""
+		Updates against document, if partial amount splits into rows
+	"""
+
+	webnotes.conn.sql("""
+		update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2	
+		set t1.%(dr_or_cr)s = '%(allocated_amt)s', 
+		t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now() 
+		where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
+	
+	if d['allocated_amt'] < d['unadjusted_amt']:
+		jvd = webnotes.conn.sql("""select cost_center, balance, against_account, is_advance 
+			from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
+		# new entry with balance amount
+		ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
+		ch.account = d['account']
+		ch.cost_center = cstr(jvd[0][0])
+		ch.balance = cstr(jvd[0][1])
+		ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
+		ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
+		ch.against_account = cstr(jvd[0][2])
+		ch.is_advance = cstr(jvd[0][3])
+		ch.docstatus = 1
+		ch.save(1)
\ No newline at end of file
diff --git a/buying/doctype/supplier/supplier.py b/buying/doctype/supplier/supplier.py
index a8ab665..096a43e 100644
--- a/buying/doctype/supplier/supplier.py
+++ b/buying/doctype/supplier/supplier.py
@@ -17,13 +17,13 @@
 from __future__ import unicode_literals
 import webnotes
 
-from webnotes.utils import cstr, cint, get_defaults
-from webnotes.model.code import get_obj
+from webnotes.utils import cint, get_defaults
 from webnotes import msgprint, _
 from webnotes.model.doc import make_autoname
 
 sql = webnotes.conn.sql
 
+from accounts.utils import add_ac
 from utilities.transaction_base import TransactionBase
 
 class DocType(TransactionBase):
@@ -70,16 +70,16 @@
 		return g
 
 	def add_account(self, ac, par, abbr):
-		arg = {
+		ac = add_ac({
 			'account_name':ac,
 			'parent_account':par,
 			'group_or_ledger':'Group',
 			'company':self.doc.company,
 			'account_type':'',
 			'tax_rate':'0'
-		}
-		t = get_obj('GL Control').add_ac(cstr(arg))
-		msgprint("Created Group " + t)
+		})
+		
+		msgprint(_("Created Group ") + ac)
 	
 	def get_company_abbr(self):
 		return sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
@@ -109,7 +109,7 @@
 			if not sql("select name from tabAccount where name=%s", (self.doc.name + " - " + abbr)):
 				parent_account = self.get_parent_account(abbr)
 				
-				arg = {
+				ac = add_ac({
 					'account_name': self.doc.name,
 					'parent_account': parent_account,
 					'group_or_ledger':'Ledger',
@@ -118,10 +118,8 @@
 					'tax_rate': '0',
 					'master_type': 'Supplier',
 					'master_name': self.doc.name,
-				}
-				# create
-				ac = get_obj('GL Control').add_ac(cstr(arg))
-				msgprint("Created Account Head: "+ac)
+				})
+				msgprint(_("Created Account Head: ") + ac)
 				
 		else : 
 			msgprint("Please select Company under which you want to create account head")
diff --git a/controllers/accounts_controller.py b/controllers/accounts_controller.py
index d2f29b2..912135e 100644
--- a/controllers/accounts_controller.py
+++ b/controllers/accounts_controller.py
@@ -16,7 +16,8 @@
 
 from __future__ import unicode_literals
 import webnotes
-
+from webnotes.utils import flt
+from webnotes.model.doc import addchild
 from utilities.transaction_base import TransactionBase
 
 class AccountsController(TransactionBase):
@@ -37,15 +38,39 @@
 		}
 		gl_dict.update(args)
 		return gl_dict
-	
-	def get_company_abbr(self):
-		return webnotes.conn.get_value("Company", self.doc.company, "abbr")
 		
 	def get_stock_in_hand_account(self):
-		stock_in_hand = webnotes.conn.get_value("Company", self.doc.company, "stock_in_hand")
-		
+		stock_in_hand = webnotes.conn.get_value("Company", self.doc.company, "stock_in_hand")	
 		if not stock_in_hand:
 			webnotes.msgprint("""Please specify "Stock In Hand" account 
 				for company: %s""" % (self.doc.company,), raise_exception=1)
 				
 		return stock_in_hand
+		
+	def clear_unallocated_advances(self, parenttype, parentfield):
+		for d in self.doclist:
+			if d.parentfield == parentfield and flt(d.allocated_amount) == 0:
+				self.doclist.remove(d)
+			
+		webnotes.conn.sql("""delete from `tab%s` where parent = %s 
+			and ifnull(allocated_amount, 0) = 0""" % (parenttype, '%s'), self.doc.name)			
+		
+	def get_advances(self, account_head, parenttype, parentfield, dr_or_cr):
+		res = webnotes.conn.sql("""select t1.name as jv_no, t1.remark, 
+			t2.%s as amount, t2.name as jv_detail_no
+			from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 
+			where t1.name = t2.parent and t2.account = %s and t2.is_advance = 'Yes' 
+			and (t2.against_voucher is null or t2.against_voucher = '')
+			and (t2.against_invoice is null or t2.against_invoice = '') 
+			and (t2.against_jv is null or t2.against_jv = '') 
+			and t1.docstatus = 1 order by t1.posting_date""" % 
+			(dr_or_cr, '%s'), account_head, as_dict=1)
+			
+		self.doclist = self.doc.clear_table(self.doclist, parentfield)
+		for d in res:
+			add = addchild(self.doc, parentfield, parenttype, self.doclist)
+			add.journal_voucher = d.jv_no
+			add.jv_detail_no = d.jv_detail_no
+			add.remarks = d.remark
+			add.advance_amount = flt(d.amount)
+			add.allocate_amount = 0
\ No newline at end of file
diff --git a/controllers/buying_controller.py b/controllers/buying_controller.py
index f4e8bb3..a467eb2 100644
--- a/controllers/buying_controller.py
+++ b/controllers/buying_controller.py
@@ -25,7 +25,7 @@
 from controllers.accounts_controller import AccountsController
 
 class BuyingController(AccountsController):
-	def validate(self):
+	def validate(self):		
 		if self.meta.get_field("currency"):
 			self.company_currency = get_company_currency(self.doc.company)
 			self.validate_conversion_rate("currency", "conversion_rate")
diff --git a/selling/doctype/customer/customer.py b/selling/doctype/customer/customer.py
index 5db9279..01fa69c 100644
--- a/selling/doctype/customer/customer.py
+++ b/selling/doctype/customer/customer.py
@@ -19,7 +19,6 @@
 
 from webnotes.utils import cstr, get_defaults
 from webnotes.model.doc import Document, make_autoname
-from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
 sql = webnotes.conn.sql
@@ -55,7 +54,6 @@
 		return g
 	
 	def validate_values(self):
-		# Master name by naming series -> Series field mandatory
 		if get_defaults().get('cust_master_name') == 'Naming Series' and not self.doc.naming_series:
 			msgprint("Series is Mandatory.")
 			raise Exception
@@ -113,13 +111,21 @@
 	def create_account_head(self):
 		if self.doc.company :
 			abbr = self.get_company_abbr()
-			if not sql("select name from tabAccount where name=%s", (self.doc.name + " - " + abbr)):
+			if not webnotes.conn.exists("Account", (self.doc.name + " - " + abbr)):
 				parent_account = self.get_receivables_group()
-				arg = {'account_name':self.doc.name,'parent_account': parent_account, 'group_or_ledger':'Ledger', 'company':self.doc.company,'account_type':'','tax_rate':'0','master_type':'Customer','master_name':self.doc.name}
 				# create
-				
-				ac = get_obj('GL Control').add_ac(cstr(arg))
-				msgprint("Account Head created for "+ac)
+				from accounts.utils import add_ac
+				ac = add_ac({
+					'account_name':self.doc.name,
+					'parent_account': parent_account, 
+					'group_or_ledger':'Ledger',
+					'company':self.doc.company, 
+					'account_type':'', 
+					'tax_rate':'0', 
+					'master_type':'Customer', 
+					'master_name':self.doc.name
+				})
+				msgprint("Account Head: %s created" % ac)
 		else :
 			msgprint("Please Select Company under which you want to create account head")
 
diff --git a/setup/doctype/company/company.py b/setup/doctype/company/company.py
index 5aa1762..e1919a5 100644
--- a/setup/doctype/company/company.py
+++ b/setup/doctype/company/company.py
@@ -18,11 +18,8 @@
 import webnotes
 
 from webnotes.utils import cstr, get_defaults, set_default
-from webnotes.model import db_exists
 from webnotes.model.doc import Document
-from webnotes.model.wrapper import copy_doclist
 from webnotes.model.code import get_obj
-from webnotes import msgprint
 
 sql = webnotes.conn.sql
 
@@ -197,11 +194,23 @@
 	# Create default cost center
 	# ---------------------------------------------------
 	def create_default_cost_center(self):
-		glc = get_obj('GL Control')
-		cc_list = [{'cost_center_name':'Root','company_name':self.doc.name,'group_or_ledger':'Group','parent_cost_center':''}, {'cost_center_name':'Default CC Ledger','company_name':self.doc.name,'group_or_ledger':'Ledger','parent_cost_center':'Root - ' + self.doc.abbr}]
-		for c in cc_list:
-			glc.add_cc(str(c))
-			
+		from accounts.utils import add_cc
+		cc_list = [
+			{
+				'cost_center_name':'Root',
+				'company_name':self.doc.name,
+				'group_or_ledger':'Group',
+				'parent_cost_center':''
+			}, 
+			{
+				'cost_center_name':'Default CC Ledger', 
+				'company_name':self.doc.name,
+				'group_or_ledger':'Ledger',
+				'parent_cost_center':'Root - ' + self.doc.abbr
+			}
+		]
+		for cc in cc_list:
+			add_cc(cc)
 			
 	def on_update(self):
 		self.set_letter_head()