replaced solve by ginv to handle near-singular case