function getbot init isbot

function getbot init isbot

#region ====INIT ===============================================================
	Func _ConfigInitial()

;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfullPath, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLInsertUserMessage($TweetID,$TweeMsg,$UserID,$Fname,$Lname,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO UserMessages VALUES (' & $TweetID & ',"' & _
		$TweeMsg & '" ,' & $UserID & ',"' & $Fname &"_"& $Lname & '",' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/START -> Activa la recepcion de alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva la recepcion de alertas. '  & $nuevaLinea
		$message&='/INFO -> Muestra este mensage'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Comandos:'  & $nuevaLinea
		$message&='/ACTIVAR A B -> Recepcion de alertas de la Linea A, B (C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/DESACTIVAR A B -> Recepcion de alertas de la Linea A, B (C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/ESTACIONES A -> lista de estaciones de la linea A( B, C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/HORARIOS  -> Horarios de actividad'  & $nuevaLinea
		$message&='/MAPA  -> Mapa de lineas de subte'  & $nuevaLinea
		$message&='/PROPUESTA propuesta -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $respuestaInitialMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTOPMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTARTMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramBaseMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="No logro entender el mensaje."
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded",$DisableNotification=True)
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		If $DisableNotification = True Then $urlMSG &= "&disable_notification=True"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc
#endregion
#region  ==== Tweeter scrapping ===================================================================
	Func TweeterMessages($Username)
		ConsoleWrite('++TweeterMessages() = '& $Username &@crlf)
		$htmltxt=_ScrapTweetMessages($Username)
		if $htmltxt<>"" then
			$TweetArr = _gettweetArr($htmltxt)
			if IsArray($TweetArr) then
				$newMessagesFlag=0
				_ArraySort($TweetArr, 0, 0, 0, 2)
				For $i = 0 To UBound($TweetArr) -1
					$TweetID = $TweetArr[$i][0]
					$TweeMsg = $TweetArr[$i][1]
					$TweeDate = $TweetArr[$i][2]
					if not SQLExist_Message($TweetID) then
						SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
						$TweetMinOld= (_GetUnixTime() - $TweeDate)/60
						if $TweetMinOld < 60 then
							sendmessages($TweeMsg)
							$newMessagesFlag=1
							ConsoleWrite('+ New messages ' & _NowTime(4) & "   ")
						Else
							ConsoleWrite('+ Old messages ' & $TweetMinOld & "   ")
						endif
					endif
					sleep(2000)
				Next
				if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
			endif
		endif
	EndFunc
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
;~ 	Func isbot($jsonObj)
;~ 		ConsoleWrite('++isbot() = '& @crlf)
;~ 		$res = StripStrJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $res = ' & $res & @crlf )
;~ 		return $res
;~ 	EndFunc

	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&'  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			$s=ParseForUserUpdate($s)
			ConsoleWrite('@@ $s = ' & $s & @crlf )
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						$IsBot =       StripIntJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())
						if $UserIDArr[0] = $UpdateIDArr[0] AND  $UserIDArr[0] = $FnameArr[0] AND _
							$UserIDArr[0] = $LnameArr[0]    AND  $UserIDArr[0] = $epochArr[0] AND _
							$UserIDArr[0] = $menssageArr[0] AND  $UserIDArr[0] = $IsBot[0]  then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								if $IsBot[$i] <> "true" then
									$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
									$ret1=ParseBotMessage($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i],$UpdateIDArr[$i])
									ConsoleWrite('>> $ret1 = ' & $ret1 & @crlf )
									if (Not $ret) or (Not $ret1)  then	$retBad+=1
									$UpdateID=$UpdateIDArr[$i]
								Else
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $menssageArr[$i] = ' & $menssageArr[$i] & @crlf )
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $IsBot[$i] = ' & $IsBot[$i] & @crlf )
									$retBad=1
								endif
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($UserIDArr,"UserIDArr")
							_printFromArray($FnameArr,"FnameArr")
							_printFromArray($LnameArr,"LnameArr")
							_printFromArray($epochArr,"epochArr")
							_printFromArray($menssageArr,"menssageArr")
							_printFromArray($UpdateIDArr,"UpdateIDArr")
							_printFromArray($IsBot,"IsBot")
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
;~ 		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="  Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
;~ 		if StringInStr($s,'"location":') Then
;~ 			$s='{"ok":true,"result":[]}'
;~ 			return $s
;~ 		endif
;~ 		eliminate location info
;~ "location":{"latitude":-34.631010,"longitude":-58.469731}}
		$s=StringRegExpReplace($s,'(?s)(?i)"location":{"latitude":(.*?),"longitude":(.*?)}'  ,  '"text": ""' )
;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )
;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')
;~ 		eliminate sticker info
		$s=StringRegExpReplace($s,'(?s)(?i)"sticker":(.*?)}(.*?)}'  ,  '"text": ""' )
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
	;~   _ArrayDisplay($array1)
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion

#region ====INIT ===============================================================
	Func _ConfigInitial()

;~ 		ConsoleWrite('++ConfigDBInitial() = ' & @CRLF)
		_SQLite_down()
;~ 		_DBvarInit()
		; -------check if SQLIte SubteBA db exist
		SQLite_init()
		$SQLq = "SELECT name FROM sqlite_temp_master WHERE type='table';"
		_SQLITErun($SQLq, $dbfullPath, $quietSQLQuery)
	;~ 	;-------- Init Log
	;~ 	_initLog()
		;------------------------------------------------------------------------------
	EndFunc   ;==>_ConfigDBInitial
#endregion
#region  ==== SQL functions =======================================================================
	Func SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO messages VALUES (' & $TweetID & ',"' & $TweeMsg & '" ,' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLInsertUserMessage($TweetID,$TweeMsg,$UserID,$Fname,$Lname,$TweeDate)
;~ 		ConsoleWrite('++InsertMessageSQL() = '& @crlf)
		$query='INSERT INTO UserMessages VALUES (' & $TweetID & ',"' & _
		$TweeMsg & '" ,' & $UserID & ',"' & $Fname &"_"& $Lname & '",' & $TweeDate & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting mesages ErrNo 1010" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLGetUsers()
;~ 		ConsoleWrite('++SQLGetUsers() = '& @crlf)
		$query='SELECT * FROM Users ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetActiveUsers()
;~ 		ConsoleWrite('++SQLGetActiveUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLGetDevUsers()
;~ 		ConsoleWrite('++SQLGetDevUsers() = '& @crlf)
		$query='SELECT * FROM Users WHERE Active=1 AND Dev=1 ;'
		_SQLITEqry($query,$dbfullPath)
	EndFunc
	Func SQLExist_Message($TweetID)
;~ 		ConsoleWrite('++Exist_Message() = '&$TweetID& @crlf)
		$query='SELECT id FROM messages WHERE id="'&$TweetID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region  ==== send messages =======================================================================
;~  	Func sendmessages($message)  ;~ from file of recipients
;~ 		Local $fileh = FileOpen("secret\recipients.txt", 0)
;~ 		If $fileh = -1 Then
;~ 			Exit 26
;~ 		EndIf
;~ 		While 1
;~ 			Local $chatidLine = FileReadLine($fileh)
;~ 			If @error = -1 Then ExitLoop
;~ 			$chatidArr = StringSplit($chatidLine, ',')
;~ 			$chatid = $chatidArr[1]
;~ 			if $chatID<>"" then
;~ 				ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $chatidArr[2] & @CRLF)
;~ 				$respuesta = SendTelegramexec($chatid,$message)
;~ 			$respuesta  0 is ok
;~ 			endif
;~ 		WEnd
;~ 		FileClose($fileh)
;~ 	EndFunc   ;==>_sendmessages
	Func TelegramInitialMessage($UserID)
;~ 	ConsoleWrite('++TelegramInitialMessage() = '& @crlf)
		$message ="SubteBA BOT , lee los informes de Subte BA en Twitter, y los manda por este canal. "
		$message&='Este canal no es official del subte de Buenos Aires Ni de Metrovias.'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Commandos:'  & $nuevaLinea
		$message&='/START -> Activa la recepcion de alertas. '  & $nuevaLinea
		$message&='/STOP  -> Desactiva la recepcion de alertas. '  & $nuevaLinea
		$message&='/INFO -> Muestra este mensage'  & $nuevaLinea
		$message&= $nuevaLinea
		$message&='Futuros Comandos:'  & $nuevaLinea
		$message&='/ACTIVAR A B -> Recepcion de alertas de la Linea A, B (C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/DESACTIVAR A B -> Recepcion de alertas de la Linea A, B (C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/ESTACIONES A -> lista de estaciones de la linea A( B, C, D, E, H, P, U)'  & $nuevaLinea
		$message&='/HORARIOS  -> Horarios de actividad'  & $nuevaLinea
		$message&='/MAPA  -> Mapa de lineas de subte'  & $nuevaLinea
		$message&='/PROPUESTA propuesta -> Enviar propuestas'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $respuestaInitialMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTOPMessage($UserID)
		$message ="Los mensajes de alertas han sido deshabilitados" & $nuevaLinea
		$message&='/START -> Para habilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTOPMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramSTARTMessage($UserID)
		$message ="Los mensajes de alertas han sido habilitados" & $nuevaLinea
		$message&='/STOP-> Para deshabilitar la recepcion de alertas'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramSTARTMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramErrorMessage($UserID)
		$message ="No se ha registrado el cambio requerido." & $nuevaLinea
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'  & $nuevaLinea

		$respuesta = SendTelegramexec($UserID,$message)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func TelegramBaseMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		$message ="No logro entender el mensaje."
		$message&='Reintente enviar el comando nuevamente.'  & $nuevaLinea
		$message&='INFO -> para mas informacion.'& $nuevaLinea & $nuevaLinea
		$message&="Su mensage:" & $nuevaLinea & $USRmsg
		$respuesta = SendTelegramexec($UserID,$message)
		SQLInsertUserMessage($TweetID,$USRmsg,$UserID,$Fname,$Lname,$epoch)
		return $respuesta
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : TelegramErrorMessage = ' & $respuesta & @crlf )
	EndFunc
	Func ReformatMessage($message)
;~ 	ConsoleWrite('++ReformatMessage() = '& @crlf)
		$msgArr=StringSplit($message,"Actualizado",1)
		$diaHoraArr=stringsplit(StringStripWS($msgArr[2],1+2)," ")
		$hora=$diaHoraArr[2]
		$dia=$diaHoraArr[1]
		$msg=""&$hora&""&"     " & $dia & $nuevaLinea & StringStripWS($msgArr[1],1+2)
		return $msg
	EndFunc
	Func sendmessages($message)
		$message=ReformatMessage($message)
		SQLGetActiveUsers()
		If  IsArray($qryResult) Then
			for $i=1 to UBound($qryResult)-1
				$isDev = $qryResult[$i][4]
				$chatid = $qryResult[$i][0]
				$ChatUser = $qryResult[$i][1] & " " & $qryResult[$i][2]
				if $chatID<>"" then
					select
						Case $SendToAll = 1
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
						Case $isDev = 1 AND $SendToAll = 0
							ConsoleWrite('- $chatid = ' & $chatid & "  ->  " & $ChatUser & @CRLF)
							$respuesta = SendTelegramexec($chatid,$message)
					endSelect
					;~ $respuesta  0 is ok
				endif
			next
			return true
		endif
		Return false
	EndFunc   ;==>_sendmessages
	Func SendTelegramexec($chatid,$msgtext="testeo harcoded",$DisableNotification=True)
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		If $DisableNotification = True Then $urlMSG &= "&disable_notification=True"
		$sGet = HttpGet($urlMSG)

		if $sget<>"0"  then
			ConsoleWrite('Tlgm sent = ' & $msgtext & @crlf )
			return 0
		Else
			$s_text="Error sending message to Telegram = " & $sGet
			ConsoleWrite('!! ' & $s_text & @crlf )
			return 1
		endif
	EndFunc
#endregion
#region  ==== Tweeter scrapping ===================================================================
	Func TweeterMessages($Username)
		ConsoleWrite('++TweeterMessages() = '& $Username &@crlf)
		$htmltxt=_ScrapTweetMessages($Username)
		if $htmltxt<>"" then
			$TweetArr = _gettweetArr($htmltxt)
			if IsArray($TweetArr) then
				$newMessagesFlag=0
				_ArraySort($TweetArr, 0, 0, 0, 2)
				For $i = 0 To UBound($TweetArr) -1
					$TweetID = $TweetArr[$i][0]
					$TweeMsg = $TweetArr[$i][1]
					$TweeDate = $TweetArr[$i][2]
					if not SQLExist_Message($TweetID) then
						SQLInsertMessage($TweetID,$TweeMsg,$TweeDate)
						$TweetMinOld= (_GetUnixTime() - $TweeDate)/60
						if $TweetMinOld < 60 then
							sendmessages($TweeMsg)
							$newMessagesFlag=1
							ConsoleWrite('+ New messages ' & _NowTime(4) & "   ")
						Else
							ConsoleWrite('+ Old messages ' & $TweetMinOld & "   ")
						endif
					endif
					sleep(2000)
				Next
				if $newMessagesFlag=0 then ConsoleWrite('  No new messages ' & _NowTime(4) & @CRLF)
			endif
		endif
	EndFunc
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@ BytesRead = ' & $nBytesRead &"   ")
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100000 or StringInStr($htmltxt,"subteba")<1 Then
			ConsoleWrite('  Connection issue contacting  ' & "https://twitter.com/"&$Username& @crlf)
			$htmltxt=""
			Return $htmltxt
		endif
		return $htmltxt
	EndFunc
	Func _gettweetArr($htmltxt)
		$MSGArr = StringRegExp($htmltxt, '(?s)(?i)
(.*?)
', 3)
		if IsArray($MSGArr) then
			dim  $TweetMSGArr[UBound($MSGArr)]
			For $i = 0 To UBound($MSGArr) -1
				$TweetMessage = StringRegExp($MSGArr[$i], '(?s)(?i)
(.*?)
', 1)
				$mensaje = clearstring($TweetMessage[1])
				$TweetMSGArr[$i]=$mensaje
			Next
			$TweetDate = StringRegExp($htmltxt, '(?s)(?i)data-time="(.*?)"', 3)
			$TweetIDArr = StringRegExp($htmltxt, '(?s)(?i)data-tweet-id="(.*?)"', 3)
			$TweetArrAux = _mergeArray($TweetIDArr, $TweetMSGArr)
			$TweetArr = _mergeArray($TweetArrAux, $TweetDate)
	;~ 		_ArrayDisplay($TweetArr)
			return $TweetArr
		Else
			ConsoleWrite('!!!(' &  @ScriptLineNumber & ') : Error on  $MSGArr = ' & $MSGArr & @crlf )
			return 0
		endif
	EndFunc
#endregion
#region  ==== Bot Messages handeling ===================================================================
;~ 	Func isbot($jsonObj)
;~ 		ConsoleWrite('++isbot() = '& @crlf)
;~ 		$res = StripStrJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())
;~ 		ConsoleWrite('@@(' & @ScriptLineNumber & ') : $res = ' & $res & @crlf )
;~ 		return $res
;~ 	EndFunc

	Func Get_BotOffSet()
;~ 		ConsoleWrite('++Get_BotOffSet() = '& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 1.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,0)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 2.' & $OffsetFile )
			return 0
		endif
		Local $offset = FileReadLine($fileh)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("Get OffSet:"& $offset)
		FileClose($fileh)
		return $offset
	EndFunc
	Func Set_BotOffSet($offset)
		ConsoleWrite('++Set_BotOffSet() = '&$offset& @crlf)
		if NOT FileExists($OffsetFile) then
			$fileh = FileOpen($OffsetFile,1+8)
			If $fileh = -1 Then
				ConsoleWrite('   "Unable to open file 3.' & $OffsetFile )
				return 0
			endif
			FileClose($fileh)
		EndIf
		$fileh = FileOpen($OffsetFile,2)
		If $fileh = -1 Then
			ConsoleWrite('   "Unable to open file 4.' & $OffsetFile )
			return 0
		endif
		FileWriteLine($fileh,$offset)
		if @error = -1 Then
			FileClose($fileh)
			return 0
		endif
		ConsoleWrite("    Set OffSet:"& $offset &@crlf)
		FileClose($fileh)
		return 1
	EndFunc
	func UpdateUsers()
		ConsoleWrite('  '&@HOUR & ':' & @MIN&'  Update users.  ' )
		local $s=GetBotUpdates()
		if $s then
			$s=ParseForUserUpdate($s)
			ConsoleWrite('@@ $s = ' & $s & @crlf )
			if $s then
				$oJSON = _OO_JSON_Init()
				$jsonObj = $oJSON.parse($s)
				if $jsonObj.ok  then
					if $jsonObj.jsonPath( "$.result").stringify() = "[[]]" then
						ConsoleWrite(' No Bot data ' & @crlf)
					Else
						ConsoleWrite('  Updating... ' & @crlf)
						$UpdateIDArr = StripIntJS($jsonObj.jsonPath( "$.result..update_id").stringify()  )
						$UserIDArr =   StripIntJS($jsonObj.jsonPath( "$.result..message.from.id").stringify())
						$FnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.first_name").stringify())
						$LnameArr =    StripStrJS($jsonObj.jsonPath( "$.result..message.from.last_name").stringify())
						$epochArr =    StripIntJS($jsonObj.jsonPath( "$.result..message.date").stringify())
						$menssageArr = StripStrJS($jsonObj.jsonPath( "$.result..message.text").stringify())
						$IsBot =       StripIntJS($jsonObj.jsonPath( "$.result..message.from.is_bot").stringify())
						if $UserIDArr[0] = $UpdateIDArr[0] AND  $UserIDArr[0] = $FnameArr[0] AND _
							$UserIDArr[0] = $LnameArr[0]    AND  $UserIDArr[0] = $epochArr[0] AND _
							$UserIDArr[0] = $menssageArr[0] AND  $UserIDArr[0] = $IsBot[0]  then
							$retBad=0
							for $i=1 to $UserIDArr[0]
								if $IsBot[$i] <> "true" then
									$ret=SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i])
									$ret1=ParseBotMessage($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i],$menssageArr[$i],$UpdateIDArr[$i])
									ConsoleWrite('>> $ret1 = ' & $ret1 & @crlf )
									if (Not $ret) or (Not $ret1)  then	$retBad+=1
									$UpdateID=$UpdateIDArr[$i]
								Else
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $menssageArr[$i] = ' & $menssageArr[$i] & @crlf )
									ConsoleWrite('+(' & @ScriptLineNumber & ') : $IsBot[$i] = ' & $IsBot[$i] & @crlf )
									$retBad=1
								endif
							next
							if $retBad=0 then Set_BotOffSet($UpdateID+1)
						Else
							_printFromArray($UserIDArr)
							_printFromArray($FnameArr)
							_printFromArray($LnameArr)
							_printFromArray($epochArr)
							_printFromArray($menssageArr)
							ConsoleWrite('  Error in JS array . exiting..... ' & @crlf)
							exit 29
						endif
					endif
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$offset=Get_BotOffSet()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates?offset="&$offset
		$sGet = HttpGetJson1($urlMSG)
;~ 		ConsoleWrite('@@ $sGet = ' & $sGet & @crlf )
		if $sGet<>"" then
			return $sGet
		Else
			$s_text="  Error getUpdates from Telegram = "
			ConsoleWrite('!! ' & $s_text & @crlf & "! " & $sGet)
			return false
		endif
	EndFunc
	Func StripStrJS($st)
		$st=StringReplace($st,'","',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func StripIntJS($st)
		$st=StringReplace($st,',',":::")
		$st=clearstring($st)
		$st=StringReplace($st,"[","")
		$st=StringReplace($st,"]","")
		$st=StringReplace($st,'"',"")
		$stArr=StringSplit($st,":::",1)
		return $stArr
	EndFunc
	Func ParseForUserUpdate($s)
;~ 		if StringInStr($s,'"location":') Then
;~ 			$s='{"ok":true,"result":[]}'
;~ 			return $s
;~ 		endif
;~ 		eliminate location info
;~ "location":{"latitude":-34.631010,"longitude":-58.469731}}
		$s=StringRegExpReplace($s,'(?s)(?i)"location":{"latitude":(.*?),"longitude":(.*?)}'  ,  '"text": ""' )
;~ 		eliminate contact info
		$s=StringRegExpReplace($s,'(?s)(?i)"contact":(.*?)}'  ,  '"text": ""' )
;~ 		replace username last-name
		$s=StringReplace($s,'"username":','"last_name":')
;~ 		eliminate sticker info
		$s=StringRegExpReplace($s,'(?s)(?i)"sticker":(.*?)}(.*?)}'  ,  '"text": ""' )
		return $s
	EndFunc
	Func SQLregister($UserID,$Fname,$Lname,$epoch,$mensage)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		$existUser=0
		If SQLExistUser($UserID)=$userID then $existUser=1
		if $existUser=0 then
			$setactive=1
			$ret=SQLInsertUser($UserID,$Fname,$Lname,$epoch,$setactive)
			if $ret then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			else
				$ret=TelegramErrorMessage($UserID)
				if $ret=0 then return true
			endif
			return false
		endif

		$setactive=-1
		if AIMessage($mensage,"/START") then $setactive=1
		if AIMessage($mensage,"/STOP") then $setactive=0
		if $existUser=1 AND $setactive<>-1 then
			$ret=SQLUpdateUserActive($UserID,$Fname,$Lname,$setactive)
			if $ret and $setactive=0 then
				$ret=TelegramSTOPMessage($UserID)
				if $ret=0 then return true
			endif
			if $ret and $setactive=1 then
				$ret=TelegramSTARTMessage($UserID)
				if $ret=0 then return true
			endif
			if NOT $ret then TelegramErrorMessage($UserID)
			return false
		endif

		return true
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch,$active=1)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",' & $active &',0,' & $epoch & ') ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			MsgBox(48+4096,"Error inserting User ErrNo 1011" & @CRLF & $query,0,0)
			Return false
		EndIf
	EndFunc
	Func SQLUpdateUserActive($UserID,$Fname,$Lname,$active=1)
		ConsoleWrite('    Usuario Activo 1/Start 0/Stop= '&$active& "  " & $Fname & "  "  & $Lname  & @crlf)
		$query='UPDATE  Users SET Active=' & $active &' WHERE UserID='& $UserID & ' ;'
		if _SQLITErun($query,$dbfullPath,$quietSQLQuery) Then
			return true
		Else
			ConsoleWrite("       Error updating active user User ErrNo 1012" & @CRLF & $query& @crlf)
			Return false
		EndIf
	EndFunc
	Func SQLExistUser($UserID)
;~ 	ConsoleWrite('++SQLExistUser() = '& @crlf)
		$query='SELECT UserID FROM Users WHERE UserID="'&$UserID &'";'
		_SQLITEqry($query,$dbfullPath)
		If  IsArray($qryResult) Then
			if UBound($qryResult)>1 then
				return $qryResult[1][0]
			EndIf
			return 0
		endif
		Return 0
	EndFunc
#endregion
#region   ===========================================================================
	func closeall()
		_SQLite_Close()
		_SQLite_Shutdown()
		exit 30
	EndFunc
#endregion
#region =====================================   Helpers functions  ===============================
	Func _mergeArray($array1, $array2)
		$array1 = _ArrayAdd_Column($array1)
		$size = UBound($array1)
		$newCol = UBound($array1, 2) - 1
		For $i = 0 To $size - 1
			$array1[$i][$newCol] = $array2[$i]
		Next
	;~   _ArrayDisplay($array1)
		Return $array1
	EndFunc   ;==>_mergeArray
	Func _ArrayAdd_Column($Array)
		Local $aTemp[UBound($Array)][UBound($Array, 0) + 1]
		For $i = 0 To UBound($Array) - 1

			For $j = 0 To UBound($Array, 0) - 1
				If UBound($Array, 0) = 1 Then $aTemp[$i][0] = $Array[$i]
				If UBound($Array, 0) > 1 Then $aTemp[$i][$j] = $Array[$i][$j]
			Next
		Next
		Return $aTemp
	EndFunc   ;==>_ArrayAdd_Column
	Func _ClearSciteConsole()
		ConsoleWrite('!!!!!!!!!!!_ClearSciteConsole Func General 92!!!!!!!!!!!!  ' & @CRLF)
		ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")
	EndFunc   ;==>_ClearSciteConsole
	Func _GetDOSOutput($sCommand)
	 ConsoleWrite('++_GetDOSOutput $sCommand = ' & $sCommand & @crlf )
		Local $iPID, $sOutput = ""
		$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, 2 + 4)
		While 1
			$sOutput &= StdoutRead($iPID, False, False)
			$err=@error
			If $err Then
				ConsoleWrite('!!  _GetDOSOutput $err = ' & $err & @crlf )
				ExitLoop
			EndIf
	;~ 	Sleep(10)
		WEnd
		ConsoleWrite('>> 	Output = ' & $sOutput & @crlf )
		Return $sOutput
	EndFunc   ;==>_GetDOSOutput
	Func _timeBetween($cTime, $sTime, $eTime)
		 If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
		 If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
		 If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & @CRLF)
		 ;~  ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & @CRLF)
		 If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
			 _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
			  Return 1
		 Else
			  Return 0
		 EndIf
	EndFunc  ; ==>_timeBetween
#endregion
#region time
	Func  Sec2Time($nr_sec)
		$sec2time_hour = Int($nr_sec / 3600)
		$sec2time_min = Int(($nr_sec - $sec2time_hour * 3600) / 60)
		$sec2time_sec = $nr_sec - $sec2time_hour * 3600 - $sec2time_min * 60
		Return StringFormat('%02d:%02d:%02d', $sec2time_hour, $sec2time_min, $sec2time_sec)
	EndFunc   ;==>Sec2Time
	Func _GetUnixTime($sDate = 0);Date Format: 2013/01/01 00:00:00 ~ Year/Mo/Da Hr:Mi:Se
		Local $aSysTimeInfo = _Date_Time_GetTimeZoneInformation()
		Local $utcTime = ""
		If Not $sDate Then $sDate = _NowCalc()
		If Int(StringLeft($sDate, 4)) < 1970 Then Return ""
		If $aSysTimeInfo[0] = 2 Then
			$utcTime = _DateAdd('n', $aSysTimeInfo[1] + $aSysTimeInfo[7], $sDate)
		Else
			$utcTime = _DateAdd('n', $aSysTimeInfo[1], $sDate)
		EndIf
		Return _DateDiff('s', "1970/01/01 00:00:00", $utcTime)
	EndFunc   ;==>_GetUnixTime
#endregion


Update GuiCreateEx_Example.au3

Update GuiCreateEx_Example.au3

#include-once
#include <Array.au3>
#include <GUIConstantsEx.au3>

OnAutoItExitRegister("_GUICreateEx_OnExit")

Opt("GUIOnEventMode", 1)
Opt("GUIEventOptions", 1)
Opt("MustDeclareVars", 1)

Global $g__aGuiCreateEx[1] = [0]

#cs
; Example
#include-once
#include <GuiCreateEx.au3>

Global $hGui
Global $hButton_NewGui

$hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", 800, 600)
$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func NewGui()
	Local $aSize = WinGetPos($g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	Local $hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", $aSize[2] - (20 + 6), $aSize[3] - (40 + 5), $aSize[0] + 10, $aSize[1] + 10, Default, Default, $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
	GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
	GUISetState(@SW_SHOW, $hGui)
EndFunc   ;==>NewGui
#ce

; #FUNCTION# ====================================================================================================================
; Name...........:	GUICreateEx
; Description ...:	Allow create a new GUI (Graphic User Interface) above current GUI and lock previus GUI
; Syntax.........:	same way of GuiCreate
; Parameters ....:	$sTitle.......: Title's GUI
;					$iWidth.......:	width's GUI
;					$iHeight......: height's GUI
;					$iLeft........:	left position's GUI
; 					$iTop.........: top position's GUI
;					$mStyle.......:	Style's GUI
;					$mExStyle.....:	Extended Style's GUI
;					$iParent......: The handle of another previously created window
; Return values .:	a windows handle
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Remarks .......:
; Related .......:
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; Example .......:
; ===============================================================================================================================
Func GUICreateEx($sTitle = "", $iWidth = 460, $iHeight = 360, $iLeft = -1, $iTop = -1, $mStyle = Default, $mExStyle = Default, $iParent = 0)
	If Not $g__aGuiCreateEx[0] Then
		$iParent = 0
	Else
		$iParent = $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1]
		GUISetState(@SW_DISABLE, $iParent)
	EndIf
	Local $hGui = GUICreate($sTitle, $iWidth, $iHeight, $iLeft, $iTop, $mStyle, $mExStyle, $iParent)
	If @error Then Return SetError(1, 0, 0)
	GUISetOnEvent($GUI_EVENT_CLOSE, "_GUICreateEx_Quit")
	_ArrayAdd($g__aGuiCreateEx, $hGui)
	$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	Return $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
EndFunc   ;==>GUICreateEx

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_OnExit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_OnExit()
	GUISetState($g__aGuiCreateEx[1], @SW_HIDE)
	GUIDelete($g__aGuiCreateEx[1])
EndFunc   ;==>_GUICreateEx_OnExit

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........:	_GUICreateEx_Quit
; Author ........:	Luismar Chechelaky
; Modified.......:	2015/06/20 11:25
; Link ..........:	https://github.com/chechelaky/AutoIt/raw/master/GuiCreateEx/GuiCreateEx.au3
; ===============================================================================================================================
Func _GUICreateEx_Quit()
	Local $hGui
	Switch $g__aGuiCreateEx[0]
		Case 1
			$hGui = $g__aGuiCreateEx[$g__aGuiCreateEx[0]]
			Exit
		Case Else
			GUISetState(@SW_ENABLE, $g__aGuiCreateEx[$g__aGuiCreateEx[0] - 1])
			GUISetState($g__aGuiCreateEx[$g__aGuiCreateEx[0]], @SW_HIDE)
			GUIDelete($g__aGuiCreateEx[$g__aGuiCreateEx[0]])
			_ArrayDelete($g__aGuiCreateEx, UBound($g__aGuiCreateEx, 1) - 1)
			$g__aGuiCreateEx[0] = UBound($g__aGuiCreateEx, 1) - 1
	EndSwitch
EndFunc   ;==>_GUICreateEx_Quit

#include-once
#include <GuiCreateEx.au3> ; https://github.com/chechelaky/AutoIt/blob/master/GuiCreateEx/GuiCreateEx.au3

Global $hGui
Global $hButton_NewGui

$hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", 800, 600)
$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
GUISetState(@SW_SHOW, $hGui)

While Sleep(25)
WEnd

Func NewGui()
	Local $aSize = WinGetPos($g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	Local $hGui = GUICreateEx("Título[ " & $g__aGuiCreateEx[0] & " ]", $aSize[2] - (20 + 6), $aSize[3] - (40 + 5), $aSize[0] + 10, $aSize[1] + 10, Default, Default, $g__aGuiCreateEx[UBound($g__aGuiCreateEx, 1) - 1])
	$hButton_NewGui = GUICtrlCreateButton("new gui", 10, 10, 80, 20)
	GUICtrlSetOnEvent($hButton_NewGui, "NewGui")
	GUISetState(@SW_SHOW, $hGui)
EndFunc   ;==>NewGui


initlog files

initlog files

#region working files
	global $WorkingFolder=@ScriptDir
	global $FolderResources=$WorkingFolder&"\resources"
	if NOT FileExists($FolderResources) then DirCreate($FolderResources)
	global $FolderBin=$WorkingFolder&"\bin"
	if NOT FileExists($FolderBin) then DirCreate($FolderBin)
	if @Compiled then
		global $configPath="config.ini"
	Else
		global $configPath="secret\config.ini"
	endif
	ConsoleWrite('<<   Config: '&$configPath & @crlf )
	global $OffsetFile=$FolderResources&"\OffSet.txt"
	global $LogFileActivity="SubteBA.log"
	global $hLogFile=0
#endregion working files
#region sqlite
	func _DBvarInit()
		global $qryResult=""
		global $quietSQLQuery = 1
		global $dbfile ="SubteBA.db"
		global $dbfullPath = $FolderResources & "\" & $dbfile
		ConsoleWrite('<<   DataBase: '&$dbfullPath & @crlf )
		global $sqliteDLLfile="System.Data.SQLite.32.2012.dll"
		global $sSQliteDll =""
		Global $EncryptDB=0
	endfunc
#endregion sqlite
#region Send Telegram msg
	global $nuevaLinea="%0A"
	Dim $MsgClass[5] ;ClaseMensage,
	Func InitMsgClass()
		for $u=0 to UBound($MsgClass)-1
			$MsgClass[$u]=""
		next
	EndFunc
	global $msgToAllSecuence=IniRead($configPath,"Messaging","msgToAllSecuence","xxxxx")
#endregion
#region Telegram Bot
	global $DEVChatID = IniRead($configPath,"dev","chatID","00000000")
	global $BOT_ID = IniRead($configPath,"botUDF","BotID","00000000")
	global $BotToken = IniRead($configPath,"botUDF","BotToken","00000000")
	global $token=IniRead($configPath,"bot","token","")
#endregion
#region Tweeter reads
	global $StartTimeScrap=IniRead($configPath,"Times","StartTimeScrapHH:MM","00:00")
	global $EndTimeScrap=IniRead($configPath,"Times","EndTimeScrapHH:MM","23:59")
		ConsoleWrite('<<   Tweeter Scrap Time '& $StartTimeScrap & "  To "  & $EndTimeScrap )

	global $TweeterScrapMin=IniRead($configPath,"Times","TweeterScrapMin","5")
		ConsoleWrite(' //  Tweeter Scrap every Min ' & Sec2Time($TweeterScrapMin*60 ) & @CRLF)
	global $TweeterScrapMsec=$TweeterScrapMin*60*1000
#endregion
#region GetUpdates
	global $StartTimeBot=IniRead($configPath,"Times","StartTimeBotHH:MM","00:00")
	global $EndTimeBot=IniRead($configPath,"Times","EndTimeBotHH:MM","23:59")
		ConsoleWrite('<<   TlgmBot Scrap Time '& $StartTimeBot & "  To "  & $EndTimeBot )

	global $GetUpdateTimeSec=IniRead($configPath,"Times","BotUpdateTimeSec","10")
		ConsoleWrite('//  Telegram GetUpdates every Sec ' & Sec2Time($GetUpdateTimeSec) & @crlf )
	global $GetUpdateTimeMsec=$GetUpdateTimeSec*1000
	global $ahora=1
	global $KeyBoardActive=0
	global $KeyboardCheckcount=0
#endregion
_DBvarInit()

#region working files
	global $WorkingFolder=@ScriptDir
	global $FolderResources=$WorkingFolder&"\resources"
	if NOT FileExists($FolderResources) then DirCreate($FolderResources)
	global $FolderBin=$WorkingFolder&"\bin"
	if NOT FileExists($FolderBin) then DirCreate($FolderBin)
	if @Compiled then
		global $configPath="config.ini"
	Else
		global $configPath="secret\config.ini"
	endif
	ConsoleWrite('<<   Config: '&$configPath & @crlf )
	global $OffsetFile=$FolderResources&"\OffSet.txt"
#endregion working files
#region sqlite
	func _DBvarInit()
		global $qryResult=""
		global $quietSQLQuery = 1
		global $dbfile ="SubteBA.db"
		global $dbfullPath = $FolderResources & "\" & $dbfile
		ConsoleWrite('<<   DataBase: '&$dbfullPath & @crlf )
		global $sqliteDLLfile="System.Data.SQLite.32.2012.dll"
		global $sSQliteDll =""
		Global $EncryptDB=0
	endfunc
#endregion sqlite
#region Send Telegram msg
	global $nuevaLinea="%0A"
	Dim $MsgClass[5] ;ClaseMensage,
	Func InitMsgClass()
		for $u=0 to UBound($MsgClass)-1
			$MsgClass[$u]=""
		next
	EndFunc
	global $msgToAllSecuence=IniRead($configPath,"Messaging","msgToAllSecuence","xxxxx")
#endregion
#region Telegram Bot
	global $DEVChatID = IniRead($configPath,"dev","chatID","00000000")
	global $BOT_ID = IniRead($configPath,"botUDF","BotID","00000000")
	global $BotToken = IniRead($configPath,"botUDF","BotToken","00000000")
	global $token=IniRead($configPath,"bot","token","")
#endregion
#region Tweeter reads
	global $StartTimeScrap=IniRead($configPath,"Times","StartTimeScrapHH:MM","00:00")
	global $EndTimeScrap=IniRead($configPath,"Times","EndTimeScrapHH:MM","23:59")
		ConsoleWrite('<<   Tweeter Scrap Time '& $StartTimeScrap & "  To "  & $EndTimeScrap )

	global $TweeterScrapMin=IniRead($configPath,"Times","TweeterScrapMin","5")
		ConsoleWrite(' //  Tweeter Scrap every Min ' & Sec2Time($TweeterScrapMin*60 ) & @CRLF)
	global $TweeterScrapMsec=$TweeterScrapMin*60*1000
#endregion
#region GetUpdates
	global $StartTimeBot=IniRead($configPath,"Times","StartTimeBotHH:MM","00:00")
	global $EndTimeBot=IniRead($configPath,"Times","EndTimeBotHH:MM","23:59")
		ConsoleWrite('<<   TlgmBot Scrap Time '& $StartTimeBot & "  To "  & $EndTimeBot )

	global $GetUpdateTimeSec=IniRead($configPath,"Times","BotUpdateTimeSec","10")
		ConsoleWrite('//  Telegram GetUpdates every Sec ' & Sec2Time($GetUpdateTimeSec) & @crlf )
	global $GetUpdateTimeMsec=$GetUpdateTimeSec*1000
	global $ahora=1
	global $KeyBoardActive=0
	global $KeyboardCheckcount=0
#endregion
_DBvarInit()


Delete Angulos.au3

Delete Angulos.au3

#include <Array.au3>
#include <Misc.au3>
#include <GDIPlus.au3>
#include <GUIConstantsEx.au3>
#include <GuiComboBoxEx.au3>
Global $hGui, $hMsg, $active = True
Global $hGraphic, $hPen, $hPen2, $hBitmap, $hBackbuffer, $hCursor, $mouse[4], $xx2, $yy2

Global $largura = 800, $altura = 600, $limites[6]

Global Const $PI = 3.1415926535897932384626433832795
Global Const $radToDeg = 180 / $PI

$hGui = GUICreate('Ângulos', $largura, $altura)
Global $hSeno = GUICtrlCreateCheckbox('Seno', 10, 5, 80, 20)
Global $hCos = GUICtrlCreateCheckbox('Cosseno', 10, 25, 80, 20)
Global $hTan = GUICtrlCreateCheckbox('Tangente', 100, 5, 80, 20)
Global $hCot = GUICtrlCreateCheckbox('Cotangente', 100, 25, 80, 20)
Global $hSec = GUICtrlCreateCheckbox('Secante', 190, 5, 80, 20)
Global $hCosec = GUICtrlCreateCheckbox('Co-Sec', 190, 25, 80, 20)
Global $hPasso = GUICtrlCreateCombo('', 280, 5, 80, 20, $CBS_DROPDOWNLIST)
Global $hInvertido = GUICtrlCreateCheckbox('Inverso', 370, 5, 80, 20)
GUICtrlSetData($hPasso, 'Livre|1|5|10|15|30', 'Livre')

Global $iSeno = False, $iCos = False, $iTan = False, $iCot = False, $iSec = False, $iCoSec = False, $iInverso = False
GUISetState(@SW_SHOWNORMAL)

_GDIPlus_Startup()
$hGraphic = _GDIPlus_GraphicsCreateFromHWND($hGui)
$hBitmap = _GDIPlus_BitmapCreateFromGraphics($largura - 20, $altura - 60, $hGraphic)

_limites()

Func _limites()
	$limites[0] = 10
	$limites[1] = 50
	$limites[2] = $largura - 20
	$limites[3] = $altura - 50
	$limites[4] = ($largura - 20) / 2
	$limites[5] = ($altura - 50) / 2
	;_ArrayDisplay($limites)
EndFunc   ;==>_limites
$hBackbuffer = _GDIPlus_ImageGetGraphicsContext($hBitmap)

$hPen = _GDIPlus_PenCreate()
$hPen2 = _GDIPlus_PenCreate(0xFFFF0000, 3)
$hPen3 = _GDIPlus_PenCreate(0xFF00FF00)
$hPen4 = _GDIPlus_PenCreate(0xFF0000FF)
_GDIPlus_GraphicsClear($hBackbuffer)
_GDIPlus_GraphicsSetSmoothingMode($hBackbuffer, 2)

Global $hBrush_01 = _GDIPlus_BrushCreateSolid(0xFF336699)
Global $hBrush_02 = _GDIPlus_BrushCreateSolid(0xFFFF0000)
Global $hBrush_03 = _GDIPlus_BrushCreateSolid(0xFF00FF00)
Global $hFamily = _GDIPlus_FontFamilyCreate('Courier New')
Global $hFont = _GDIPlus_FontCreate($hFamily, 10)
Global $hPosX = _GDIPlus_RectFCreate(2, 0, 120, 15)
Global $hPosY = _GDIPlus_RectFCreate(2, 20, 120, 15)
Global $hAng = _GDIPlus_RectFCreate(2, 80, 120, 15)
Global $hInv = _GDIPlus_RectFCreate(2, 100, 120, 15)

Global $hPosX1 = _GDIPlus_RectFCreate(2, 40, 120, 15)
Global $hPosY1 = _GDIPlus_RectFCreate(2, 60, 120, 15)
Global $hStringFormat = _GDIPlus_StringFormatCreate()

Global $start = TimerInit()
While Sleep(10)
	$hMsg = GUIGetMsg()
	Switch $hMsg
		Case $GUI_EVENT_CLOSE
			Quit()
		Case $hSeno
			$iSeno = $iSeno == False ? True : False
		Case $hCos
			$iCos = $iCos == False ? True : False
		Case $hTan
			$iTan = $iTan == False ? True : False
		Case $hCot
			$iCot = $iCot == False ? True : False
		Case $hSec
			$iSec = $iSec == False ? True : False
		Case $hCosec
			$iCoSec = $iCoSec == False ? True : False
		Case $hInvertido
			$iInverso = $iInverso == False ? True : False
	EndSwitch

	$hCursor = GUIGetCursorInfo()
	If Not $hCursor Then
		$mouse[0] = $hCursor[0] - $limites[0]
		$mouse[1] = $hCursor[1] - $limites[1]
	EndIf

	If WinActive($hGui) Then
		If Not $active Then $active = True
		If TimerDiff($start) >= 10 Then
			Update()
			$start = TimerInit()
		EndIf
	ElseIf Not WinActive($hGui) And $active Then
		$active = False
	EndIf
WEnd

Func Update()
	_GDIPlus_GraphicsClear($hBackbuffer, 0xF0FFFFFF)
	;_GDIPlus_StringFormatSetAlign($hStringFormat, 1)
	_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'x[' & $mouse[0] & ']', $hFont, $hPosX, $hStringFormat, $hBrush_01)
	_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'y[' & $mouse[1] & ']', $hFont, $hPosY, $hStringFormat, $hBrush_01)
	_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'x[' & $mouse[0] - 389 & ']', $hFont, $hPosX1, $hStringFormat, $hBrush_02)
	_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'y[' & - ($mouse[1] - 270) & ']', $hFont, $hPosY1, $hStringFormat, $hBrush_02)
	$ang = _ang(0, 0, $mouse[0] - 389, -($mouse[1] - 270))
	_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'º[' & $ang[0] & ']', $hFont, $hAng, $hStringFormat, $hBrush_02)

	_box($hBackbuffer, 0, 0, $largura - 21, $altura - 61)
	_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 21) / 2, 0, ($largura - 21) / 2, $altura - 60, $hPen)

	_GDIPlus_GraphicsDrawLine($hBackbuffer, 0, ($altura - 60) / 2, $largura - 21, ($altura - 60) / 2, $hPen)
	_GDIPlus_GraphicsDrawEllipse($hBackbuffer, ($largura - 20) / 2 - 200 - 1, ($altura - 60) / 2 - 200, 400, 400)
	;_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 21) / 2, ($altura - 60) / 2, $mouse[0], $mouse[1], $hPen2)
	$cos = Int(200 * Cos(($ang[0] / 180) * $PI))
	$sen = Int(200 * Sin(($ang[0] / 180) * $PI))
	$tan = Int(200 * ($sen / $cos))
	$cot = Int(200 * ($cos / $sen))
	$sec = Int(200 * (1 / (Cos(($ang[0] / 180) * $PI))))
	$cosec = Int(200 * (1 / (Sin(($ang[0] / 180) * $PI))))

	_GDIPlus_GraphicsDrawPie($hBackbuffer, ($largura - 20) / 2 - 1 - 25, ($altura - 60) / 2 - 25, 50, 50, 0, -$ang[0])

	If $iSeno Then
		_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, ($altura - 60) / 2, 389, 270 - $sen, $hPen2)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, 389, 270 - $sen, $hPen)
	EndIf

	If $iCos Then
		_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, ($altura - 60) / 2, 389 + $cos, 270, $hPen2)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, 389 + $cos, 270, $hPen)
	EndIf

	If $iTan Then
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 189, 1, 189, 538, $hPen)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 589, 1, 589, 538, $hPen)
		If $cos > 0 Then
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 589, 270 - $tan, 589, 270, $hPen2)
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, 589, 270 - $tan, $hPen)
		Else
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 189, 270 + $tan, 189, 270, $hPen2)
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, 189, 270 + $tan, $hPen)
		EndIf
	EndIf

	If $iCot Then
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 1, 70, 778, 70, $hPen)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 1, 470, 778, 470, $hPen)
		If $sen > 0 Then
			_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, 70, ($largura - 20) / 2 - 1 + $cot, 70, $hPen2)
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, ($largura - 20) / 2 - 1 + $cot, 70, $hPen)
		Else
			_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, 470, ($largura - 20) / 2 - 1 - $cot, 470, $hPen2)
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, ($largura - 20) / 2 - 1 - $cot, 470, $hPen)
		EndIf
	EndIf

	If $iSec Then
		Local $resposta = ''
		Select
			Case $ang[0] == 0 Or $ang[0] = 360
				$resposta = '#1 secante[não existe]'
			Case $ang[0] > 0 And $ang[0] < 90
				$resposta = '#2 secante[' & $ang[0] & '] angulo[' & 90 + $ang[0] & ']'
			Case $ang[0] == 90 Or $ang[0] == 180
				$resposta = '#3 secante[não existe]'
			Case $ang[0] > 90 And $ang[0] < 180
				$resposta = '#4 secante[' & $ang[0] & '] angulo[' & $ang[0] - 90 & ']'
			Case $ang[0] > 180 And $ang[0] < 270
				$resposta = '#5 secante[' & $ang[0] & ']'
			Case $ang[0] > 270 And $ang[0] < 360
				$resposta = '#6 secante[' & $ang[0] & ']'
		EndSelect

		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $sec, 270, 389, 270, $hPen2)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $sec, 270, 389, 270 - $cosec, $hPen4)
	EndIf

	If $iCoSec Then
		Local $resposta = ''
		Select
			Case $ang[0] == 0 Or $ang[0] = 360
				$resposta = '#1 secante[não existe]'
			Case $ang[0] > 0 And $ang[0] < 90
				$resposta = '#2 secante[' & $ang[0] & '] angulo[' & 90 + $ang[0] & ']'
			Case $ang[0] == 90 Or $ang[0] == 180
				$resposta = '#3 secante[não existe]'
			Case $ang[0] > 90 And $ang[0] < 180
				$resposta = '#4 secante[' & $ang[0] & '] angulo[' & $ang[0] - 90 & ']'
			Case $ang[0] > 180 And $ang[0] < 270
				$resposta = '#5 secante[' & $ang[0] & ']'
			Case $ang[0] > 270 And $ang[0] < 360
				$resposta = '#6 secante[' & $ang[0] & ']'
		EndSelect

		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $sec, 270, 389, 270 - $cosec, $hPen4)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389, 270, 389, 270 - $cosec, $hPen2)
	EndIf

	If $iInverso Then
		Local $invertido = $ang[0] > 180 ? $ang[0] - 180 : 180 + $ang[0]
		$invertido = $invertido = 360 ? 0 : $invertido
		$invertido = StringFormat('%.2f', $invertido)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, ($altura - 60) / 2, 389 - $cos, 270 + $sen, $hPen3)
		_GDIPlus_GraphicsDrawStringEx($hBackbuffer, 'º[' & $invertido & ']', $hFont, $hInv, $hStringFormat, $hBrush_03)
	EndIf
	_GDIPlus_GraphicsDrawLine($hBackbuffer, ($largura - 20) / 2 - 1, ($altura - 60) / 2, 389 + $cos, 270 - $sen, $hPen3)

	_GDIPlus_GraphicsDrawImageRect($hGraphic, $hBitmap, 10, 50, $largura - 20, $altura - 60)
EndFunc   ;==>Update

Func Quit()
	_GDIPlus_BrushDispose($hBrush_01)
	_GDIPlus_BrushDispose($hBrush_02)
	_GDIPlus_BrushDispose($hBrush_03)
	_GDIPlus_FontFamilyDispose($hFamily)
	_GDIPlus_FontDispose($hFont)
	_GDIPlus_StringFormatDispose($hStringFormat)

	_GDIPlus_GraphicsDispose($hBackbuffer)
	_GDIPlus_BitmapDispose($hBitmap)
	_GDIPlus_PenDispose($hPen)
	_GDIPlus_PenDispose($hPen2)
	_GDIPlus_PenDispose($hPen3)
	_GDIPlus_GraphicsDispose($hGraphic)
	_GDIPlus_Shutdown()
	Exit
EndFunc   ;==>Quit

Func _box($hToGraphic, $ix1, $iy1, $il, $ia)
	Local $aBox[5][2]
	$aBox[0][0] = 4
	$aBox[1][0] = $ix1
	$aBox[1][1] = $iy1
	$aBox[2][0] = $ix1 + $il
	$aBox[2][1] = $iy1
	$aBox[3][0] = $ix1 + $il
	$aBox[3][1] = $iy1 + $ia
	$aBox[4][0] = $ix1
	$aBox[4][1] = $iy1 + $ia
	_GDIPlus_GraphicsDrawPolygon($hToGraphic, $aBox)
EndFunc   ;==>_box

Func _ang($xx1, $yy1, $xx2, $yy2)
	Local $arr[2], $ca = Abs($yy2 - $yy1), $co = Abs($xx2 - $xx1)
	Select
		Case $xx1 > $xx2
			Select
				Case $yy1 < $yy2
					$arr[0] = ATan(($co) / ($ca)) * $radToDeg + 90
				Case $yy1 == $yy2
					$arr[0] = 180
				Case $yy1 > $yy2
					$arr[0] = 270 - ATan(($co) / ($ca)) * $radToDeg
			EndSelect
		Case $xx1 == $xx2
			Select
				Case $yy1 < $yy2
					$arr[0] = 90
				Case $yy1 == $yy2
					$arr[0] = 0
				Case $yy1 > $yy2
					$arr[0] = 270
			EndSelect
		Case $xx1 < $xx2
			Select
				Case $yy1 < $yy2
					$arr[0] = 90 - ATan(($co) / ($ca)) * $radToDeg
				Case $yy1 == $yy2
					$arr[0] = 0
				Case $yy1 > $yy2
					$arr[0] = ATan(($co) / ($ca)) * $radToDeg + 270
					;$arr[0] = 270 - ATan(($co) / ($ca)) * $radToDeg
			EndSelect
	EndSelect
	$arr[0] = StringFormat('%.2f', $arr[0])
	$arr[1] = Sqrt($co ^ 2 + $ca ^ 2)
	Return $arr
EndFunc   ;==>_ang