# -*- coding: utf-8 -*-
'''
/***************************************************************************
 TopopyProfiler
								 A QGIS plugin
 This plugin shows the geomorphic index profile
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
							  -------------------
		begin				: 2021-03-31
		git sha			  : $Format:%H$
		copyright			: (C) 2021 by David
		email				: davidglezojgo@gmail.com
 ***************************************************************************/

/***************************************************************************
 *																		 *
 *	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 2 of the License, or	 *
 *	(at your option) any later version.									*
 *																		 *
 ***************************************************************************/
'''
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import QAction, QFileDialog
# Initialize Qt resources from file resources.py
from .resources import *

# Import the code for the DockWidget
from .topopy_profiler_dockwidget import TopopyProfilerDockWidget
import os.path

from qgis.core import *
from qgis.gui import *

from . import topopy
from .topopy import *

from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
from matplotlib.widgets import Button
import matplotlib
import matplotlib.pyplot as plt

import random
import numpy as np
from scipy import interpolate
import ogr, osr

from .qgs_topopy_provider import QgsTopopyProvider

class TopopyProfiler:
	'''QGIS Plugin Implementation.'''

	def __init__(self, iface):
		'''Constructor.

		:param iface: An interface instance that will be passed to this class
			which provides the hook by which you can manipulate the QGIS
			application at run time.
		:type iface: QgsInterface
		'''
		# Save reference to the QGIS interface
		self.iface = iface

		# initialize plugin directory
		self.plugin_dir = os.path.dirname(__file__)

		# initialize locale
		locale = QSettings().value('locale/userLocale')[0:2]
		locale_path = os.path.join(
			self.plugin_dir,
			'i18n',
			'TopopyProfiler_{}.qm'.format(locale))

		if os.path.exists(locale_path):
			self.translator = QTranslator()
			self.translator.load(locale_path)
			QCoreApplication.installTranslator(self.translator)

		# Declare instance attributes
		self.actions = []
		self.menu = self.tr(u'&Topopy')
		# TODO: We are going to let the user set this up in a future iteration
		self.toolbar = self.iface.addToolBar(u'Topopy')
		self.toolbar.setObjectName(u'Topopy')

		# print '** INITIALIZING TopopyProfiler'

		self.pluginIsActive = False
		self.first_start = None
		# Declare UI variable
		self.dockwidget = TopopyProfilerDockWidget()
				
		# Set all layouts		
		LayoutsParam = matplotlib.figure.SubplotParams(left=0.05, bottom=0.19, right=0.99, top=0.98)
		
		self.Ecanvas = FigureCanvas(Figure(tight_layout=True, subplotpars = LayoutsParam))
		self.Ccanvas = FigureCanvas(Figure(tight_layout=True, subplotpars = LayoutsParam))
		self.Kcanvas = FigureCanvas(Figure(tight_layout=True, subplotpars = LayoutsParam))
		self.Scanvas = FigureCanvas(Figure(tight_layout=True, subplotpars = LayoutsParam))
		
		self.Eaxes = self.Ecanvas.figure.add_subplot()
		self.Caxes = self.Ccanvas.figure.add_subplot()
		self.Kaxes = self.Kcanvas.figure.add_subplot()
		self.Saxes = self.Scanvas.figure.add_subplot()
		
		self.ElevLayout = self.dockwidget.ElevProf.layout()
		self.ChiLayout = self.dockwidget.ChiProf.layout()
		self.KsnLayout = self.dockwidget.KsnProf.layout()
		self.SlopeLayout = self.dockwidget.SlopeProf.layout()
		
		self.ElevLayout.addWidget(self.Ecanvas)
		self.ChiLayout.addWidget(self.Ccanvas)
		self.KsnLayout.addWidget(self.Kcanvas)
		self.SlopeLayout.addWidget(self.Scanvas)

		# Set first channel to plot 
		self.graph = 0
		
		self.CHs=[]

		self.regAct = False

		# Set the properties of the temporary layer
		self.rubberband = QgsRubberBand(self.iface.mapCanvas(), False)
		self.rubberband.setWidth(2)
		self.rubberband.setColor(QColor(Qt.red))
		
		# Set the properties of the temporary layer
		self.rubberpoint = QgsRubberBand(self.iface.mapCanvas(), False)
		self.rubberpoint.setWidth(10)
		self.rubberpoint.setColor(QColor(Qt.red))

		# Set the properties of the temporary layer
		self.rubberknick = QgsRubberBand(self.iface.mapCanvas(), False)
		self.rubberknick.setWidth(5)
		self.rubberknick.setColor(QColor(Qt.red))

		# Delete any temporary layer drawn
		self.rubberknick.reset(QgsWkbTypes.PointGeometry)
		self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
		self.rubberband.reset(QgsWkbTypes.LineGeometry)
		
####-----------------------------------------------------------------------------####
		'''caja de herramientas'''
		self.provider = None
####-----------------------------------------------------------------------------####		

		# Button actions
		self.dockwidget.AddButton.clicked.connect(self.calculate_channels)
		self.dockwidget.NextButton.clicked.connect(lambda:self.next_prev(1))
		self.dockwidget.PrevButton.clicked.connect(lambda:self.next_prev(0))
		self.dockwidget.GoButton.clicked.connect(self.go_graph)
		self.dockwidget.AllCheckBox.clicked.connect(self.all_channels)
		self.dockwidget.KnickButton.clicked.connect(self.check_knickpoints)
		self.dockwidget.SaveButton.clicked.connect(self.save)
		self.dockwidget.RegButton.clicked.connect(self.regression)	
		self.dockwidget.DamButton.clicked.connect(self.remove_dam)	
		
		self.dockwidget.RegButton.clicked.connect(lambda:self.knick_move('L'))
		self.dockwidget.DamButton.clicked.connect(lambda:self.knick_move('R'))
		
		self.dockwidget.LayCursorCheckBox.clicked.connect(lambda:self.lay_show('C'))		
		self.dockwidget.LayStreamCheckBox.clicked.connect(lambda:self.lay_show('S'))	
		self.dockwidget.LayKpCheckBox.clicked.connect(lambda:self.lay_show('K'))	
		self.dockwidget.GraphRegCheckBox.clicked.connect(lambda:self.lay_show('R'))	
		
		self.dockwidget.SimplifyButton.clicked.connect(self.simplify)
		self.dockwidget.tabWidget.currentChanged.connect(self.tabs)

	# noinspection PyMethodMayBeStatic
	def tr(self, message):
		'''Get the translation for a string using Qt translation API.

		We implement this ourselves since we do not inherit QObject.

		:param message: String for translation.
		:type message: str, QString

		:returns: Translated version of message.
		:rtype: QString
		'''
		# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
		return QCoreApplication.translate('TopopyProfiler', message)

	def add_action(self,
		icon_path,
		text,
		callback,
		enabled_flag=True,
		add_to_menu=True,
		add_to_toolbar=True,
		status_tip=None,
		whats_this=None,
		parent=None):
		'''Add a toolbar icon to the toolbar.

		:param icon_path: Path to the icon for this action. Can be a resource
			path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
		:type icon_path: str

		:param text: Text that should be shown in menu items for this action.
		:type text: str

		:param callback: Function to be called when the action is triggered.
		:type callback: function

		:param enabled_flag: A flag indicating if the action should be enabled
			by default. Defaults to True.
		:type enabled_flag: bool

		:param add_to_menu: Flag indicating whether the action should also
			be added to the menu. Defaults to True.
		:type add_to_menu: bool

		:param add_to_toolbar: Flag indicating whether the action should also
			be added to the toolbar. Defaults to True.
		:type add_to_toolbar: bool

		:param status_tip: Optional text to show in a popup when mouse pointer
			hovers over the action.
		:type status_tip: str

		:param parent: Parent widget for the new action. Defaults None.
		:type parent: QWidget

		:param whats_this: Optional text to show in the status bar when the
			mouse pointer hovers over the action.

		:returns: The action that was created. Note that the action is also
			added to self.actions list.
		:rtype: QAction
		'''

		icon = QIcon(icon_path)
		action = QAction(icon, text, parent)
		action.triggered.connect(callback)
		action.setEnabled(enabled_flag)

		if status_tip is not None:
			action.setStatusTip(status_tip)

		if whats_this is not None:
			action.setWhatsThis(whats_this)

		if add_to_toolbar:
			self.toolbar.addAction(action)

		if add_to_menu:
			self.iface.addPluginToMenu(
				self.menu,
				action)

		self.actions.append(action)

		return action

	def initGui(self):
		'''Create the menu entries and toolbar icons inside the QGIS GUI.'''

		icon_path = ':/plugins/topopy_profiler/icon.png'
####-----------------------------------------------------------------------------####	
	###caja de herramientas'''
		self.initProcessing()
####-----------------------------------------------------------------------------####	
		self.add_action(
			icon_path,
			text=self.tr(u'Geomophological profiler'),
			callback=self.run,
			parent=self.iface.mainWindow())
			
		self.first_start = True
		
	#--------------------------------------------------------------------------

	def onClosePlugin(self):
		'''Cleanup necessary items here when plugin dockwidget is closed'''

		#print '** CLOSING TopopyProfiler'

		# disconnects
		self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

		# remove this statement if dockwidget is to remain
		# for reuse if plugin is reopened
		# Commented next statement since it causes QGIS crashe
		# when closing the docked window:
		# self.dockwidget = None

		self.pluginIsActive = False
		
		#Clean the plugin
		self.dockwidget.PrevButton.setEnabled(False)
		self.dockwidget.NextButton.setEnabled(False)
		self.dockwidget.GoButton.setEnabled(False)
		self.dockwidget.GoSpinBox.setEnabled(False)
		self.dockwidget.AllCheckBox.setEnabled(False)
		self.dockwidget.AllCheckBox.setChecked(False)
		self.dockwidget.KnickButton.setEnabled(False)	
		self.dockwidget.RegButton.setEnabled(False)
		self.dockwidget.DamButton.setEnabled(False)		
		self.dockwidget.SaveButton.setEnabled(False)	
		self.dockwidget.SaveComboBox.setEnabled(False)	
		self.dockwidget.verticalGroupBox.setEnabled(True)

		self.regAct = False

		try:
			self.Ecanvas.mpl_disconnect(self.Epoint)
			self.Ccanvas.mpl_disconnect(self.Cpoint)
			self.Kcanvas.mpl_disconnect(self.Kpoint)
			self.Scanvas.mpl_disconnect(self.Spoint)
		except:
			None
		
		if self.dockwidget.KnickButton.isChecked()==True:		
			try:
				self.dockwidget.RegButton.clicked.disconnect(lambda:self.knick_move('L'))
			except:
				None
			try:
				self.dockwidget.DamButton.clicked.disconnect(lambda:self.knick_move('R'))
			except:
				None
				
			self.dockwidget.RegButton.clicked.connect(self.regression)	
			self.dockwidget.DamButton.clicked.connect(self.remove_dam)
			self.Ecanvas.mpl_disconnect(self.Eknick)
			self.Ccanvas.mpl_disconnect(self.Cknick)
			self.Kcanvas.mpl_disconnect(self.Kknick)
			self.Scanvas.mpl_disconnect(self.Sknick)
			self.dockwidget.KnickButton.setChecked(False)			
			self.dockwidget.RegButton.setText('Regression')			
			self.dockwidget.DamButton.setText('Remove Dam')		
			self.dockwidget.FileLineEdit.setEnabled(True)			
			self.dockwidget.PathButton.setEnabled(True)	
			self.dockwidget.AddButton.setEnabled(True)	

			self.dockwidget.RegButton.setCheckable(True)
			self.dockwidget.DamButton.setCheckable(True)	
		
		if self.dockwidget.DamButton.isChecked()==True:
			self.dockwidget.FileLineEdit.setEnabled(True)	
			self.dockwidget.PathButton.setEnabled(True)	
			self.dockwidget.AddButton.setEnabled(True)	
			self.Ecanvas.mpl_disconnect(self.Edam)
			self.Ccanvas.mpl_disconnect(self.Cdam)
			self.dockwidget.DamButton.setChecked(False)		
		
		if self.dockwidget.RegButton.isChecked()==True:
			self.dockwidget.RegButton.setChecked(False)	
			
		self.dockwidget.NcLabelValue.setText('')
	
		self.clear_graph()
		self.draw_graph()
		self.graph = 0
		
		self.rubberband.reset(QgsWkbTypes.LineGeometry)
		self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
		self.rubberknick.reset(QgsWkbTypes.PointGeometry)
		self.iface.mainWindow().statusBar().showMessage( '' )

		self.CHs=[]

	def unload(self):
		'''Removes the plugin menu item and icon from QGIS GUI.'''

		#print '** UNLOAD TopopyProfiler'

		for action in self.actions:
			self.iface.removePluginMenu(
				self.tr(u'&Topopy Profiler'),
				action)
			self.iface.removeToolBarIcon(action)
		# remove the toolbar
		del self.toolbar
		
		# Delete any temporary layer drawn
		self.rubberband.reset(QgsWkbTypes.LineGeometry)
		self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
		self.rubberknick.reset(QgsWkbTypes.PointGeometry)
####-----------------------------------------------------------------------------####	
	###caja de herramientas'''
		QgsApplication.processingRegistry().removeProvider(self.provider)
####-----------------------------------------------------------------------------####			

	def run(self):
		'''Run method that loads and starts the plugin'''

		
		if not self.pluginIsActive:
			self.pluginIsActive = True

			#print '** STARTING TopopyProfiler'

			# dockwidget may not exist if:
			#	first run of plugin
			#	removed on close (see self.onClosePlugin method)
			#if self.dockwidget == None:
				# Create the dockwidget (after translation) and keep reference


			# connect to provide cleanup on closing of dockwidget
			self.dockwidget.closingPlugin.connect(self.onClosePlugin)
			

		# Clear the contents of the comboBox from previous runs
		self.dockwidget.FileLineEdit.clear()
		

		# Help message at the bottom of the QGis window
		self.iface.mainWindow().statusBar().showMessage( 'Set CHANNELS file (.npy), then click on \'READ\' to display the profiles.' )

		# show the dockwidget
		# TODO: fix to allow choice of dock location
		self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dockwidget)
		self.dockwidget.show()
		if self.first_start == True:
			self.first_start = False
			self.dockwidget.PathButton.clicked.connect(self.select_output_file)


####-----------------------------------------------------------------------------####	
	'''caja de herramientas'''
	def initProcessing(self):
		'''Init Processing provider for QGIS >= 3.8.'''
		self.provider = QgsTopopyProvider()
		QgsApplication.processingRegistry().addProvider(self.provider)
####-----------------------------------------------------------------------------####


	def select_output_file(self):
		filename, _filter = QFileDialog.getOpenFileName(self.dockwidget, 'Select Channels file ','', 'NPY files (*.npy)')
		if filename != '':
			self.dockwidget.FileLineEdit.setText(filename)

	def calculate_channels(self):
		print('calculate')
		''' Calculate all elements of topopy '''
		filename = self.dockwidget.FileLineEdit.text()
		if filename:

			self.CHs = np.load(str(filename), allow_pickle=True)

			# Set first channel to plot 
			self.graph = 0
			
			self.change_graph()
			
			# Turn on the buttons and display the number of channels 
			self.dockwidget.GoSpinBox.setMaximum(int(len(self.CHs)))
			self.dockwidget.NcLabelValue.setText(str(len(self.CHs))+ ' Channels loaded')

			self.dockwidget.KnickButton.setEnabled(True)
			self.dockwidget.SaveButton.setEnabled(True)	
			self.dockwidget.SaveComboBox.setEnabled(True)	
			self.dockwidget.AllCheckBox.setChecked(False)
			self.dockwidget.LayCursorCheckBox.setEnabled(True)			
			self.dockwidget.LayStreamCheckBox.setEnabled(True)			
			self.dockwidget.LayKpCheckBox.setEnabled(True)			
			self.dockwidget.GraphRegCheckBox.setEnabled(True)	

			if len(self.CHs)>1:
				self.dockwidget.NextButton.setEnabled(True)	
				self.dockwidget.GoButton.setEnabled(True)
				self.dockwidget.GoSpinBox.setEnabled(True)
				self.dockwidget.AllCheckBox.setEnabled(True)

			else:
				self.dockwidget.NextButton.setEnabled(False)	
				self.dockwidget.GoButton.setEnabled(False)
				self.dockwidget.GoSpinBox.setEnabled(False)
				self.dockwidget.AllCheckBox.setEnabled(False)

		
			self.iface.mainWindow().statusBar().showMessage( '' )

			self.tabs()
			
			self.d_all = []
			self.chi_all = []

	def simplify(self):
		self.simplify = self.dockwidget.SimplifySpinBox.value()
		if self.dockwidget.AllCheckBox.isChecked()==True:
			self.all_channels()
		else:
			self.change_graph()
		self.iface.mainWindow().statusBar().showMessage('simplifyed!')		
			
	def change_graph(self):
		print('change')
		''' Change the plotted channel '''
		if 	len(self.CHs) != 0:
			# Clear the profiles
			self.clear_graph()
			
			# Call the channel 
			self.channel = self.CHs[self.graph]
			self.simplify = self.dockwidget.SimplifySpinBox.value()

			# Update the channel selector 
			self.dockwidget.GoSpinBox.setValue(int(self.graph)+1)

			self.Epoint = self.Ecanvas.mpl_connect('motion_notify_event', lambda event: self.move(event, 'D'))
			self.Cpoint = self.Ccanvas.mpl_connect('motion_notify_event', lambda event: self.move(event, 'C'))
			self.Kpoint = self.Kcanvas.mpl_connect('motion_notify_event', lambda event: self.move(event, 'D'))
			self.Spoint = self.Scanvas.mpl_connect('motion_notify_event', lambda event: self.move(event, 'D'))

			# W = self.dockwidget.ElevProf.geometry().width()
			# H = self.dockwidget.ElevProf.geometry().height()

			# self.Ecanvas.figure.tight_layout(pad=2, w_pad=0, h_pad=0)			
			# self.Ccanvas.figure.tight_layout(pad=2, w_pad=0, h_pad=0)	
			# self.Kcanvas.figure.tight_layout(pad=2, w_pad=0, h_pad=0)	
			# self.Scanvas.figure.tight_layout(pad=2, w_pad=0, h_pad=0)	

			# self.Ecanvas.resize(W,H)
			# self.Ccanvas.resize(W,H)
			# self.Kcanvas.resize(W,H)
			# self.Scanvas.resize(W,H)	
			
			
			# Show the profiles
			self.draw_graph()
			
			# Create a temporary polyline of the selected channel
			self.rubberband.reset(QgsWkbTypes.LineGeometry)
			self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
			self.rubberknick.reset(QgsWkbTypes.PointGeometry)
			
			self.lay_show('C')	
			self.lay_show('S')	
			self.lay_show('K')	
			
			

	def next_prev(self, direction):
		''' Select the next or previuos channel '''
		print('next_prev')
		if direction == 0:
			# Go back to the previous channel
			if self.graph > 0:
				self.graph -= 1
				
			# Disable the '<Prev' button if the channel is the first
			if self.graph == 0:
				self.dockwidget.PrevButton.setEnabled(False)
				
			# Enable the 'Next>' button if the channel is the penultimate
			if self.graph == (len(self.CHs)-2):
				self.dockwidget.NextButton.setEnabled(True)

		if direction == 1:
			# Advance to the next channel
			if self.graph < (len(self.CHs)-1):
				self.graph += 1
			
			# Disable the 'Next>' button if the channel is the last
			if self.graph == (len(self.CHs)-1):
				self.dockwidget.NextButton.setEnabled(False)
			
			# Enable the '<Prev' button if the channel is the second 
			if self.graph == 1:
				self.dockwidget.PrevButton.setEnabled(True)
			
		# Change channel
		self.change_graph()
		
	def go_graph(self):
		''' Select a specific channel '''
		print('go')
		# Select the channel number 	
		self.graph = self.dockwidget.GoSpinBox.value() - 1
	
		# Disable the 'Next>' button if the channel is the last, else enable it
		if self.graph == (len(self.CHs)-1):
			self.dockwidget.NextButton.setEnabled(False)
		else:
			self.dockwidget.NextButton.setEnabled(True)
			
		# Disable the '<Prev' button if the channel is the first, else enable it
		if self.graph == 0:
			self.dockwidget.PrevButton.setEnabled(False)
		else:
			self.dockwidget.PrevButton.setEnabled(True)
			
		# Change channel	
		self.change_graph()

	def single_channels(self):
		print('single')
		# Set the Profiles
		# Elevation profile
		self.Eaxes.plot(list(self.channel.get_d(head=False)[::self.simplify])+list([self.channel.get_d(head=False)[-1]]), list(self.channel.get_z()[::self.simplify])+list([self.channel.get_z()[-1]]), color='r', ls='-', c='0.3', lw=1)
		self.Eaxes.set_xlim(xmin=0, xmax=max(self.channel.get_d()))
		# Chi profile
		self.Caxes.plot(list(self.channel.get_chi()[::self.simplify])+list([self.channel.get_chi()[-1]]), list(self.channel.get_z()[::self.simplify])+list([self.channel.get_z()[-1]]), color='r', ls='-', c='0.3', lw=1)
		self.Caxes.set_xlim(xmin=min(self.channel.get_chi()), xmax=max(self.channel.get_chi()))
		# Ksn profile
		self.Kaxes.plot(list(self.channel.get_d(head=False)[::self.simplify])+list([self.channel.get_d(head=False)[-1]]), list(self.channel.get_ksn()[::self.simplify])+list([self.channel.get_ksn()[-1]]),  color='0', ls='None', marker='.', ms=1)
		self.Kaxes.set_xlim(xmin=0, xmax=max(self.channel.get_d()))
		# Slope profile
		self.Saxes.plot(np.array(list(self.channel.get_d(head=False)[::self.simplify])+list([self.channel.get_d(head=False)[-1]])), np.array(list(self.channel.get_slope()[::self.simplify])+list([self.channel.get_slope()[-1]]))*100,  color='0', ls='None', marker='.', ms=1)
		self.Saxes.set_xlim(xmin=0, xmax=max(self.channel.get_d()))		
		
	def all_channels(self):
		'''Show all channels'''
		if self.dockwidget.AllCheckBox.isChecked()==True:
			# Clear the profiles
			self.clear_graph()
			
			if len(self.d_all) == 0:
				for n in np.arange(len(self.CHs)):

					self.d_all += list(self.CHs[n].get_d(head=False))
					self.chi_all += list(self.CHs[n].get_chi())

			for n in np.arange(len(self.CHs)):
				print('all')
				color = np.arange(0,1,0.1)
				C = (random.choice(color), random.choice(color), random.choice(color))
				# Set the Profiles
				# Elevation profile
				self.Eaxes.plot(list(self.CHs[n].get_d(head=False)[::self.simplify])+list([self.CHs[n].get_d(head=False)[-1]]), list(self.CHs[n].get_z()[::self.simplify])+list([self.CHs[n].get_z()[-1]]), color=C, ls='-', c='0.3', lw=1)
				self.Eaxes.set_xlim(xmin=0, xmax=max(self.d_all))
				# Chi profile
				self.Caxes.plot(list(self.CHs[n].get_chi()[::self.simplify])+list([self.CHs[n].get_chi()[-1]]), list(self.CHs[n].get_z()[::self.simplify])+list([self.CHs[n].get_z()[-1]]), color=C, ls='-', c='0.3', lw=1)
				self.Caxes.set_xlim(xmin=min(self.chi_all), xmax=max(self.chi_all))
				# Ksn profile
				self.Kaxes.plot(list(self.CHs[n].get_d(head=False)[::self.simplify])+list([self.CHs[n].get_d(head=False)[-1]]), list(self.CHs[n].get_ksn()[::self.simplify])+list([self.CHs[n].get_ksn()[-1]]),  color=C, ls='None', marker='.', ms=1)
				self.Kaxes.set_xlim(xmin=0, xmax=max(self.d_all))
				# Slope profile
				self.Saxes.plot(np.array(list(self.CHs[n].get_d(head=False)[::self.simplify])+list([self.CHs[n].get_d(head=False)[-1]])), np.array(list(self.CHs[n].get_slope()[::self.simplify])+list([self.CHs[n].get_slope()[-1]]))*100,  color=C, ls='None', marker='.', ms=1)
				self.Saxes.set_xlim(xmin=0, xmax=max(self.d_all))

			# Show the profiles
			self.draw_graph()
			self.rubberband.reset(QgsWkbTypes.LineGeometry)

			self.dockwidget.PrevButton.setEnabled(False)
			self.dockwidget.NextButton.setEnabled(False)
			self.dockwidget.GoButton.setEnabled(False)
			self.dockwidget.GoSpinBox.setEnabled(False)
			self.dockwidget.PrevButton.setEnabled(False)
			self.dockwidget.KnickButton.setEnabled(False)	
			self.dockwidget.RegButton.setEnabled(False)
			self.dockwidget.DamButton.setEnabled(False)
			self.dockwidget.LayCursorCheckBox.setEnabled(False)			
			self.dockwidget.LayStreamCheckBox.setEnabled(False)			
			self.dockwidget.LayKpCheckBox.setEnabled(False)			
			self.dockwidget.GraphRegCheckBox.setEnabled(False)			
			
			self.Ecanvas.mpl_disconnect(self.Epoint)
			self.Ccanvas.mpl_disconnect(self.Cpoint)
			self.Kcanvas.mpl_disconnect(self.Kpoint)
			self.Scanvas.mpl_disconnect(self.Spoint)

			self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
			self.rubberknick.reset(QgsWkbTypes.PointGeometry)	
			
			self.iface.mainWindow().statusBar().showMessage('All channels plotted!')			
		
			
		elif self.dockwidget.AllCheckBox.isChecked()==False:
			# Change channel
			self.change_graph()
			if self.graph < (len(self.CHs)-1):
				self.dockwidget.NextButton.setEnabled(True)
			if self.graph > 0:
				self.dockwidget.PrevButton.setEnabled(True)

			self.dockwidget.GoButton.setEnabled(True)
			self.dockwidget.GoSpinBox.setEnabled(True)
			self.dockwidget.KnickButton.setEnabled(True)
			self.dockwidget.DamButton.setEnabled(True)
			self.dockwidget.LayCursorCheckBox.setEnabled(True)			
			self.dockwidget.LayStreamCheckBox.setEnabled(True)			
			self.dockwidget.LayKpCheckBox.setEnabled(True)			
			self.dockwidget.GraphRegCheckBox.setEnabled(True)		
			
			self.iface.mainWindow().statusBar().showMessage('Plotted channel '+ str(self.graph+1)+'!')	
			
	def clear_graph(self):
		''' Clear all graphs '''
		
		self.Eaxes.clear()
		self.Caxes.clear()
		self.Kaxes.clear()
		self.Saxes.clear()
	
	def draw_graph(self):
		''' Draw all graphs '''
		
		self.Eaxes.set_xlabel('Distance to mouth [m]')
		self.Eaxes.set_ylabel('Elevation [m]')
		self.Caxes.set_xlabel('χ [m]')		
		self.Caxes.set_ylabel('Elevation [m]')
		self.Kaxes.set_xlabel('Distance to mouth [m]')
		self.Kaxes.set_ylabel('ksn')
		self.Saxes.set_xlabel('Distance to mouth [m]')
		self.Saxes.set_ylabel('Slope [%]')
			
		self.Ecanvas.draw()
		self.Ccanvas.draw()
		self.Kcanvas.draw()
		self.Scanvas.draw()

	def tabs(self):
		
		w = self.dockwidget.dockWidgetContents.geometry().width()
		h = self.dockwidget.dockWidgetContents.geometry().height()
		
		self.dockwidget.dockWidgetContents.resize((w+1), (h+1))
		self.dockwidget.dockWidgetContents.resize((w-1), (h-1))
			
		if len(self.CHs) != 0:
			if self.dockwidget.KnickButton.isChecked()==False:
				if self.dockwidget.AllCheckBox.isChecked()==False:
					if self.dockwidget.tabWidget.currentIndex() == 1 and self.dockwidget.DamButton.isChecked()== False:
						self.dockwidget.RegButton.setEnabled(True)
					else:
						self.dockwidget.RegButton.setEnabled(False)

					if self.dockwidget.tabWidget.currentIndex() <=1 and self.regAct == False:
						self.dockwidget.DamButton.setEnabled(True)	
					elif self.dockwidget.tabWidget.currentIndex() ==1 and self.regAct == True and len(self.CHs[self.graph]._regressions) != 0:
						self.dockwidget.DamButton.setEnabled(True)	
					else:
						self.dockwidget.DamButton.setEnabled(False)			
			else:
				self.knick_buttons()

	def move(self, event, graphic):
		
		if self.dockwidget.LayCursorCheckBox.isChecked()==True:	
			if event.inaxes:

				if self.dockwidget.AllCheckBox.isChecked()==False:
					self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
					if graphic == 'D':
						i = np.abs(list(self.channel.get_d(head=False)) - event.xdata).argmin()
					if graphic == 'C':
						i = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()
					if graphic == 'H':
						i = np.abs(list(self.hypsometric)- event.xdata).argmin()	
					xy = self.channel.get_xy()[i]
					self.rubberpoint.addPoint(QgsPointXY(xy[0], xy[1]))	  

	def check_knickpoints (self):

		if self.dockwidget.KnickButton.isChecked()==True:
			
			self.Eknick = self.Ecanvas.mpl_connect('button_press_event', lambda event: self.knpoint(event, 'D'))
			self.Cknick = self.Ccanvas.mpl_connect('button_press_event', lambda event: self.knpoint(event, 'C'))
			self.Kknick = self.Kcanvas.mpl_connect('button_press_event', lambda event: self.knpoint(event, 'D'))
			self.Sknick = self.Scanvas.mpl_connect('button_press_event', lambda event: self.knpoint(event, 'D'))
			
			self.dockwidget.verticalGroupBox.setEnabled(False)			
			self.dockwidget.AllCheckBox.setEnabled(False)
			self.dockwidget.SaveButton.setEnabled(False)	
			self.dockwidget.SaveComboBox.setEnabled(False)				
			self.dockwidget.FileLineEdit.setEnabled(False)	
			self.dockwidget.PathButton.setEnabled(False)	
			self.dockwidget.AddButton.setEnabled(False)	
			
			self.dockwidget.RegButton.setCheckable(False)
			self.dockwidget.DamButton.setCheckable(False)
			
			self.iface.mainWindow().statusBar().showMessage( 'Add Points: Left click / Remove Points: Rigth Click' )		

			try:
				self.dockwidget.RegButton.clicked.disconnect(self.regression)
				self.dockwidget.DamButton.clicked.disconnect(self.remove_dam)
			except:
				None

			self.dockwidget.RegButton.setText('<')
			self.dockwidget.DamButton.setText('>')

			self.Ecanvas.figure.set_tight_layout(False)
			self.Ccanvas.figure.set_tight_layout(False)
			self.Kcanvas.figure.set_tight_layout(False)
			self.Scanvas.figure.set_tight_layout(False)

			self.knick_buttons()
		
		if self.dockwidget.KnickButton.isChecked()==False:
		
			self.Ecanvas.mpl_disconnect(self.Eknick)
			self.Ccanvas.mpl_disconnect(self.Cknick)
			self.Kcanvas.mpl_disconnect(self.Kknick)
			self.Scanvas.mpl_disconnect(self.Sknick)		

			self.dockwidget.verticalGroupBox.setEnabled(True)	
			if len(self.CHs)>1:
				self.dockwidget.AllCheckBox.setEnabled(True)
			self.dockwidget.SaveButton.setEnabled(True)	
			self.dockwidget.SaveComboBox.setEnabled(True)
			self.dockwidget.FileLineEdit.setEnabled(True)	
			self.dockwidget.PathButton.setEnabled(True)	
			self.dockwidget.AddButton.setEnabled(True)	

			self.tabs()

			self.dockwidget.RegButton.setCheckable(True)
			self.dockwidget.DamButton.setCheckable(True)			

			self.iface.mainWindow().statusBar().showMessage( '' )	

			self.dockwidget.RegButton.setText('Regression')			
			self.dockwidget.RegButton.clicked.connect(self.regression)
			self.dockwidget.DamButton.setText('Remove Dam')			
			self.dockwidget.DamButton.clicked.connect(self.remove_dam)

			self.Ecanvas.figure.set_tight_layout(True)
			self.Ccanvas.figure.set_tight_layout(True)
			self.Kcanvas.figure.set_tight_layout(True)
			self.Scanvas.figure.set_tight_layout(True)

	def knpoint(self, event, graphic):
		if event.inaxes:
			if self.simplify == 1:
				if graphic == 'D':
						i = np.abs(list(self.channel.get_d(head=False))- event.xdata).argmin()
				if graphic == 'C':
					i = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()		
				if graphic == 'H':
					i = np.abs(list(self.hypsometric)- event.xdata).argmin()				

			else:
				if graphic == 'D':
					S = list(self.channel.get_d(head=False))[::self.simplify][np.abs(list(self.channel.get_d(head=False))[::self.simplify] - event.xdata).argmin()]			
					i = np.abs(list(self.channel.get_d(head=False)) - S).argmin()	
				if graphic == 'C':
					S = list(self.channel.get_chi())[::self.simplify][np.abs(list(self.channel.get_chi())[::self.simplify] - event.xdata).argmin()]			
					i = np.abs(list(self.channel.get_chi()) - S).argmin()		
					print(S)
				if graphic == 'H':
					S = list(self.hypsometric)[::self.simplify][np.abs(list(self.hypsometric)[::self.simplify] - event.xdata).argmin()]			
					i = np.abs(list(self.hypsometric) - S).argmin()					
			if event.button == 1:
	
				self.CHs[self.graph]._knickpoints.append(i)

			if event.button == 3:
				if len(self.CHs[self.graph]._knickpoints)>0:
					i = np.abs(list(self.CHs[self.graph]._knickpoints) - i).argmin()

					self.CHs[self.graph]._knickpoints.pop(i)


			
			self.rubberknick.reset(QgsWkbTypes.PointGeometry)
			
			self.lay_show('K')

		self.knick_buttons()		

	def knick_move(self, move):
		if self.dockwidget.KnickButton.isChecked()==True:

			# if len(self.CHs[self.graph]._knickpoints) > 0:
			i = self.CHs[self.graph]._knickpoints[-1]
			print(self.channel.get_chi()[i] in self.channel.get_chi()[::self.simplify])
			if (self.channel.get_chi()[i] in self.channel.get_chi()[::self.simplify]) == False:
				S = list(self.channel.get_chi())[::self.simplify][np.abs(list(self.channel.get_chi())[::self.simplify] - self.channel.get_chi()[i]).argmin()]
				i = np.abs(list(self.channel.get_chi()) - S).argmin()	
				print(S)
				
				if (S- self.channel.get_chi()[i]).argmin() < 0:		
					if move == 'R':
						i2 = i
					if move == 'L':
						i2 = i+self.simplify		

				else:
					if move == 'R':
						i2 = i-self.simplify

					if move == 'L':
						i2 = i						
			else:
				if self.dockwidget.tabWidget.currentIndex() == 4:
					if move == 'R':
						if i == ((len(self.channel._zx)//self.simplify)*self.simplify):
							i2 = len(self.channel._zx)-1
						else:
							i2 = i+self.simplify
					if move == 'L':
						if i == len(self.channel._zx)-1 :
							i2 = ((len(self.channel._zx)//self.simplify)*self.simplify)
						else:
							i2 = i-self.simplify	
				else:
					if move == 'L':
						if i == ((len(self.channel._zx)//self.simplify)*self.simplify):
							i2 = len(self.channel._zx)-1
						else:
							i2 = i+self.simplify
					if move == 'R':
						if i == len(self.channel._zx)-1 :
							i2 = ((len(self.channel._zx)//self.simplify)*self.simplify)
						else:
							i2 = i-self.simplify
						
			self.CHs[self.graph]._knickpoints.pop()
			self.CHs[self.graph]._knickpoints.append(i2)
			self.rubberknick.reset(QgsWkbTypes.PointGeometry)

			self.lay_show('K')
			self.knick_buttons()

	def show_knickpoints(self, channel):
		kpoints = channel._knickpoints		
		for kp in kpoints:
			xy = channel.get_xy()[kp]
			self.rubberknick.addPoint(QgsPointXY(xy[0], xy[1]))		
			
			self.Eaxes.plot(self.channel.get_d(head=False)[kp], self.channel.get_z()[kp], color='b', ls='None', marker='x', ms=10)
			# Chi profile
			self.Caxes.plot(self.channel.get_chi()[kp], self.channel.get_z()[kp], color='b', ls='None', marker='x', ms=10)
			# Ksn profile
			self.Kaxes.plot(self.channel.get_d(head=False)[kp], self.channel.get_ksn()[kp],  color='r', ls='None', marker='X', ms=10)
			# # Slope profile
			self.Saxes.plot(self.channel.get_d(head=False)[kp], self.channel.get_slope()[kp]*100,  color='r', ls='None', marker='X', ms=10)

		self.draw_graph()

	def knick_buttons(self):
		if len(self.channel._knickpoints) == 0:
			self.dockwidget.RegButton.setEnabled(False)
			self.dockwidget.DamButton.setEnabled(False)
		else:
			if self.dockwidget.tabWidget.currentIndex() == 4:
				if self.channel._knickpoints[-1] == (len(self.channel._zx)-1):
					self.dockwidget.RegButton.setEnabled(True)
					self.dockwidget.DamButton.setEnabled(False)

				elif self.channel._knickpoints[-1] <= 0:
					self.channel._knickpoints[-1] = 0
					self.dockwidget.RegButton.setEnabled(False)
					self.dockwidget.DamButton.setEnabled(True)	
				else:			
					self.dockwidget.RegButton.setEnabled(True)
					self.dockwidget.DamButton.setEnabled(True)			
			else:
				if self.channel._knickpoints[-1] == 0:
					self.dockwidget.RegButton.setEnabled(True)
					self.dockwidget.DamButton.setEnabled(False)

				elif self.channel._knickpoints[-1] == (len(self.channel._zx)-1):
					self.dockwidget.RegButton.setEnabled(False)
					self.dockwidget.DamButton.setEnabled(True)	
				else:			
					self.dockwidget.RegButton.setEnabled(True)
					self.dockwidget.DamButton.setEnabled(True)
		print(self.channel._knickpoints)

	def regression(self):
		if self.dockwidget.RegButton.isChecked():	
			self.iface.mainWindow().statusBar().showMessage( 'Left Point: Left click / Rigth Point: Rigth Click')	

			self.dockwidget.NextButton.setEnabled(False)
			self.dockwidget.PrevButton.setEnabled(False)
			self.dockwidget.KnickButton.setEnabled(False)
			self.dockwidget.verticalGroupBox.setEnabled(False)			
			self.dockwidget.AllCheckBox.setEnabled(False)
			self.dockwidget.SaveButton.setEnabled(False)	
			self.dockwidget.SaveComboBox.setEnabled(False)				
			self.dockwidget.FileLineEdit.setEnabled(False)	
			self.dockwidget.PathButton.setEnabled(False)	
			self.dockwidget.AddButton.setEnabled(False)	

			try:
				self.dockwidget.DamButton.clicked.disconnect(self.remove_dam)
			except:
				None

			self.dockwidget.DamButton.setText('Remove Reg')
			self.dockwidget.DamButton.setCheckable(False)
			self.dockwidget.DamButton.clicked.connect(self.remove_reg)
			if len(self.CHs[self.graph]._regressions) == 0:
				self.dockwidget.DamButton.setEnabled(False)
			
			
			self.regAct = True
			self.RData = [-1,-1]			
			self.CReg = self.Ccanvas.mpl_connect('button_press_event', self.reg)	
			self.Ccanvas.figure.set_tight_layout(False)	
	
		if self.dockwidget.RegButton.isChecked() == False:	
			self.iface.mainWindow().statusBar().showMessage('')	

			# self.change_graph()
			if self.graph < (len(self.CHs)-1):
				self.dockwidget.NextButton.setEnabled(True)
			if self.graph > 0:
				self.dockwidget.PrevButton.setEnabled(True)

			self.dockwidget.KnickButton.setEnabled(True)
			self.dockwidget.DamButton.setEnabled(True)

			self.dockwidget.verticalGroupBox.setEnabled(True)	
			if len(self.CHs)>1:
				self.dockwidget.AllCheckBox.setEnabled(True)
			self.dockwidget.SaveButton.setEnabled(True)	
			self.dockwidget.SaveComboBox.setEnabled(True)
			self.dockwidget.FileLineEdit.setEnabled(True)	
			self.dockwidget.PathButton.setEnabled(True)	
			self.dockwidget.AddButton.setEnabled(True)	

			self.dockwidget.DamButton.setText('Remove Dam')			
			self.dockwidget.DamButton.clicked.connect(self.remove_dam)
			self.dockwidget.DamButton.setCheckable(True)
			
			
			self.regAct = False

			self.Ccanvas.mpl_disconnect(self.CReg)
			self.Ccanvas.figure.set_tight_layout(True)		
	
	def reg(self, event):
		if event.inaxes:
	
			if event.button == 1:
				self.RData[1] = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()	
			
			if event.button == 3:			
				self.RData[0] = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()	
				
		if (-1 in self.RData):
			for rd in self.RData:
				self.Caxes.plot(self.channel.get_chi()[rd], self.channel.get_z()[rd], color='b', ls='None', marker='|', ms=10)		
			self.draw_graph()
			self.tabs()
				
		if (-1 in self.RData) == False:		
			Sfit = np.polyfit(self.channel.get_chi()[self.RData[0]:self.RData[1]][::-1], self.channel._zx[self.RData[0]:self.RData[1]][::-1] ,1)	
			R =list(Sfit[::-1])
			R.extend((self.channel.get_chi()[self.RData[1]],self.channel.get_chi()[self.RData[0]]))
			self.CHs[self.graph]._regressions.append(R)	
			print(self.CHs[self.graph]._regressions)
			print(str(self.channel._zx[self.RData[0]])+', '+str(self.channel._zx[self.RData[1]]))
			self.RData = [-1,-1]

			self.lay_show('R')

		if len(self.CHs[self.graph]._regressions) == 0:
			self.dockwidget.DamButton.setEnabled(False)
		print(self.RData)

	def remove_reg(self):
		if len(self.CHs[self.graph]._regressions) > 0:
			self.CHs[self.graph]._regressions.pop()
			self.lay_show('R')
			if len(self.CHs[self.graph]._regressions) == 0:
				self.dockwidget.DamButton.setEnabled(False)
		
	def show_reg(self, channel):

		reg = channel._regressions		
		for r in range(len(reg)):
			chi = reg[r][2:4]
			z = []
			for c in chi:
				result = reg[r][0]+reg[r][1]*c
				z.append(result)
			self.Caxes.plot(chi, z, color='b', ls='-', c='0.3', lw=1)	
	def remove_dam(self):
	
		if self.dockwidget.DamButton.isChecked() == True:	
			self.dockwidget.NextButton.setEnabled(False)
			self.dockwidget.PrevButton.setEnabled(False)
			self.dockwidget.verticalGroupBox.setEnabled(False)
			self.dockwidget.KnickButton.setEnabled(False)
			self.dockwidget.AllCheckBox.setEnabled(False)
			self.dockwidget.SaveButton.setEnabled(False)	
			self.dockwidget.SaveComboBox.setEnabled(False)				
			self.dockwidget.FileLineEdit.setEnabled(False)	
			self.dockwidget.PathButton.setEnabled(False)	
			self.dockwidget.AddButton.setEnabled(False)	
			self.dockwidget.RegButton.setEnabled(False)
			self.Data = [-1,-1,-1,-1,-1,-1]
			self.Edam = self.Ecanvas.mpl_connect('button_press_event', lambda event: self.dam(event, 'D'))
			self.Cdam = self.Ccanvas.mpl_connect('button_press_event', lambda event: self.dam(event, 'C'))
			self.iface.mainWindow().statusBar().showMessage( 'Left Point: Left click / Rigth Point: Rigth Click')	
			
			# self.Ecanvas.figure.set_tight_layout(False)
			# self.Ccanvas.figure.set_tight_layout(False)
		
			
		if self.dockwidget.DamButton.isChecked() == False:	
		
			if self.graph < (len(self.CHs)-1):
				self.dockwidget.NextButton.setEnabled(True)
			if self.graph > 0:
				self.dockwidget.PrevButton.setEnabled(True)
		
			self.dockwidget.verticalGroupBox.setEnabled(True)
			self.lay_show('K')
			self.dockwidget.AllCheckBox.setEnabled(True)
			self.dockwidget.SaveButton.setEnabled(True)	
			self.dockwidget.SaveComboBox.setEnabled(True)
			self.dockwidget.FileLineEdit.setEnabled(True)	
			self.dockwidget.PathButton.setEnabled(True)	
			self.dockwidget.AddButton.setEnabled(True)	
			self.Ecanvas.mpl_disconnect(self.Edam)
			self.Ccanvas.mpl_disconnect(self.Cdam)
			self.iface.mainWindow().statusBar().showMessage('')	
			
			# self.Ecanvas.figure.set_tight_layout(True)
			# self.Ccanvas.figure.set_tight_layout(True)

		
	def dam(self, event, graphic):
		if event.inaxes:
	
			if event.button == 1:	
				if graphic == 'D':
					I = np.abs(list(self.channel.get_d(head=False)) - event.xdata).argmin()
				if graphic == 'C':
					I = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()			
				if type(self.Data[3]) == list:
					if I >= self.Data[3][0]:
						self.Data[2] = ([I, self.channel.get_z()[I], self.channel.get_chi()[I], self.channel.get_ksn()[I], self.channel.get_slope()[I], self.channel.get_a()[I]])
						self.Data[1] = ([I+1, self.channel.get_z()[I+1], self.channel.get_chi()[I+1], self.channel.get_ksn()[I+1], self.channel.get_slope()[I+1], self.channel.get_a()[I+1]])
						self.Data[0] = ([I+2, self.channel.get_z()[I+2], self.channel.get_chi()[I+2], self.channel.get_ksn()[I+2], self.channel.get_slope()[I+2], self.channel.get_a()[I+2]])
				else:
					self.Data[2] = ([I, self.channel.get_z()[I], self.channel.get_chi()[I], self.channel.get_ksn()[I], self.channel.get_slope()[I], self.channel.get_a()[I]])
					self.Data[1] = ([I+1, self.channel.get_z()[I+1], self.channel.get_chi()[I+1], self.channel.get_ksn()[I+1], self.channel.get_slope()[I+1], self.channel.get_a()[I+1]])
					self.Data[0] = ([I+2, self.channel.get_z()[I+2], self.channel.get_chi()[I+2], self.channel.get_ksn()[I+2], self.channel.get_slope()[I+2], self.channel.get_a()[I+2]])
				
			if event.button == 3:
				if graphic == 'D':
					D = np.abs(list(self.channel.get_d(head=False)) - event.xdata).argmin()
				if graphic == 'C':
					D = np.abs(list(self.channel.get_chi()) - event.xdata).argmin()		
				if type(self.Data[2]) == list:
					if D <= self.Data[2][0]:
						self.Data[3] = ([D, self.channel.get_z()[D],self.channel.get_chi()[D], self.channel.get_ksn()[D],self.channel.get_slope()[D], self.channel.get_a()[D]])
						self.Data[4] = ([D-1, self.channel.get_z()[D-1],self.channel.get_chi()[D-1], self.channel.get_ksn()[D-1],self.channel.get_slope()[D-1], self.channel.get_a()[D+1]])
						self.Data[5] = ([D-2, self.channel.get_z()[D-2],self.channel.get_chi()[D-2], self.channel.get_ksn()[D-2],self.channel.get_slope()[D-2], self.channel.get_a()[D+2]])

				else:
					self.Data[3] = ([D, self.channel.get_z()[D],self.channel.get_chi()[D], self.channel.get_ksn()[D],self.channel.get_slope()[D], self.channel.get_a()[D]])	
					self.Data[4] = ([D-1, self.channel.get_z()[D-1],self.channel.get_chi()[D-1], self.channel.get_ksn()[D-1],self.channel.get_slope()[D-1], self.channel.get_a()[D+1]])
					self.Data[5] = ([D-2, self.channel.get_z()[D-2],self.channel.get_chi()[D-2], self.channel.get_ksn()[D-2],self.channel.get_slope()[D-2], self.channel.get_a()[D+2]])
					
		self.show_dam()
		if (-1 in self.Data) == False:
			Data = np.array(self.Data)

			Zfit = np.polyfit(Data[:,0], Data[:,1] ,1)
			Zline = np.poly1d(Zfit)
			Cfit = np.polyfit(Data[:,0], Data[:,2] ,1)
			Cline = np.poly1d(Cfit)
			Kfit = np.polyfit(Data[:,0], Data[:,3] ,1)
			Kline = np.poly1d(Kfit)
			Sfit = np.polyfit(Data[:,0], Data[:,4] ,1)
			Sline = np.poly1d(Sfit)
			
			for n in np.arange((int(Data[3,0]+1)),(int(Data[2,0]-1))):
				self.CHs[self.graph]._zx[n] = Zline(n)
				self.CHs[self.graph]._chi[n] = Cline(n)
				self.CHs[self.graph]._ksn[n] = Kline(n)
				self.CHs[self.graph]._slp[n] = Sline(n)
				self.CHs[self.graph]._ax[n] = Hline(n)
				
			self.show_dam()			
			self.Data = [-1,-1,-1,-1,-1,-1]

	def show_dam(self):
		Data = self.Data
		dam = []
		if type(Data[2]) == list:
			dam.append(Data[2][0])
		if type(Data[3]) == list:
			dam.append(Data[3][0])
		self.lay_show('K')
		for d in dam:
			
			self.Eaxes.plot(self.channel.get_d(head=False)[d], self.channel.get_z()[d], color='b', ls='None', marker='|', ms=10)
			# Chi profile
			self.Caxes.plot(self.channel.get_chi()[d], self.channel.get_z()[d], color='b', ls='None', marker='|', ms=10)
			# Ksn profile
			self.Kaxes.plot(self.channel.get_d(head=False)[d], self.channel.get_ksn()[d],  color='r', ls='None', marker='x', ms=10)
			# # Slope profile
			self.Saxes.plot(self.channel.get_d(head=False)[d], self.channel.get_slope()[d]*100,  color='r', ls='None', marker='x', ms=10)
		self.draw_graph()			

	def lay_show(self, show):
		if show == 'C':
			if self.dockwidget.LayCursorCheckBox.isChecked()==False:
				self.rubberpoint.reset(QgsWkbTypes.PointGeometry)
		try:
			if show == 'S':
				if self.dockwidget.LayStreamCheckBox.isChecked():
					for x, y in self.channel.get_xy():
						self.rubberband.addPoint(QgsPointXY(x, y))
				else:
					self.rubberband.reset(QgsWkbTypes.LineGeometry)		
			if show == 'K':
				if self.dockwidget.LayKpCheckBox.isChecked():
					self.clear_graph()
					self.single_channels()
					self.show_knickpoints(self.channel)
					if self.dockwidget.GraphRegCheckBox.isChecked():
						self.show_reg(self.channel)
					self.draw_graph()
					if self.dockwidget.DamButton.isChecked() == False:	
						self.dockwidget.KnickButton.setEnabled(True)
				else:
					self.rubberknick.reset(QgsWkbTypes.PointGeometry)
					self.clear_graph()
					self.single_channels()
					if self.dockwidget.GraphRegCheckBox.isChecked():
						self.show_reg(self.channel)
					self.draw_graph()
					self.dockwidget.KnickButton.setEnabled(False)
			if show == 'R':
				if self.dockwidget.GraphRegCheckBox.isChecked():
					self.clear_graph()
					self.single_channels()
					self.show_reg(self.channel)

					if self.dockwidget.LayKpCheckBox.isChecked():
						self.show_knickpoints(self.channel)
					self.draw_graph()
				else:
					self.rubberknick.reset(QgsWkbTypes.PointGeometry)
					self.clear_graph()
					self.single_channels()
					if self.dockwidget.LayKpCheckBox.isChecked():
						self.show_knickpoints(self.channel)
					self.draw_graph()
					self.dockwidget.KnickButton.setEnabled(False)
			self.tabs()
		except:
			None

	def save (self):
		saved = False
		self.iface.mainWindow().statusBar().showMessage('Saving...')
		format = self.dockwidget.SaveComboBox.currentIndex()
		if format == 0:
			filename, _filter = QFileDialog.getSaveFileName(self.dockwidget, 'Save Channels','', 'NPY files (*.npy)')
			if filename:
				with open(filename, 'wb') as f:
					np.save(f, self.CHs)
				saved = True					
		if format == 1:
			filename, _filter = QFileDialog.getSaveFileName(self.dockwidget, 'Save Channel','', 'DAT files (*.dat)')
			if filename:
				self.CHs[self.graph].save(filename)
				saved = True				
		if format == 2:
			filename, _filter = QFileDialog.getSaveFileName(self.dockwidget, 'Save Knickpoints','', 'ESRI Shapefile (*.shp)')
			if filename:
				channel = self.CHs[self.graph]
				# Create shapefile
				driver = ogr.GetDriverByName('ESRI Shapefile')
				dataset = driver.CreateDataSource(filename)
				sp = osr.SpatialReference()
				sp.ImportFromWkt(channel._proj)
				layer = dataset.CreateLayer('Knickpoints', sp, ogr.wkbPoint)
				
				# Add fields
				campos = ['id', 'z', 'chi', 'ksn', 'rksn', 'slope', 'rslope', 'area']
				tipos = [0, 2, 2, 2, 2, 2, 2, 2]
				id = 0
				for n in range(len(campos)):
					layer.CreateField(ogr.FieldDefn(campos[n], tipos[n]))
				for n in channel._knickpoints:
					id +=1
					feat = ogr.Feature(layer.GetLayerDefn())
					feat.SetField('id', int(id))
					feat.SetField('z', float(channel._zx[n]))
					feat.SetField('chi', float(channel._chi[n]))
					feat.SetField('ksn', float(channel._ksn[n]))
					feat.SetField('rksn', float(channel._R2ksn[n]))
					feat.SetField('slope', float(channel._slp[n]))
					feat.SetField('rslope', float(channel._R2slp[n]))
					feat.SetField('area', float(channel._ax[n]))
					
					# Create geometry
					geom = ogr.Geometry(ogr.wkbPoint)
					geom.AddPoint(channel.get_xy()[n][0], channel.get_xy()[n][1])
					feat.SetGeometry(geom)			
					layer.CreateFeature(feat)				
					print(str(channel.get_xy()[n][0])+ '/' +str(channel.get_xy()[n][1])+ '/' +str(n))	
				saved = True	
		if format >= 3:	
			directory = QFileDialog.getExistingDirectory(self.dockwidget, 'Save Graphics','')	
			if directory:

				kpoints = self.channel._knickpoints	
				reg = channel._regressions		
				
				ElevFig = self.Ecanvas.figure
				ChiFig = self.Ccanvas.figure
				KsnFig = self.Kcanvas.figure
				SlpFig = self.Scanvas.figure
				if format == 3:
					extension = '.png'
				if format == 4:
					extension = '.svg'
				if format == 5:
					extension = '.ps'
				if format == 6:
					extension = '.eps'

				self.dockwidget.tabWidget.setCurrentIndex(0)
				self.tabs()	
				
				try:
					self.Ecanvas.figure.set_tight_layout(False)
					ElevFig.savefig(str(directory)+'/Elev'+extension)
					
					self.Eaxes.clear()
					self.Eaxes.plot(list(self.channel.get_chi()[::self.simplify])+list([self.channel.get_chi()[-1]]), list(self.channel.get_z()[::self.simplify])+list([self.channel.get_z()[-1]]), color='r', ls='-', c='0.3', lw=1)
					self.Eaxes.set_xlim(xmin=min(self.channel.get_chi()), xmax=max(self.channel.get_chi()))
					if self.dockwidget.LayKpCheckBox.isChecked()==True:
						for kp in kpoints:
							self.Eaxes.plot(self.channel.get_chi()[kp], self.channel.get_z()[kp], color='b', ls='None', marker='x', ms=10)
					if self.dockwidget.GraphRegCheckBox.isChecked()==True:	
						for r in range(len(reg)):
							chi = reg[r][2:4]
							z = []
							for c in chi:
								result = reg[r][0]+reg[r][1]*c
								z.append(result)
							self.Caxes.plot(chi, z, color='b', ls='-', c='0.3', lw=1)						
					self.Eaxes.set_xlabel('χ [m]')		
					self.Eaxes.set_ylabel('Elevation [m]')
					self.Ecanvas.draw()
					ElevFig.savefig(str(directory)+'/Chi'+extension)
					
					self.Eaxes.clear()				
					self.Eaxes.plot(list(self.channel.get_d(head=False)[::self.simplify])+list([self.channel.get_d(head=False)[-1]]), list(self.channel.get_ksn()[::self.simplify])+list([self.channel.get_ksn()[-1]]),  color='0', ls='None', marker='.', ms=1)
					self.Eaxes.set_xlim(xmin=0, xmax=max(self.channel.get_d()))				
					if self.dockwidget.LayKpCheckBox.isChecked()==True:
						for kp in kpoints:
							self.Eaxes.plot(self.channel.get_d(head=False)[kp], self.channel.get_ksn()[kp],  color='r', ls='None', marker='X', ms=10)			
					self.Eaxes.set_xlabel('Distance to mouth [m]')
					self.Eaxes.set_ylabel('ksn')
					self.Ecanvas.draw()				
					ElevFig.savefig(str(directory)+'/Ksn'+extension)
					
					self.Eaxes.clear()				
					self.Eaxes.plot(np.array(list(self.channel.get_d(head=False)[::self.simplify])+list([self.channel.get_d(head=False)[-1]])), np.array(list(self.channel.get_slope()[::self.simplify])+list([self.channel.get_slope()[-1]]))*100,  color='0', ls='None', marker='.', ms=1)
					self.Eaxes.set_xlim(xmin=0, xmax=max(self.channel.get_d()))	
					if self.dockwidget.LayKpCheckBox.isChecked()==True:
						for kp in kpoints:
							self.Eaxes.plot(self.channel.get_d(head=False)[kp], self.channel.get_slope()[kp]*100,  color='r', ls='None', marker='X', ms=10)
					self.Eaxes.set_xlabel('Distance to mouth [m]')
					self.Eaxes.set_ylabel('Slope [%]')
					self.Ecanvas.draw()				
					ElevFig.savefig(str(directory)+'/Slope'+extension)
					
					self.change_graph()
					self.Ecanvas.figure.set_tight_layout(True)
					self.tabs()	
					
					saved = True
				except:
					self.change_graph()
					self.Ecanvas.figure.set_tight_layout(True)
					self.tabs()						
		
		if saved == True:
			self.iface.mainWindow().statusBar().showMessage('Saved!')
		else:
			self.iface.mainWindow().statusBar().showMessage('Something went wrong!')			