Delete Angulos.au3

Delete Angulos.au3

; http://www.brasilescola.com/matematica/secante-cosecante-cotangente.htm
; http://eduardo-vasconcelos.blogspot.com.br/2012/01/trigonometria-05-funcao-secante.html
#include <Array.au3>
#include <Misc.au3>
#include <GDIPlus.au3>
#include <GUIConstantsEx.au3>
#include <GuiComboBoxEx.au3>

; #SCRIPT# =====================================================================================================================
; Name ..........: Angulos
; Description ...: Um script que demonstra visualmente onde como é representado os componentes de um ângulo (sen, cos, tan...)
; Author ........: Luigi (Luismar Chechelaky)
; Link ..........: https://github.com/chechelaky/AutoIt/blob/master/Diversos/Angulos.au3
; ===============================================================================================================================

Global $hGui, $hMsg, $active = True
Global $hGraphic, $hPen, $hPen2, $hBitmap, $hBackbuffer, $width = 350, $height = 300, $hCursor, $mouse[4], $xx2, $yy2

Global $mapa[10][10]
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 $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 = 0, $iCos = 0, $iTan = 0, $iCot = 0, $iSec = 0, $iInverso = 0
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)
$hPen3 = _GDIPlus_PenCreate(0xFF00FF00)
_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 1
	$hMsg = GUIGetMsg()
	Switch $hMsg
		Case $GUI_EVENT_CLOSE
			_exit()
		Case $hSeno
			$iSeno = _Iif($iSeno == 0, 1, 0)
		Case $hCos
			$iCos = _Iif($iCos == 0, 1, 0)
		Case $hTan
			$iTan = _Iif($iTan == 0, 1, 0)
		Case $hCot
			$iCot = _Iif($iCot == 0, 1, 0)
		Case $hSec
			$iSec = _Iif($iSec == 0, 1, 0)
		Case $hInvertido
			$iInverso = _Iif($iInverso == 0, 1, 0)
	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))

	_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, $hPen2)
	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, $hPen2)
	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, $hPen2)
		Else
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 189, 270 + $tan, 189, 270, $hPen2)
			_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, 189, 270 + $tan, $hPen2)
		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, $hPen2)
		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, $hPen2)
		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] & '] angulo[' & 270 - $ang[0]  & ']'
			Case $ang[0] > 270 And $ang[0] < 360
				$resposta = '#6 secante[' & $ang[0] & '] angulo[' & $ang[0] - 270 & ']'
		EndSelect

		$nn1 = 389 + 0 + 1 / Int(200 * Cos(($ang[0] / 180) * $PI))
		$nn2 = 270 + 0 - $sen

		ConsoleWrite('nn1[' & $nn1 & '] nn2[' & $nn2 & ']' & @LF)
		_GDIPlus_GraphicsDrawLine($hBackbuffer, 389 + $cos, 270 - $sen, $nn1, $nn2, $hPen2)
;~ 		_GDIPlus_GraphicsDrawEllipse($hBackbuffer, ($largura - 20) / 2 - 250 - 1, ($altura - 60) / 2 - 250, 500, 500)
		ConsoleWrite($resposta & @LF)
	EndIf

	If $iInverso Then
		Local $invertido = _Iif($ang[0] > 180, $ang[0] - 180, 180 + $ang[0])
		$invertido = _Iif($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, $hPen2)

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

Func _exit()
	_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   ;==>_exit

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

Func _Iif($aa, $bb, $cc)
	If $aa Then Return $bb
	Return $cc
EndFunc


silence console output

silence console output

#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, $dbfile, $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 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 SendTelegramMessages($TweetArr)
		If IsArray($TweetArr) Then
			$U = UBound($TweetArr) - 1
			For $i = $u To 1 Step -1
				sendmessages($TweetArr[1])
			Next
			Exit 30
		Else
			Exit 21
		EndIf
	EndFunc
;~  	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 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&"%0A"&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")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$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 handeling ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@(' & @ScriptName & '-' & @ScriptLineNumber & ') : $nBytesRead = ' & $nBytesRead & @CRLF)
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100 Then	Exit 25
		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 UpdateUsers()
		ConsoleWrite('  Update users ' & @crlf)
		local $s=GetBotUpdates()
		$s=StringReplace($s,'"username":','"last_name":')
		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
					$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())
					for $i=1 to $UserIDArr[0]
						SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i])
					next
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates"
		$sGet = HttpGetJson($urlMSG)
		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 SQLregister($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		if SQLExistUser($UserID)=0 then
			SQLInsertUser($UserID,$Fname,$Lname,$epoch)
		endif
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLInsertUser() = '& @crlf)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",1,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 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 ===========================================================================
	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, $dbfile, $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 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 SendTelegramMessages($TweetArr)
		If IsArray($TweetArr) Then
			$U = UBound($TweetArr) - 1
			For $i = $u To 1 Step -1
				sendmessages($TweetArr[1])
			Next
			Exit 30
		Else
			Exit 21
		EndIf
	EndFunc
;~  	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 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&"%0A"&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")
		$urlMSG="https://api.telegram.org/" & $token & "/sendMessage?chat_id=" & $chatid & _
		"&text=" & $msgtext & "&parse_mode=HTML"
		$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 handeling ===================================================================
	func _ScrapTweetMessages($Username)
		Local $sData = InetRead("https://twitter.com/"&$Username)
		Local $nBytesRead = @extended
		ConsoleWrite('@@(' & @ScriptName & '-' & @ScriptLineNumber & ') : $nBytesRead = ' & $nBytesRead & @CRLF)
		$htmltxt = BinaryToString($sData)
		If $nBytesRead < 100 Then	Exit 25
		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 UpdateUsers()
		ConsoleWrite('  Update users ' & @crlf)
		local $s=GetBotUpdates()
		$s=StringReplace($s,'"username":','"last_name":')
		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
					$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())
					for $i=1 to $UserIDArr[0]
						SQLregister($UserIDArr[$i],$FnameArr[$i],$LnameArr[$i],$epochArr[$i])
					next
				endif
			endif
		endif
	EndFunc
	Func GetBotUpdates()
		$urlMSG="https://api.telegram.org/" & $token & "/getUpdates"
		$sGet = HttpGetJson($urlMSG)
		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 SQLregister($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLregister() = '& @crlf)
		if SQLExistUser($UserID)=0 then
			SQLInsertUser($UserID,$Fname,$Lname,$epoch)
		endif
	EndFunc
	Func SQLInsertUser($UserID,$Fname,$Lname,$epoch)
;~ 	ConsoleWrite('++SQLInsertUser() = '& @crlf)
		ConsoleWrite('  Nuevo usuario = '& $Fname & "  "  & $Lname  & @crlf)
		$query='INSERT INTO Users VALUES (' & $UserID & ',"' & $Fname & '","' & $Lname & '",1,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 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


lockup sqlite error 5

lockup sqlite error 5

	func SQLite_init()
;~ 		ConsoleWrite('++SQLite_init() = ' & @crlf )
		$sqliteDLLfile=$FolderBin &"\System.Data.SQLite.32.2012.dll"
		$sSQliteDll = _SQLite_Startup($sqliteDLLfile,0,1)
		Local $err=@error
		Sleep(1000)
		if $sSQliteDll = "" then
			MsgBox(16, "Database Error", "Database error . ErrNo 1000/" & $err & @CRLF & "version " & _SQLite_LibVersion())
			Exit 11
		EndIf
	EndFunc
	Func _SQLite_down()
;~ 		ConsoleWrite('++_SQLite_down() = ' & @crlf )
		If $sSQliteDll<>"" Then DllClose($sSQliteDll)
		$sSQliteDll =""
	EndFunc
	func _SQLITErun($SQLq,$DBfile,$quiet=true,$sqlClose=1)
		While 1
			If $quiet=False Then ConsoleWrite('-->_SQLITErun = ' & $DBfile & @crlf & " >> " & $SQLq & @crlf )
			$ExitOnError=1
			Local $hDB=_SQLite_Open($DBfile)
			If $EncryptDB Then _SQLite_Exec(-1, _PragmaQuery($DBfile,"") )
			$iRval= _SQLite_Exec(-1, $SQLq)       ;~ 		Local $d = _SQLite_Exec(-1, $SQLq, "_cb") ; _cb will be called for each row
			If $iRval<>0 Then ConsoleWrite('_SQLite_Exec= ' & $iRval& @crlf )
			if $sqlClose=1 then
				_SQLite_Close($hDB)
			endif
			if $iRval = $SQLITE_OK then
				Return True
			else
				Switch $iRval
					case 5
						$ExitOnError=0
						$s_text="SQLITE return code " & $iRval
						_ConsoleWrite($s_text,3)
						sleep(1000)
					case 21
						MsgBox(16, "Database Error: " & $iRval,"Database not found at "& $DBfile & ". check file/path . ErrNo 1001c" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
					case 26
						$encriptedMsg="DataBase file is encrypted or is not a database"
						MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001q" & @crlf & $encriptedMsg & @crlf & $DBfile  )
					case Else
						MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001w" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
				EndSwitch
				if $ExitOnError=1 then
					_SQLite_QueryFinalize($SQLq)
					_SQLite_Close($hDB)
					exit
				endif
;~ 				return false
			endif
			return true
		wend
	EndFunc
	Func _SQLITEqry($SQLq,$DBfile,$quiet=true,$sqlClose=1)
		While 1
			If $quiet=False Then ConsoleWrite('-->_SQLITEqry = ' & $DBfile & @crlf& " >> " & $SQLq & @crlf )
			$ExitOnError=1
			Local $hDB=_SQLite_Open($DBfile)
			If $EncryptDB Then _SQLite_Exec(-1, _PragmaQuery($DBfile,"") )
			local $iRows, $iColumns
			$iRval = _SQLite_GetTable2d($hDB,$SQLq, $qryResult, $iRows, $iColumns)
			If $iRval = $SQLITE_OK  Or $iRval=$SQLITE_DONE Then
				If $quiet=False Then
					ConsoleWrite(" >> Rows="&ubound($qryResult,1)&"   Cols="&ubound($qryResult,2)&@crlf)
					_SQLite_Display2DResult($qryResult)
				endif
			Else
				Switch $iRval
					case 5
						$ExitOnError=0
						$s_text="SQLITE return code " & $iRval
						_ConsoleWrite($s_text,3)
						sleep(1000)
					case 21
						MsgBox(16, "Database Error: " & $iRval,"Database not found at "& $DBfile & ". check file/path . ErrNo 1001c" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
					case 26
						$encriptedMsg="DataBase file is encrypted or is not a database"
						MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001q" & @crlf & $encriptedMsg & @crlf & $DBfile  )
					case Else
						MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001w" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
				EndSwitch
				if $ExitOnError=1 then
					_SQLite_QueryFinalize($SQLq)
					_SQLite_Close($hDB)
					exit
				endif
;~ 				return false
			EndIf
			if $sqlClose=1 then
				_SQLite_Close($hDB)
			endif
			return true
		wend
	EndFunc
	Func _PragmaQuery($db,$SQLq)
	;~ 	ConsoleWrite('++_PragmaQuery() = '& @crlf)
		Switch $db
			Case $dbfile
				$SQLq='PRAGMA key = "' & $defaultdbencript & '";'&$SQLq
			case Else
				$SQLq='PRAGMA key = "' & $defaultdbencript & '";'&$SQLq
		EndSwitch
		Return $SQLq
	EndFunc
	Func _cb($aRow)
		For $s In $aRow
			ConsoleWrite("=>"& $s & @TAB)
		Next
		ConsoleWrite(@CRLF)
	EndFunc   ;==>_cb
	Func _SQLITEgetUnit($query,$db,$quiet=false,$sqlClose=1) ; returns one unit result from query
;~ 		ConsoleWrite('++_SQLITEgetUnit() = '& @crlf)
;~ 		$quietSQLQuery=false  no muestra los queries
;~ 		$vervoseSQLQuery=true
		_SQLITEqry($query,$db,$quiet,$sqlClose)
		If  IsArray($qryResult) then
			If UBound($qryResult)>1 then
				Return $qryResult[1][0]
			Else
				Return ""
			endif
		endif
		return 0
	EndFunc
#cs
;~ func SQLite_InMemory()   $profiledbfile
;~ 	$hMemDb = _SQLite_Open(":memory:") ; Creates a :memory: database
;~ 	$hMemDb = _SQLite_Open("Diffreport.db") ; Creates a :memory: database
;~ 	If @error Then
;~ 		ConsoleWrite("Can't create a memory Database!" & @CRLF)
;~ 		Exit $hMemDb
;~ 	EndIf
;~ 	_SQLite_Exec($hMemDb,"PRAGMA journal_mode = OFF;")
;~ 	_SQLite_Exec($hMemDb,"PRAGMA temp_store = MEMORY;")
;~ 	_SQLite_Exec($hMemDb, "PRAGMA synchronous = OFF;")
;~ EndFunc
#ce

	func SQLite_init()
;~ 		ConsoleWrite('++SQLite_init() = ' & @crlf )
		$sqliteDLLfile=$FolderBin &"\System.Data.SQLite.32.2012.dll"
		$sSQliteDll = _SQLite_Startup($sqliteDLLfile,0,1)
		Local $err=@error
		Sleep(1000)
		if $sSQliteDll = "" then
			MsgBox(16, "Database Error", "Database error . ErrNo 1000/" & $err & @CRLF & "version " & _SQLite_LibVersion())
			Exit 11
		EndIf
	EndFunc
	Func _SQLite_down()
;~ 		ConsoleWrite('++_SQLite_down() = ' & @crlf )
		If $sSQliteDll<>"" Then DllClose($sSQliteDll)
		$sSQliteDll =""
	EndFunc
	func _SQLITErun($SQLq,$DBfile,$quiet=true,$sqlClose=1)
		If $quiet=False Then ConsoleWrite('-->_SQLITErun = ' & $DBfile & @crlf & " >> " & $SQLq & @crlf )
		$ExitOnError=1
		Local $hDB=_SQLite_Open($DBfile)
		If $EncryptDB Then _SQLite_Exec(-1, _PragmaQuery($DBfile,"") )
		$iRval= _SQLite_Exec(-1, $SQLq)       ;~ 		Local $d = _SQLite_Exec(-1, $SQLq, "_cb") ; _cb will be called for each row
		If $iRval<>0 Then ConsoleWrite('_SQLite_Exec= ' & $iRval& @crlf )
		if $sqlClose=1 then
			_SQLite_Close($hDB)
		endif
		if $iRval = $SQLITE_OK then
			Return True
		else
			If $iRval=26 Then
				$encriptedMsg="DataBase file is encrypted or is not a database"
;~ 				MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001r" & @crlf & $encriptedMsg & @crlf & $DBfile & @CRLF & "version " & _SQLite_LibVersion() )
			else
;~ 				MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001r" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile & @CRLF & "version " & _SQLite_LibVersion() )
			EndIf
;~ 			_SQLite_QueryFinalize($SQLq)
			if $ExitOnError=1 then
				_SQLite_QueryFinalize($SQLq)
				_SQLite_Close($hDB)
				;exit
			endif
			return false
		endif
		return true
	EndFunc
	Func _SQLITEqry($SQLq,$DBfile,$quiet=true,$sqlClose=1)
		If $quiet=False Then ConsoleWrite('-->_SQLITEqry = ' & $DBfile & @crlf& " >> " & $SQLq & @crlf )
		$ExitOnError=1
		Local $hDB=_SQLite_Open($DBfile)
		If $EncryptDB Then _SQLite_Exec(-1, _PragmaQuery($DBfile,"") )
		local $iRows, $iColumns
		$iRval = _SQLite_GetTable2d($hDB,$SQLq, $qryResult, $iRows, $iColumns)
		If $iRval = $SQLITE_OK  Or $iRval=$SQLITE_DONE Then
			If $quiet=False Then
				ConsoleWrite(" >> Rows="&ubound($qryResult,1)&"   Cols="&ubound($qryResult,2)&@crlf)
				_SQLite_Display2DResult($qryResult)
			endif
		Else
			If $iRval=21 Then
				MsgBox(16, "Database Error: " & $iRval,"Database not found at "& $DBfile & ". check file/path . ErrNo 1001c" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
			endif
			If $iRval=26 Then
				$encriptedMsg="DataBase file is encrypted or is not a database"
				MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001q" & @crlf & $encriptedMsg & @crlf & $DBfile  )
			else
				MsgBox(16, "Database Error: " & $iRval,"Database error . ErrNo 1001w" & @crlf & _SQLite_ErrMsg() & @crlf &  $SQLq  & @crlf & $DBfile  )
			EndIf
			if $ExitOnError=1 then
				_SQLite_QueryFinalize($SQLq)
				_SQLite_Close($hDB)
				exit
			endif
			return false
		EndIf
		if $sqlClose=1 then
			_SQLite_Close($hDB)
		endif
		return true
	EndFunc
	Func _PragmaQuery($db,$SQLq)
	;~ 	ConsoleWrite('++_PragmaQuery() = '& @crlf)
		Switch $db
			Case $dbfile
				$SQLq='PRAGMA key = "' & $defaultdbencript & '";'&$SQLq
			case Else
				$SQLq='PRAGMA key = "' & $defaultdbencript & '";'&$SQLq
		EndSwitch
		Return $SQLq
	EndFunc
	Func _cb($aRow)
		For $s In $aRow
			ConsoleWrite("=>"& $s & @TAB)
		Next
		ConsoleWrite(@CRLF)
	EndFunc   ;==>_cb
	Func _SQLITEgetUnit($query,$db,$quiet=false,$sqlClose=1) ; returns one unit result from query
;~ 		ConsoleWrite('++_SQLITEgetUnit() = '& @crlf)
;~ 		$quietSQLQuery=false  no muestra los queries
;~ 		$vervoseSQLQuery=true
		_SQLITEqry($query,$db,$quiet,$sqlClose)
		If  IsArray($qryResult) then
			If UBound($qryResult)>1 then
				Return $qryResult[1][0]
			Else
				Return ""
			endif
		endif
		return 0
	EndFunc
#cs
;~ func SQLite_InMemory()   $profiledbfile
;~ 	$hMemDb = _SQLite_Open(":memory:") ; Creates a :memory: database
;~ 	$hMemDb = _SQLite_Open("Diffreport.db") ; Creates a :memory: database
;~ 	If @error Then
;~ 		ConsoleWrite("Can't create a memory Database!" & @CRLF)
;~ 		Exit $hMemDb
;~ 	EndIf
;~ 	_SQLite_Exec($hMemDb,"PRAGMA journal_mode = OFF;")
;~ 	_SQLite_Exec($hMemDb,"PRAGMA temp_store = MEMORY;")
;~ 	_SQLite_Exec($hMemDb, "PRAGMA synchronous = OFF;")
;~ EndFunc
#ce


Add Chrome compatibility to one-click login

Chrome simply stores its Flash files in a different folder for the
Pepper flash player. To account for this, the base path is abstracted
into an array, which is expanded (much like the site directory) when
searching for file paths.

Fixes atomizer/muledump#41
Closes atomizer/muledump#81

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths_base[2] = [ _
	@AppDataDir & "\Macromedia\Flash Player\#SharedObjects\", _
	_PathFull("../Local", @AppDataDir) & "\Google\Chrome\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot\#SharedObjects\" _
]
Local $paths[3] = [ _
	"localhost", _
	"realmofthemadgodhrd.appspot.com", _
	"www.realmofthemadgod.com" _
]
For $path_base In $paths_base
	$search = FileFindFirstFile($path_base & "*")
	$searchPath = FileFindNextFile($search)
	For $gameDir In $paths
		$gameFilePath = $path_base & $searchPath & "\" & $gameDir & "\RotMG.sol"
		$file = FileOpen($gameFilePath,26)
		FileWrite($file,$string)
		FileClose($file)
	Next
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths[3] = [ _
	"localhost", _
	"realmofthemadgodhrd.appspot.com", _
	"www.realmofthemadgod.com" _
]
$path = @AppDataDir & "\Macromedia\Flash Player\#SharedObjects\"
$search = FileFindFirstFile($path & "*")
$searchPath = FileFindNextFile($search)
For $gameDir In $paths
	$gameFilePath = $path & $searchPath & "\" & $gameDir & "\RotMG.sol"
	$file = FileOpen($gameFilePath,26)
	FileWrite($file,$string)
	FileClose($file)
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')


remove extraneous script

remove extraneous script

#include <ScreenCapture.au3>

Func Screenshots($prefix, $rows, $columns)
   $window = WinGetHandle("NPP")
   $left = 3
   $top = WinGetPos("NPP")[3] - WinGetClientSize("NPP")[1] + 3
   $right = WinGetClientSize("NPP")[0] - 3
   $bottom = WinGetClientSize("NPP")[1] - 3

   For $row = 0 To $rows - 1
	  $rowname = "A"
	  If $row == 1 Then
		 $rowname = "B"
	  ElseIf $row == 2 Then
		 $rowname = "C"
	  ElseIf $row == 3 Then
		 $rowname = "D"
	  ElseIf $row == 4 Then
 		 $rowname = "E"
	  ElseIf $row == 5 Then
		 $rowname = "X"
	  EndIf

	  For $col = 0 To $columns - 1
 		 $colname = "00"
		 If $col < 10 Then
			$colname = "0" & $col
		 Else
			$colname = "" & $col
		 EndIf

		 Send("{SPACE}")
		 Sleep(500)

		 For $level = 0 To 4
			$levelname = "0" & $level
			$filename = "C:\Users\Liam\workspace\inne++\screenshots\" & $prefix & "-" & $rowname & "-" & $colname & "-" & $levelname & ".jpg"

			Send("{ENTER}")
			Sleep(500)
			Send("{SPACE}")
			Sleep(1)
			_ScreenCapture_CaptureWnd($filename, $window, $left, $top, $right, $bottom, False)
			Send("{ESCAPE}")
 			Sleep(1)
			Send("{DOWN}")
			Sleep(1)
			Send("{DOWN}")
			Sleep(1)
			Send("{ENTER}")
			Sleep(50)
			Send("{RIGHT}")
			Sleep(50)
		 Next

		 Send("{ESCAPE}")
		 Sleep(500)

		 If $col < $columns - 1 Then
			Send("{RIGHT}")
		 EndIf
	  Next

	  Send("{DOWN}")

	  For $col = 0 To $columns - 2
		 Sleep(50)
		 Send("{LEFT}")
	  Next
   Next
EndFunc

WinWaitActive("NPP")
Send("{ENTER}")
Sleep(1)
Send("{ENTER}")
Sleep(1)

Send("{PGUP}")
Sleep(500)
Screenshots("SI", 5, 5)
Sleep(500)
Send("{PGDN}")

Sleep(500)
Screenshots("S", 6, 20)

;Sleep(500)
;Send("{PGDN}")
;Sleep(500)
;Screenshots("SL", 6, 20)


command-prompt title fix

command-prompt title fix

; Purpose:       Automates RogueKillerCMD cleaning
; Requirements:  RogueKillerCMD.exe placed in the same directory as this compiled file
; Author:        reddit.com/user/SleepyDoge
; Version:       1.0.0-TRON
; Misc:          Included for use with Tron by reddit.com/user/vocatus

#include <MsgBoxConstants.au3>
#include <TrayConstants.au3>
#include <Array.au3>
#include <Constants.au3>

sleep(1000)
;Wait for RogueKiller to Start, timeout of 3 minutes
ProcessWait( "RogueKillerCMD.exe", 180 )

;Activate Tron Window and send keystrokes until RogueKillerCMD.exe isn't running
do
sleep(30000)
ControlSend("TRON v6.6.0 [stage_3_disinfect] [RogueKiller]", "", "", "remove{ENTER}")
ControlSend("Administrator: TRON v6.6.0 [stage_3_disinfect] [RogueKiller]", "", "", "remove{ENTER}")
$errorCheck = ProcessExists("RogueKillerCMD.exe")
until $errorCheck = 0

Exit

; Purpose:       Automates RogueKillerCMD cleaning
; Requirements:  RogueKillerCMD.exe placed in the same directory as this compiled file
; Author:        reddit.com/user/SleepyDoge
; Version:       1.0.0-TRON
; Misc:          Included for use with Tron by reddit.com/user/vocatus

#include <MsgBoxConstants.au3>
#include <TrayConstants.au3>
#include <Array.au3>
#include <Constants.au3>

sleep(1000)
;Wait for RogueKiller to Start, timeout of 3 minutes
ProcessWait( "RogueKillerCMD.exe", 180 )

;Activate Tron Window and send keystrokes until RogueKillerCMD.exe isn't running
do
sleep(30000)
ControlSend("[stage_3_disinfect] [RogueKiller]", "", "", "remove{ENTER}")
$errorCheck = ProcessExists("RogueKillerCMD.exe")
until $errorCheck = 0

Exit


Improve one-click login installation error message

Sometimes users will need to open mulelogin.au3 directly using AutoIt
rather than launching the script directly.

Fixes atomizer/muledump#101

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights" & @CRLF & "or open this file through AutoIt directly")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths_base[2] = [ _
	@AppDataDir & "\Macromedia\Flash Player\#SharedObjects\", _
	_PathFull("../Local", @AppDataDir) & "\Google\Chrome\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot\#SharedObjects\" _
]
Local $paths[3] = [ _
	"localhost", _
	"realmofthemadgodhrd.appspot.com", _
	"www.realmofthemadgod.com" _
]
For $path_base In $paths_base
	$search = FileFindFirstFile($path_base & "*")
	$searchPath = FileFindNextFile($search)
	For $gameDir In $paths
		$gameFilePath = $path_base & $searchPath & "\" & $gameDir & "\RotMG.sol"
		$file = FileOpen($gameFilePath,26)
		FileWrite($file,$string)
		FileClose($file)
	Next
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')

#include <String.au3>
#include <File.au3>
#include <Array.au3>

Global $string, $password, $email, $data, $path, $search, $file, $root
$root = "HKEY_CLASSES_ROOT\muledump"

Func _write()
	RegWrite($root,"","REG_SZ","URL: muledump Protocol")
	RegWrite($root,"URL Protocol","REG_SZ","")
	RegWrite($root & "\shell")
	RegWrite($root & "\shell\open")
	RegWrite($root & "\shell\open\command","","REG_SZ", @AutoItExe & ' "' & @ScriptFullPath & '" %1')
	If RegRead("HKEY_CLASSES_ROOT\muledump","") Then
		MsgBox(64,"mulelogin","muledump: URL handler installed")
	Else
		MsgBox(16,"mulelogin","Unable to write to registry" & @CRLF & "Try again with admin rights")
	EndIf
	Exit
EndFunc

Func _install()
	Local $k
	$k = RegEnumKey($root, 1)
	If @error == 2 Then
		MsgBox(16,"mulelogin","Unable to open the registry" & @CRLF & "Try again with admin rights")
		Exit
	EndIf
	If @error == 1 Then _write()
	$k = MsgBox(6 + 32, 'mulelogin', _
		'URL handler is already installed. Uninstall?' & @CRLF & @CRLF & _
		'"Cancel" to do nothing' & @CRLF & _
		'"Try Again" to reinstall' & @CRLF & _
		'"Continue" to uninstall')
	If $k == 10 Then _write()
	If $k == 11 Then
		RegDelete($root)
		if @error <> 0 Then
			MsgBox(16,"mulelogin","Unable to delete the key" & @CRLF & "Try again with admin rights")
		Else
			MsgBox(64,"mulelogin","muledump: URL handler uninstalled")
		EndIf
	EndIf
	Exit
EndFunc

Func _length($string)
	Local $binlength, $declength, $array, $result
	$declength = StringLen($string)/2
    While $declength > 0
        $binlength &= Mod($declength,2)
        $declength = Floor($declength/2)
    WEnd
	$binlength = StringReverse($binlength)
	if @error <> 0 Then
		$binlength = _StringReverse($binlength)
	EndIf
	$binlength = $binlength & "1"
	$array = StringSplit($binlength,"")
	For $i = 1 To $array[0]
        $array[0] -= 1
        If $array[$i] = "1" Then $result += 2 ^ ($array[0])
	Next
	Return Hex(Int($result),2)
EndFunc

Func _build()
	;header
	$string  = "0x 00 BF" 						;Magic Number		 2 bytes
	$string &= "?? ?? ?? ??"					;Size				 4 bytes
	$string &= "54 43 53 4F 00 04 00 00 00 00"	;Marker				10 bytes
	$string &= "00 05"							;Name Size			 2 bytes
	$string &= "52 6F 74 4D 47"					;"RotMG"			 5 bytes
	$string &= "00 00 00"						;Padding			 3 bytes
	$string &= "03"								;AMF Version		 1 byte

	;data
	$string &= "11"								;Length				 1 byte
	$string &= "50 61 73 73 77 6F 72 64"		;"Password"			 8 bytes
	$string &= "06"								;Type (string) 		 1 byte
	$string &= _length($password)				;Length				 1 byte
	$string &= $password						;Actual Password	 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string &= "09"								;Length				 1 byte
	$string &= "47 55 49 44"					;"GUID"				 4 bytes
	$string &= "06"								;Type (string)		 1 byte
	$string &= _length($email)					;Length				 1 byte
	$string &=  $email							;Email				 ? bytes
	$string &= "00"								;AMF Padding		 1 byte

	$string = StringReplace($string," ","")
	$string = StringRegExpReplace($string,"\?{8}",Hex(Int(StringLen(StringMid($string,15))/2)))
EndFunc

If $CmdLine[0] = 0 Then _install()

$data = StringReplace($CmdLine[1],"muledump:","")
$data = StringSplit($data,"-")
$email = $data[1]
$password = $data[2]

_build()

Local $paths_base[2] = [ _
	@AppDataDir & "\Macromedia\Flash Player\#SharedObjects\", _
	_PathFull("../Local", @AppDataDir) & "\Google\Chrome\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot\#SharedObjects\" _
]
Local $paths[3] = [ _
	"localhost", _
	"realmofthemadgodhrd.appspot.com", _
	"www.realmofthemadgod.com" _
]
For $path_base In $paths_base
	$search = FileFindFirstFile($path_base & "*")
	$searchPath = FileFindNextFile($search)
	For $gameDir In $paths
		$gameFilePath = $path_base & $searchPath & "\" & $gameDir & "\RotMG.sol"
		$file = FileOpen($gameFilePath,26)
		FileWrite($file,$string)
		FileClose($file)
	Next
Next
FileClose($search)

ShellExecute("http://www.realmofthemadgod.com/")
; replace the line above if you're using a projector
; for example, with totalcmd + swfview
;ShellExecute('C:\Program Files\Total Commander\Totalcmd.exe', '/S=L:Pswfview e:\temp\rotmg\loader.swf')
; or to open the latest swf with the Adobe Flash Projector
;ShellExecute('C:\flashplayer_16_sa.exe', 'https://realmofthemadgodhrd.appspot.com/AssembleeGameClient'&BinaryToString(InetRead("http://www.realmofthemadgod.com/version.txt"))&'.swf')


Removed debug directive from the script

Removed debug directive from the script

; ****** REMEMBER TO SWITCH OFF UAC ON TARGET MACHINE!!! *********
;
; This script will install, run and uninstall SasView
; given location of the installer. The exit code of the script
; points at failure location:
;
; 0 - OK
; 1 - Installer failure
; 2 - Problems running SasView (simple fitting)
; 3 - Uninstaller failure

#include <Constants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

; Modifiable globals
Global $fInstallerLocation = @TempDir & "\setupSasView.exe"
if $CmdLine[0] > 0 Then
   ; If argument present - use it as local download path
   $fInstallerLocation = $CmdLine[1]
EndIf

Global $fUninstallerLocation = "C:\Program Files (x86)\SasView\unins000.exe"
Global $lTimeout = 10          ; 10 sec timeout for waiting on windows
Global $lInstallTimeout = 120  ; 2 min timeout for the installation process

; General globals
Global $installerPID = 0

;; MAIN SCRIPT
Install()
RunSasView()
Uninstall()
Exit(0)

;==============================================================

Func Install()
   ;;;;; APPLICATION INSTALLED ;;;;;;;
   Local $sSetupWindow = "Setup - SasView"
   Local $iFailFlag = 1
   ; Run setup
   if FileExists($fInstallerLocation) Then
	  $installerPID = Run($fInstallerLocation)
	  Assert($installerPID, $iFailFlag)
	  Sleep(1000)
   Else
	  ;$Error = ObjEvent(AutoIt.Error, "Setup file does not exist","123")
	  Exit($iFailFlag)
   EndIf

   ; License click through
   WinActivate($sSetupWindow)
   Local $test = WinWaitActive($sSetupWindow, "License Agreement", $lTimeout)
   ;ConsoleWrite("license agreement: " & $test)
   Assert($test, $iFailFlag)
   sleep(1000)

   Send("{TAB}{up}{ENTER}")

   ; Location
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Destination Location", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Icons, Startup entry
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Additional Tasks", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Ready to install...
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Ready to Install", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Final OK on running
   Sleep(5000)
   $test = WinWaitActive($sSetupWindow, "Completing the SasView Setup Wizard", $lInstallTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")
   ;ConsoleWrite("Installed" & @CRLF)

EndFunc

Func RunSasView()
   ;;;;; APPLICATION STARTED ;;;;;;;
   ; Start app - DEBUG ONLY
   ;;Run("C:\Program Files (x86)\SasView\SasView.exe")
   local $sActiveWindow = "SasView  - Fitting -"
   Local $iFailFlag = 2
   ; Wait for the window
   Sleep(1000)
   Local $hWnd = WinWaitActive($sActiveWindow, "", $lTimeout)
   Assert($hWnd, $iFailFlag)

   ;;;;; Load a File
   ; Open File Load dialog
   Send("!{f}{ENTER}")
   WinWaitActive("Choose a file", "", $lTimeout)
   Assert($hWnd, $iFailFlag)
   Sleep(200)

   ; Focus is in file chooser - enter filename
   Send("C:\Program Files (x86)\SasView\test\1d_data\cyl_400_20.txt")
   Sleep(1000)
   Send("{ENTER}")

   ;; Send file to fitting
   ControlClick($hWnd, "Send To", 231)

   ;; Choose a python model
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 1)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)
   ;; Assure we got the charts
   Local $hPlot = WinWait($sActiveWindow, "Graph2", $lTimeout)
   Assert($hPlot, $iFailFlag)
   $hPlot = WinWait($sActiveWindow, "Graph3", $lTimeout)
   Assert($hPlot, $iFailFlag)

   sleep(1000)
   ;; Calculate a compiled model
   ControlClick($hWnd, "Send To", 231)

   ;; Choose Shapes/Cylinder
   ControlCommand($hWnd, "", "ComboBox2", "SetCurrentSelection", 1)
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 11)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)

   ;; Assure we got another chart
   $hPlot = WinWait($sActiveWindow, "Graph4", $lTimeout)
   Assert($hPlot, $iFailFlag)

   ;; Close SasView
   WinClose($hWnd)

   Local $hEnd = WinWaitActive("Confirm Exit", "", $lTimeout)
   Assert($hEnd, $iFailFlag)
   ControlClick($hEnd, "", "[CLASS:Button; INSTANCE:1]")

   Local $sv_closed = WinWaitClose($hWnd, "", $lTimeout)
   Assert($sv_closed, $iFailFlag)

EndFunc

Func Uninstall()
;;;;; UNINSTALL ;;;;;;;
   Local $iFailFlag = 3
   $installerPID = Run($fUninstallerLocation)
   Assert($installerPID, $iFailFlag)

   Local $sSetupWindow = "SasView Uninstall"

   Local $test = WinWaitActive($sSetupWindow, "", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{TAB}{ENTER}")

   WinActivate("SasView Uninstal")
   $test = WinWaitActive($sSetupWindow, "SasView was successfully removed", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

EndFunc

;;; HELPER FUNCTIONS ;;;;
Func Assert($test, $lExitValue)
   ;;; Asserts $test to be non-zero and exit with code $lExitValue ;;;
   if $test == 0 Then
	  ProcessClose($installerPID)
	  Exit($lExitValue)
   EndIf
EndFunc

; ****** REMEMBER TO SWITCH OFF UAC ON TARGET MACHINE!!! *********
;
; This script will install, run and uninstall SasView
; given location of the installer. The exit code of the script
; points at failure location:
;
; 0 - OK
; 1 - Installer failure
; 2 - Problems running SasView (simple fitting)
; 3 - Uninstaller failure

#include <Constants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

; Modifiable globals
Global $fInstallerLocation = @TempDir & "\setupSasView.exe"
if $CmdLine[0] > 0 Then
   ; If argument present - use it as local download path
   $fInstallerLocation = $CmdLine[1]
EndIf

Global $fUninstallerLocation = "C:\Program Files (x86)\SasView\unins000.exe"
Global $lTimeout = 10          ; 10 sec timeout for waiting on windows
Global $lInstallTimeout = 120  ; 2 min timeout for the installation process

; General globals
Global $installerPID = 0

;; MAIN SCRIPT
Install()
RunSasView()
Uninstall()
Exit(0)

;==============================================================

Func Install()
   ;;;;; APPLICATION INSTALLED ;;;;;;;
   Local $sSetupWindow = "Setup - SasView"
   Local $iFailFlag = 1
   ; Run setup
   if FileExists($fInstallerLocation) Then
	  $installerPID = Run($fInstallerLocation)
	  Assert($installerPID, $iFailFlag)
	  Sleep(1000)
   Else
	  ;$Error = ObjEvent(AutoIt.Error, "Setup file does not exist","123")
	  Exit($iFailFlag)
   EndIf

   ; License click through
   WinActivate($sSetupWindow)
   Local $test = WinWaitActive($sSetupWindow, "License Agreement", $lTimeout)
   ;ConsoleWrite("license agreement: " & $test)
   Assert($test, $iFailFlag)
   sleep(1000)

   Send("{TAB}{up}{ENTER}")

   ; Location
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Destination Location", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Icons, Startup entry
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Additional Tasks", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Ready to install...
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Ready to Install", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Final OK on running
   Sleep(5000)
   $test = WinWaitActive($sSetupWindow, "Completing the SasView Setup Wizard", $lInstallTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")
   ;ConsoleWrite("Installed" & @CRLF)

EndFunc

Func RunSasView()
   ;;;;; APPLICATION STARTED ;;;;;;;
   ; Start app - DEBUG ONLY
   ;;Run("C:\Program Files (x86)\SasView\SasView.exe")
   Run("C:\util\SasView\SasView.exe")
   local $sActiveWindow = "SasView  - Fitting -"
   Local $iFailFlag = 2
   ; Wait for the window
   Sleep(1000)
   Local $hWnd = WinWaitActive($sActiveWindow, "", $lTimeout)
   Assert($hWnd, $iFailFlag)

   ;;;;; Load a File
   ; Open File Load dialog
   Send("!{f}{ENTER}")
   WinWaitActive("Choose a file", "", $lTimeout)
   Assert($hWnd, $iFailFlag)
   Sleep(200)

   ; Focus is in file chooser - enter filename
   Send("C:\Program Files (x86)\SasView\test\1d_data\cyl_400_20.txt")
   Sleep(1000)
   Send("{ENTER}")

   ;; Send file to fitting
   ControlClick($hWnd, "Send To", 231)

   ;; Choose a python model
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 1)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)
   ;; Assure we got the charts
   Local $hPlot = WinWait($sActiveWindow, "Graph2", $lTimeout)
   Assert($hPlot, $iFailFlag)
   $hPlot = WinWait($sActiveWindow, "Graph3", $lTimeout)
   Assert($hPlot, $iFailFlag)

   sleep(1000)
   ;; Calculate a compiled model
   ControlClick($hWnd, "Send To", 231)

   ;; Choose Shapes/Cylinder
   ControlCommand($hWnd, "", "ComboBox2", "SetCurrentSelection", 1)
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 11)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)

   ;; Assure we got another chart
   $hPlot = WinWait($sActiveWindow, "Graph4", $lTimeout)
   Assert($hPlot, $iFailFlag)

   ;; Close SasView
   WinClose($hWnd)

   Local $hEnd = WinWaitActive("Confirm Exit", "", $lTimeout)
   Assert($hEnd, $iFailFlag)
   ControlClick($hEnd, "", "[CLASS:Button; INSTANCE:1]")

   Local $sv_closed = WinWaitClose($hWnd, "", $lTimeout)
   Assert($sv_closed, $iFailFlag)

EndFunc

Func Uninstall()
;;;;; UNINSTALL ;;;;;;;
   Local $iFailFlag = 3
   $installerPID = Run($fUninstallerLocation)
   Assert($installerPID, $iFailFlag)

   Local $sSetupWindow = "SasView Uninstall"

   Local $test = WinWaitActive($sSetupWindow, "", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{TAB}{ENTER}")

   WinActivate("SasView Uninstal")
   $test = WinWaitActive($sSetupWindow, "SasView was successfully removed", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

EndFunc

;;; HELPER FUNCTIONS ;;;;
Func Assert($test, $lExitValue)
   ;;; Asserts $test to be non-zero and exit with code $lExitValue ;;;
   if $test == 0 Then
	  ProcessClose($installerPID)
	  Exit($lExitValue)
   EndIf
EndFunc


Updated deployment test script

Updated deployment test script

; ****** REMEMBER TO SWITCH OFF UAC ON TARGET MACHINE!!! *********
;
; This script will install, run and uninstall SasView
; given location of the installer. The exit code of the script
; points at failure location:
;
; 0 - OK
; 1 - Download failure
; 2 - Installer failure
; 3 - Problems running SasView (simple fitting)
; 4 - Uninstaller failure

#include <Constants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <InetConstants.au3>
#include <WinAPIFiles.au3>

; Custom error handler
;Global $oMyError = ObjEvent("AutoIt.Error","MyErrFunc")

; Modifiable globals
if $CmdLine[0] == 0 Then
   ; Expected command line with the build number as argument
   Exit (-1)
EndIf

Local $lBuildNumber = $CmdLine[1]
;Global $fInstallerLocation = "C:\util\setupSasView.exe" ; debug and testing location
Global $fInstallerLocation = @TempDir & "\setupSasView.exe"
Global $fRemoteInstallerLocation = "https://jenkins.esss.dk/sasview/job/SasView_Win7_Test/" & $lBuildNumber & "/artifact/sasview/dist/setupSasView.exe"
Global $fUninstallerLocation = "C:\Program Files (x86)\SasView\unins000.exe"
Global $lTimeout = 10          ; 10 sec timeout for waiting on windows
Global $lInstallTimeout = 120  ; 2 min timeout for the installation process

; General globals
Global $installerPID = 0

;; MAIN SCRIPT
Download()
Install()
RunSasView()
Uninstall()

Exit(0)

;==============================================================
Func Download()
   ; Download the file in the background with the selected option of 'force a reload from the remote site.'
   ConsoleWrite("Downloading...." & @CRLF)
   Local $iFailFlag = 1
   Local $hDownload = InetGet($fRemoteInstallerLocation, $fInstallerLocation, $INET_FORCERELOAD)

    ; Close the handle returned by InetGet.
    InetClose($hDownload)
	Assert($hDownload, $iFailFlag)
	ConsoleWrite("Installer downloaded successfully to " & $fInstallerLocation & @CRLF)

EndFunc

Func Install()
   ;;;;; APPLICATION INSTALLED ;;;;;;;
   Local $sSetupWindow = "Setup - SasView"
   Local $iFailFlag = 2
   ; Run setup
   if FileExists($fInstallerLocation) Then
	  $installerPID = Run($fInstallerLocation)
	  Assert($installerPID, $iFailFlag)
	  Sleep(1000)
   Else
	  ;$Error = ObjEvent(AutoIt.Error, "Setup file does not exist","123")
	  Exit($iFailFlag)
   EndIf

   ; License click through
   WinActivate($sSetupWindow) ; <-- REQUIRED when connecting from another host
   Local $test = WinWaitActive($sSetupWindow, "License Agreement", $lTimeout)
   ;ConsoleWrite("license agreement: " & $test)
   Assert($test, $iFailFlag)
   sleep(1000)

   Send("{TAB}{up}{ENTER}")

   ; Location
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Destination Location", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Icons, Startup entry
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Additional Tasks", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Ready to install...
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Ready to Install", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Final OK on running
   Sleep(5000)
   $test = WinWaitActive($sSetupWindow, "Completing the SasView Setup Wizard", $lInstallTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")
   ;ConsoleWrite("Installed" & @CRLF)

EndFunc

Func RunSasView()
   ;;;;; APPLICATION STARTED ;;;;;;;
   ; Start app - DEBUG ONLY
   ;;Run("C:\Program Files (x86)\SasView\SasView.exe")
   Local $iFailFlag = 2
   ; Wait for the window
   Sleep(1000)
   Local $hWnd = WinWaitActive("SasView  - Fitting -", "", $lTimeout)
   Assert($hWnd, $iFailFlag)

   ;;;;; Load a File
   ; Open File Load dialog
   Send("!{f}{ENTER}")
   WinWaitActive("Choose a file", "", $lTimeout)
   Assert($hWnd, $iFailFlag)
   Sleep(200)

   ; Focus is in file chooser - enter filename
   Send("C:\Program Files (x86)\SasView\test\1d_data\cyl_400_20.txt")
   Sleep(1000)
   Send("{ENTER}")

   ;; Send file to fitting
   ControlClick($hWnd, "Send To", 231)

   ;; Choose a model
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 1)

   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)

   ;; Close SasView
   WinClose($hWnd)

   Local $hEnd = WinWaitActive("Confirm Exit", "", $lTimeout)
   Assert($hEnd, $iFailFlag)
   ControlClick($hEnd, "", "[CLASS:Button; INSTANCE:1]")

   Local $sv_closed = WinWaitClose($hWnd, "", $lTimeout)
   Assert($sv_closed, $iFailFlag)

EndFunc

Func Uninstall()
;;;;; UNINSTALL ;;;;;;;
   Local $iFailFlag = 3
   $installerPID = Run($fUninstallerLocation)
   Assert($installerPID, $iFailFlag)

   Local $sSetupWindow = "SasView Uninstall"

   Local $test = WinWaitActive($sSetupWindow, "", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{TAB}{ENTER}")

   WinActivate("SasView Uninstal")
   $test = WinWaitActive($sSetupWindow, "SasView was successfully removed", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

EndFunc

;;; HELPER FUNCTIONS ;;;;
Func Assert($test, $lExitValue)
   ;;; Asserts $test to be non-zero and exit with code $lExitValue ;;;
   if $test == 0 Then
	  ProcessClose($installerPID)
	  Exit($lExitValue)
   EndIf
EndFunc

; ****** REMEMBER TO SWITCH OFF UAC ON TARGET MACHINE!!! *********
;
; This script will install, run and uninstall SasView
; given location of the installer. The exit code of the script
; points at failure location:
;
; 0 - OK
; 1 - Installer failure
; 2 - Problems running SasView (simple fitting)
; 3 - Uninstaller failure

#include <Constants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

; Custom error handler
;Global $oMyError = ObjEvent("AutoIt.Error","MyErrFunc")

; Modifiable globals
Global $fInstallerLocation = "C:\util\setupSasView.exe"
Global $lTimeout = 10          ; 10 sec timeout for waiting on windows
Global $lInstallTimeout = 120  ; 2 min timeout for the installation process

; General globals
Global $installerPID = 0

;; MAIN SCRIPT
Install()
RunSasView()
Uninstall()
Exit(0)

;==============================================================
Func Install()
   ;;;;; APPLICATION INSTALLED ;;;;;;;
   Local $sSetupWindow = "Setup - SasView"

   ; Run setup
   if FileExists($fInstallerLocation) Then
	  $installerPID = Run($fInstallerLocation)
	  Assert($installerPID, 1)
	  Sleep(1000)
   Else
	  ;$Error = ObjEvent(AutoIt.Error, "Setup file does not exist","123")
	  Exit(1)
   EndIf

   ; License click through
   Local $test = WinWaitActive($sSetupWindow, "License Agreement", $lTimeout)
   ;ConsoleWrite("license agreement: " & $test)
   Assert($test, 1)
   sleep(1000)

   Send("{TAB}{up}{ENTER}")

   ; Location
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Destination Location", $lTimeout)
   Assert($test, 1)
   Send("{ENTER}")

   ; Icons, Startup entry
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Additional Tasks", $lTimeout)
   Assert($test, 1)
   Send("{ENTER}")

   ; Ready to install...
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Ready to Install", $lTimeout)
   Assert($test, 1)
   Send("{ENTER}")

   ; Final OK on running
   Sleep(5000)
   $test = WinWaitActive($sSetupWindow, "Completing the SasView Setup Wizard", $lInstallTimeout)
   Assert($test, 1)
   Send("{ENTER}")
   ;ConsoleWrite("Installed" & @CRLF)

EndFunc

Func RunSasView()
   ;;;;; APPLICATION STARTED ;;;;;;;
   ; Start app - DEBUG ONLY
   ;;Run("C:\Program Files (x86)\SasView\SasView.exe")

   ; Wait for the window
   Sleep(1000)
   Local $hWnd = WinWaitActive("SasView  - Fitting -", "", $lTimeout)
   Assert($hWnd, 2)

   ;;;;; Load a File
   ; Open File Load dialog
   Send("!{f}{ENTER}")
   WinWaitActive("Choose a file", "", $lTimeout)
   Assert($hWnd, 2)
   Sleep(200)

   ; Focus is in file chooser - enter filename
   Send("C:\Program Files (x86)\SasView\test\1d_data\cyl_400_20.txt")
   Sleep(1000)
   Send("{ENTER}")

   ;; Send file to fitting
   ControlClick($hWnd, "Send To", 231)

   ;; Choose a model
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 1)

   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)

   ;; Close SasView
   WinClose($hWnd)

   Local $hEnd = WinWaitActive("Confirm Exit", "", $lTimeout)
   Assert($hEnd, 2)
   ControlClick($hEnd, "", "[CLASS:Button; INSTANCE:1]")

   Local $sv_closed = WinWaitClose($hWnd, "", $lTimeout)
   Assert($sv_closed, 2)

EndFunc

Func Uninstall()
;;;;; UNINSTALL ;;;;;;;
   $installerPID = Run("C:\Program Files (x86)\SasView\unins000.exe")

   Local $sSetupWindow = "SasView Uninstall"

   Local $test = WinWaitActive($sSetupWindow, "", $lTimeout)
   Assert($test, 3)
   Send("{TAB}{ENTER}")

   WinActivate("SasView Uninstal")
   $test = WinWaitActive($sSetupWindow, "SasView was successfully removed", $lTimeout)
   Assert($test, 3)
   Send("{ENTER}")

EndFunc

;;; HELPER FUNCTIONS ;;;;
Func Assert($test, $lExitValue)
   ;;; Asserts $test to be non-zero and exit with code $lExitValue ;;;
   if $test == 0 Then
	  ProcessClose($installerPID)
	  Exit($lExitValue)
   EndIf
EndFunc


Removed a deployment test - at best it was in the wrong place

; ****** REMEMBER TO SWITCH OFF UAC ON TARGET MACHINE!!! *********
;
; This script will install, run and uninstall SasView
; given location of the installer. The exit code of the script
; points at failure location:
;
; 0 - OK
; 1 - Installer failure
; 2 - Problems running SasView (simple fitting)
; 3 - Uninstaller failure

#include <Constants.au3>
#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

; Modifiable globals
Global $fInstallerLocation = @TempDir & "\setupSasView.exe"
if $CmdLine[0] > 0 Then
   ; If argument present - use it as local download path
   $fInstallerLocation = $CmdLine[1]
EndIf

Global $fUninstallerLocation = "C:\Program Files (x86)\SasView\unins000.exe"
Global $lTimeout = 10          ; 10 sec timeout for waiting on windows
Global $lInstallTimeout = 120  ; 2 min timeout for the installation process

; General globals
Global $installerPID = 0

;; MAIN SCRIPT
Install()
RunSasView()
Uninstall()
Exit(0)

;==============================================================

Func Install()
   ;;;;; APPLICATION INSTALLED ;;;;;;;
   Local $sSetupWindow = "Setup - SasView"
   Local $iFailFlag = 1
   ; Run setup
   if FileExists($fInstallerLocation) Then
	  $installerPID = Run($fInstallerLocation)
	  Assert($installerPID, $iFailFlag)
	  Sleep(1000)
   Else
	  ;$Error = ObjEvent(AutoIt.Error, "Setup file does not exist","123")
	  Exit($iFailFlag)
   EndIf

   ; License click through
   WinActivate($sSetupWindow)
   Local $test = WinWaitActive($sSetupWindow, "License Agreement", $lTimeout)
   ;ConsoleWrite("license agreement: " & $test)
   Assert($test, $iFailFlag)
   sleep(1000)

   Send("{TAB}{up}{ENTER}")

   ; Location
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Destination Location", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Icons, Startup entry
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Select Additional Tasks", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Ready to install...
   Sleep(1000)
   $test = WinWaitActive($sSetupWindow, "Ready to Install", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

   ; Final OK on running
   Sleep(5000)
   $test = WinWaitActive($sSetupWindow, "Completing the SasView Setup Wizard", $lInstallTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")
   ;ConsoleWrite("Installed" & @CRLF)

EndFunc

Func RunSasView()
   ;;;;; APPLICATION STARTED ;;;;;;;
   ; Start app - DEBUG ONLY
   ;;Run("C:\Program Files (x86)\SasView\SasView.exe")
   local $sActiveWindow = "SasView  - Fitting -"
   Local $iFailFlag = 2
   ; Wait for the window
   Sleep(1000)
   Local $hWnd = WinWaitActive($sActiveWindow, "", $lTimeout)
   Assert($hWnd, $iFailFlag)

   ;;;;; Load a File
   ; Open File Load dialog
   Send("!{f}{ENTER}")
   WinWaitActive("Choose a file", "", $lTimeout)
   Assert($hWnd, $iFailFlag)
   Sleep(200)

   ; Focus is in file chooser - enter filename
   Send("C:\Program Files (x86)\SasView\test\1d_data\cyl_400_20.txt")
   Sleep(1000)
   Send("{ENTER}")

   ;; Send file to fitting
   ControlClick($hWnd, "Send To", 231)

   ;; Choose a python model
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 1)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)
   ;; Assure we got the charts
   Local $hPlot = WinWait($sActiveWindow, "Graph2", $lTimeout)
   Assert($hPlot, $iFailFlag)
   $hPlot = WinWait($sActiveWindow, "Graph3", $lTimeout)
   Assert($hPlot, $iFailFlag)

   sleep(1000)
   ;; Calculate a compiled model
   ControlClick($hWnd, "Send To", 231)

   ;; Choose Shapes/Cylinder
   ControlCommand($hWnd, "", "ComboBox2", "SetCurrentSelection", 1)
   ControlCommand($hWnd, "", "ComboBox3", "SetCurrentSelection", 11)
   ;; Calculate the model
   ControlClick($hWnd, "Compute", 211)

   ;; Assure we got another chart
   $hPlot = WinWait($sActiveWindow, "Graph4", $lTimeout)
   Assert($hPlot, $iFailFlag)

   ;; Close SasView
   WinClose($hWnd)

   Local $hEnd = WinWaitActive("Confirm Exit", "", $lTimeout)
   Assert($hEnd, $iFailFlag)
   ControlClick($hEnd, "", "[CLASS:Button; INSTANCE:1]")

   Local $sv_closed = WinWaitClose($hWnd, "", $lTimeout)
   Assert($sv_closed, $iFailFlag)

EndFunc

Func Uninstall()
;;;;; UNINSTALL ;;;;;;;
   Local $iFailFlag = 3
   $installerPID = Run($fUninstallerLocation)
   Assert($installerPID, $iFailFlag)

   Local $sSetupWindow = "SasView Uninstall"

   Local $test = WinWaitActive($sSetupWindow, "", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{TAB}{ENTER}")

   WinActivate("SasView Uninstal")
   $test = WinWaitActive($sSetupWindow, "SasView was successfully removed", $lTimeout)
   Assert($test, $iFailFlag)
   Send("{ENTER}")

EndFunc

;;; HELPER FUNCTIONS ;;;;
Func Assert($test, $lExitValue)
   ;;; Asserts $test to be non-zero and exit with code $lExitValue ;;;
   if $test == 0 Then
	  ProcessClose($installerPID)
	  Exit($lExitValue)
   EndIf
EndFunc