instPath = SystemPath( "ScriptPath" )

# turn everything OFF first
KillScript("loop.mscr")
RemoveNotifications(instPath&"\TitaniumWeather.exe")
#RunOnPowerOn (instPath&"\TitaniumWeather.exe")

# update interval set by user in minutes
usertime = RegRead("HKLM","Software\TitaniumWeather","usertime")*60
forceupdate = RegRead("HKLM","Software\TitaniumWeather","forceupdate")

# For manual updates (if usertime = 0, no scheduling is required)
If (forceupdate && (usertime <> 0))
	nextupdate = TimeStamp()+usertime
	RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
	RegWriteDWord("HKLM","Software\TitaniumWeather","forceupdate",0)
	RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)

# For auto updates
ElseIf (usertime > 0)
	offtime = RegRead("HKLM", "Software\TitaniumWeather","OFFtime")
	ontime = RegRead("HKLM", "Software\TitaniumWeather","ONtime")

	# make sure ON/OFF times are valid hours
	If ( (offtime >= 0) AND (offtime <= 24) AND (ontime >= 0) AND (ontime <= 24) )
		GetTime(currhour,currmin,currsec,currday,currmonth,curryear)

		# no wrap-around at midnight (hour 0)
		If (offtime > ontime)
			If (currhour >= ontime)
				If (currhour < offtime)
					# ON
					nextupdate = TimeStamp()+usertime
					RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
					RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
				Else
					# OFF - schedule for tomorrow
					RegWriteDWord("HKLM","Software\TitaniumWeather","fupdate",1)
					nextupdate = TimeStamp() + (ontime+24-currhour)*3600 - (currmin)*60 + Rand(300)
					RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
					RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
					#Run(instPath&"\loop.exe")
					exit
				EndIf
			Else
				# OFF - schedule for today
				RegWriteDWord("HKLM","Software\TitaniumWeather","fupdate",1)
				nextupdate = TimeStamp() + (ontime-currhour)*3600 - (currmin)*60 + Rand(300)
				RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
				RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
				#Run(instPath&"\loop.exe")
				exit
			EndIf
		# wrap-around midnight
		Else
			If ( (currhour < ontime) AND (currhour >= offtime) )
				# OFF
				RegWriteDWord("HKLM","Software\TitaniumWeather","fupdate",1)
				nextupdate = TimeStamp() + (ontime-currhour)*3600 - (currmin)*60 + Rand(300)
				RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
				RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
				#Run(instPath&"\loop.exe")
				exit
			Else
				# ON
				nextupdate = TimeStamp()+usertime
				RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
				RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
			EndIf
		EndIf

	# invalid ON/OFF times or always update
	Else
		nextupdate = TimeStamp()+usertime
		RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
		RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
	EndIf
EndIf

# do not try to update if a call is active, try again in 5 min
If (RegRead("HKLM","System\State\Phone","Status") AND 537067520)
	RemoveNotifications(instPath&"\TitaniumWeather.exe")
	nextupdate = TimeStamp()+300
	RunAt(nextupdate, instPath&"\TitaniumWeather.exe")
	RegWriteDWord("HKLM","Software\TitaniumWeather","nextupdate",nextupdate)
	exit
EndIf

#####################

If (RegValueExists("HKLM","Software\TitaniumWeather","fupdate"))
 	fupdate = RegRead("HKLM", "Software\TitaniumWeather","fupdate")
Else
	fupdate = 1
	RegWriteDWord("HKLM","Software\TitaniumWeather","fupdate",fupdate)
EndIf

location = RegRead("HKLM", "Software\TitaniumWeather","code")
units = RegRead("HKLM", "Software\TitaniumWeather","units")
startconn = RegRead("HKLM", "Software\TitaniumWeather","Connect")
icontype = RegRead("HKLM", "Software\TitaniumWeather","Icons")

If (usertime = 0)
	fupdate = 1
EndIf

If (units eq "F")
	metric = 0
	windunits = " mph"
	distunits = " miles"
	precipunits = " in"
Else
	metric = 1
	windunits = " kph"
	distunits = " km"
	precipunits = " mm"
EndIf

#Update Panel
RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","0")
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","Time","Connecting")
RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","1")

If (startconn)
   connect("The Internet")
   Sleep 500
EndIf

If(InternetConnected("http://google.com/m"))

	Call Accuweather

	#Update Panel
	RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","1")
	units = ToUpper(units)
		

	Call WriteCurrent
	Call WriteForecast

	#Update Panel
	RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","Time","Completed")
	RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","0")

Else
	exit
EndIf

RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","Time",updatetime)
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","City",City)
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\CondensedPage","City",City)
RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","1")

wmsg=1
Return(wmsg)

Exit

###########################################

Sub AccuWeather

link=ReadFile("http://wwwa.accuweather.com/adcbin/forecastfox/weather_data.asp?location="&location&"&metric="&metric)

Split(link, "<day ", TRUE, curdata, forecastdata[1], forecastdata[2], forecastdata[3], forecastdata[4], forecastdata[5]);

# check if location is valid
If (Find(link, "<failure>"))
	#Update Panel
	RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","Time","Invalid location.")
	RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","0")
	Exit
EndIf

#Update Panel
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","Time","Downloading")
RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","0")

daynum = 1

##Get Current
pos = Find(curdata,"<city>")
If (pos)
	pos = pos + 6
	len = Find(curdata, "</city>",pos)-pos
	City = SubStr(curdata,pos,len)
EndIf

updatetime = FormatTime("h:i A")

#pos = Find(curdata,"<pressure state=")
#If (pos)
#	pos = pos + 17
#	len = Find(curdata, "</pressure>",pos)-pos
#	bar = SubStr(curdata,pos,len)
#	bar = Replace(bar,""">"," ")
#EndIf

pos = Find(curdata,"<temperature>")
If (pos)
	pos = pos + 13
	len = Find(curdata, "</temperature>",pos)-pos
	ctemp = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<realfeel>")
If (pos)
	pos = pos + 10
	len = Find(curdata, "</realfeel>",pos)-pos
	realfeel = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<weathericon>")
If (pos)
	pos = pos + 13
	len = Find(curdata, "</weathericon>",pos)-pos
	ccode = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<humidity>")
If (pos)
	pos = pos + 10
	len = Find(curdata, "</humidity>",pos)-pos
	humidity = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<weathertext>")
If (pos)
	pos = pos + 13
	len = Find(curdata, "</weathertext>",pos)-pos
	ccond = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<visibility>")
If (pos)
	pos = pos + 12
	len = Find(curdata, "</visibility>",pos)-pos
	vis = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<uvindex")
If (pos)
	pos = pos + 16
	len = Find(curdata, "</uvindex>",pos)-pos
	uvindex = SubStr(curdata,pos,len)
	uvindex = Replace(uvindex,""">"," (")&")"
EndIf

pos = Find(curdata,"<dewpoint>")
If (pos)
	pos = pos + 10
	len = Find(curdata, "</dewpoint>",pos)-pos
	dewpt = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<cloudcover>")
If (pos)
	pos = pos + 12
	len = Find(curdata, "%</cloudcover>",pos)-pos
	clouds = SubStr(curdata,pos,len)
	# can't get round function to word
	clouds = part(clouds,".",1) & "%"
EndIf

pos = Find(curdata,"<windspeed>")
If (pos)
	pos = pos + 11
	len = Find(curdata, "</windspeed>",pos)-pos
	cwindspeed = SubStr(curdata,pos,len)
EndIf

pos = Find(curdata,"<winddirection>")
If (pos)
	pos = pos + 15
	len = Find(curdata, "</winddirection>",pos)-pos
	cwinddir = SubStr(curdata,pos,len)

	If(cwinddir eq "CLM")
		cwinddir = "Calm"
	EndIf
EndIf

pos = Find(curdata,"<precip>")
If (pos)
	pos = pos + 8
	len = Find(curdata, "</precip>",pos)-pos
	cprecip = SubStr(curdata,pos,len)
EndIf

##Get wind gust
pos = Find(forecastdata[1],"<windgust>")
If (pos)
	pos = pos + 10
	len = Find(forecastdata[1], "</windgust>",pos)-pos
	cwindgust = SubStr(forecastdata[1],pos,len)
EndIf

#end Get Current

##Get Forecast
If (fupdate = 1)
	For i = 1 to 5 step 1
		Call("Forecast", forecastdata[i])
	Next
EndIf

EndSub
#########################

Sub Forecast

fdata = argv[1]

pos = Find(fdata,"number=")
if(pos)
	daynum = SubStr(fdata,pos+8,1)
	#Update Panel
	RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","1")
	RegWriteDWord ("HKLM", "Software\Microsoft\CHome\TitaniumWeather","Updated","0")

	pos = Find(fdata,"<obsdate>")
	If (pos)
		pos = pos + 9
		endspot = Find(fdata,"</obsdate>",pos)-pos
		date[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<daycode>")
	If (pos)
		pos = pos + 9
		endspot = Find(fdata,"</daycode>",pos)-pos
		day[daynum] = FormatTime ("{WW}", Timestamp() +86400*daynum-86400 )
	EndIf

	pos = Find(fdata,"<sunrise>")
	If (pos)
		pos = pos + 9
		endspot = Find(fdata,"</sunrise>",pos)-pos
		sunrise[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<sunset>")
	If (pos)
		pos = pos + 8
		endspot = Find(fdata,"</sunset>",pos)-pos
		sunset[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<txtshort>")
	If (pos)
		pos = pos + 10
		endspot = Find(fdata,"</txtshort>",pos)-pos
		shortdesc[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<weathericon>")
	If (pos)
		pos = pos + 13
		endspot = Find(fdata,"</weathericon>",pos)-pos
		icon[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<hightemperature>")
	If (pos)
		pos = pos + 17
		endspot = Find(fdata,"</hightemperature>",pos)-pos
		high[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<lowtemperature>")
	If (pos)
		pos = pos + 16
		endspot = Find(fdata,"</lowtemperature>",pos)-pos
		low[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<realfeelhigh>")
	If (pos)
		pos = pos + 14
		endspot = Find(fdata,"</realfeelhigh>",pos)-pos
		realfeelhi[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<realfeellow>")
	If (pos)
		pos = pos + 13
		endspot = Find(fdata,"</realfeellow>",pos)-pos
		realfeello[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<windspeed>")
	If (pos)
		pos = pos + 11
		endspot = Find(fdata,"</windspeed>",pos)-pos
		windspeed[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<winddirection>")
	If (pos)
		pos = pos + 15
		endspot = Find(fdata,"</winddirection>",pos)-pos
		winddir[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<windgust>")
	If (pos)
		pos = pos + 10
		endspot = Find(fdata,"</windgust>",pos)-pos
		windgust[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<maxuv>")
	If (pos)
		pos = pos + 7
		endspot = Find(fdata,"</maxuv>",pos)-pos
		uv[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<precipamount>")
	If (pos)
		pos = pos + 14
		endspot = Find(fdata,"</precipamount>",pos)-pos
		prec[daynum] = SubStr(fdata,pos,endspot)
	EndIf

	pos = Find(fdata,"<tstormprob>")
	If (pos)
		pos = pos + 12
		endspot = Find(fdata,"</tstormprob>",pos)-pos
		tstormprob[daynum] = SubStr(fdata,pos,endspot)
	EndIf
EndIf
EndSub


########################

Sub WriteCurrent

RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\CondensedPage","CurrentTemp",ctemp&"°")
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","CurrentIcon",instPath&"\"&ccode&".png")
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\CondensedPage","CurrentIcon",instPath&"\"&ccode&".png")
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","CurrentTemp",ctemp&"°")

# write current detail page
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page2","CurrentIcon",instPath&"\"&ccode&".png")
RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page2","CurrentTemp2",ctemp&"°")
RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page2","Desc",City&" feels like "&realfeel&"°")
RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page2","Winds","Winds: "&cwinddir&" "&cwindspeed&windunits&", Gusts to "&cwindgust)
RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page2","Prec","Prec: "&cprecip&" "&precipunits&", Visibility: "&vis&" "&distunits)
RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page2","Other","Cloudcover: "&clouds&", Humidity: "&humidity)


#Write to S2U2
If (RegKeyExists("HKCU","Software\A_C\S2U2"))
	RegWriteString("HKCU","Software\A_C\S2U2","UserWeather","C|"&ccode&"|"&ctemp&",  Feels Like "&realfeel)
EndIf

EndSub

########################

Sub WriteForecast

dct = 2
# format forecast days
For ct = 1 to 5 step 1

	shortday = SubStr(day[ct], 1, 3)
	shortday = ToUpper(shortday)
	dct = dct + 1

	# Only update the number of forecast days received (only 4 days are received around 12am - 2am)
	RegWriteDWord("HKLM","Software\TitaniumWeather","forecastdays", daynum)
	If (daynum >= ct)
		RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page1","Day"&ct&"Icon",instPath&"\"&icon[ct]&".png")
		RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\CondensedPage","Day"&ct&"Icon",instPath&"\"&icon[ct]&".png")
	Else
		RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page1","Day"&ct&"Icon",instPath&"\blank.png")
		RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\CondensedPage","Day"&ct&"Icon",instPath&"\blank.png")
	EndIf
	# Write forecast detail pages

	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Day",day[ct]&", "&date[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Desc",shortdesc[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Temps",high[ct]&"/"&low[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Winds",winddir[ct]&" "&windspeed[ct]&windunits&", Gusts to "&windgust[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Prec","Chance of Prec: "&tstormprob[ct]&"%, UV Level: "&uv[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"Other","Sunrise: "&sunrise[ct]&", Sunset: "&sunset[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page"&dct,"ForecastIcon",instPath&"\"&icon[ct]&".png")
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\Page1","Day"&ct,shortday&"^CR^"&high[ct]&"/"&low[ct])
	RegWriteString("HKLM","Software\Microsoft\CHome\TitaniumWeather\CondensedPage","Day"&ct,shortday&"^CR^"&high[ct]&"/"&low[ct])

Next
	RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page1","TodayTemps",high[1]&"°/"&low[1]&"°")
	RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\CondensedPage","TodayTemps",high[1]&"°/"&low[1]&"°")
	RegWriteString ("HKLM", "Software\Microsoft\CHome\TitaniumWeather\Page2","TodayTemps",high[1]&"°/"&low[1]&"°")

EndSub
