--  ========================================================================
--
--  FILE: fillstore.lua
--
--  SERVICES: 
--     This script comes down with the data package, to store dpkg into store  
--     This script is expected to be concatenated into the same lua file as the datapackage
--
--  ========================================================================
--  ========================================================================
--
--               Copyright  1999-2006 QUALCOMM Incorporated
--                     All Rights Reserved.
--                   QUALCOMM Proprietary/GTDR
--
--  ========================================================================
--  ========================================================================

------------------------------------------------------------------------------
--                         Helper functions                                 --
------------------------------------------------------------------------------

fsRemoveDebugMessages = false

if fsRemoveDebugMessages then
   printfn = print
   function print()

   end

end

--Checks to see if "value" is a valid number 
-- Needed because tonumber() returns FALSE for floating point numbers
-- in ILua
function checkNumber(value)

	if string.find(value, "^%d+$")
	   	or string.find(value, "^%d+%.%d+$")
		or string.find(value, "^%.%d+$") then
			return true
	else
		return false
	end
	

end

function isTableEmpty(inTable)
	
	for k,v in pairs(inTable) do
		return false
	end
	
	return true

end
function getSortedShowtimes(sTimes)
    --_, nvow = string.gsub(text, "[AEIOUaeiou]", "")
    local sTable = {}
    local count = 1

    if sTimes then
	    for w in string.gfind(sTimes, "[:%a%d]+") do
		sTable[count] = w
		count = count + 1
	    end
   end

    return sTable
end

		
------------------------------------------------------------------------------
--             Function: getValueAndDirection(stringdata)                   --
--             Interprets a string like "+2.4" to mean this:                --
--             change    = 2.4                                              --
--             direction = up                                               --
------------------------------------------------------------------------------
function getValueAndDirection(stringdata)
   local startsearch = 1
   local nosign = true
   local sign = string.sub(stringdata,1,1)
   if sign == "+" or sign == "-" then
	   startsearch = 2
	   nosign = false
   end
	   
   if string.find(stringdata,"^0+%.0+$",startsearch) -- matches 0.0 0.00 000.0000 etc
	   or string.find(stringdata,"^0+$",startsearch) -- matches 0 00 000 00000 etc
	   or string.find(stringdata,"^%.0+$",startsearch) -- matches .0 .00 .0000 etc
	   or tonumber(stringdata) == 0 then
        value = "0.00"
        direction = "unchg"
   else
        if nosign then
		if not checkNumber(stringdata) then
			value = ""
			direction = "default"
		else
	        	value = stringdata
			direction = "up"
		end
	else
		value = string.sub(stringdata,2)
		if not checkNumber(value) then
			value = ""
			direction = "default"
		else
			if sign == "+" then
			 	direction = "up"
			elseif sign == "-" then
				direction = "down"
			else
				value = ""
				direction = "default"
			end  
		end
	end
  end

   return value,direction
   
end


--stub function - replace with actual function from interface layer
-- Notify interface layer that a new image has arrived for the short name "k"

function notifyImageChange(k,v)

   return

end



------------------------------------------------------------------------------
--                      Function fillimages()                               --
--    Fills the images table from the data package into the datastore       --
------------------------------------------------------------------------------
function fillimages()

	if images then
		print( "Fillstore: Updating images table from datapackage")
		for k,v in pairs(images) do
		
			if datastore.images[k] then
			
			    --an image already exists for this shortname
			    --need to update interface layer with the new image
			    
			    notifyImageChange(k,v)
			    
			end -- if datastore...
			
			datastore.images[k] = v
		        table.insert(datastore.downloadImages, k)
			
		end -- for k,v

	images = nil -- reset images from fillstore environment
		
	end -- if images

      
end -- fillimages



function fillmarketing()

	if marketing then
		datastore.marketing = marketing
	end
end
------------------------------------------------------------------------------
--                      Function fillmoney()                               --
--    Fills the money table from the data package into the datastore        --
------------------------------------------------------------------------------
function fillmoney()

   if money then

	  print( "Fillstore: Updating money table from datapackage")


	  ctable = datastore.money.portfolio

	  for k,v in pairs(money) do

		  if k == "NASDAQ" or k == "DJX" or k == "SnP500" then
		  --change money.markets
		  	datastore.money.markets[k] = {}
			datastore.money.markets[k].value = money[k].last
			datastore.money.markets[k].change, datastore.money.markets[k].direction = getValueAndDirection(money[k].change)

	          else
	 		ctable[k] = {}
			ctable[k].ticker                     = money[k].ticker
			ctable[k].label                      = money[k].label
		  	ctable[k].value                      = money[k].last
		  	ctable[k].change, ctable[k].direction = getValueAndDirection(money[k].change)
	          end		

	  end -- end for
   money = nil
   end -- if money
  
    --Next up: Money details table
    
  if money_details then

	  print( "Fillstore: Updating money details table from datapackage")
        ctable = datastore.money.stockdetails
	
	    for k,v in pairs(money_details) do


	        ctable[k] = {}

			ctable[k].name = money_details[k].name
			ctable[k].index = money_details[k].index
			ctable[k].details = money_details[k].details
			
			--remove these after data packages become available
			
	        ctable[k].exchange    = money_details[k].exchange
		    ctable[k].prevClose   = money_details[k].prevClose
			ctable[k].OpenPrice   = money_details[k].OpenPrice
			ctable[k].dayRange    = money_details[k].dayRange
			ctable[k].p52wkrange  = money_details[k].p52wkrange
			ctable[k].Volume      = money_details[k].Volume

			--end remove these
			

	    end
	    money_details = nil
    
  end -- if money_details
    
end  -- end fillmoney()




------------------------------------------------------------------------------
--                      Function fillmovies()                               --
--    Fills the movies table from the data package into the datastore       --
------------------------------------------------------------------------------
function fillmovies()

  if movie_ids then
	  print( "Fillstore: Updating movie list table from datapackage")
	ctable = datastore.movies.movielist
	
	for k,v in pairs(movie_ids) do
	    ctable[k] = {}
		ctable[k].name         =   movie_ids[k].name
		ctable[k].genre        =   movie_ids[k].genre
		ctable[k].rating       =   movie_ids[k].rating
		ctable[k].newMovieFlag =   movie_ids[k].flag -- meaning of this flag is changed in the new SAS
	
	end
  
	movie_ids = nil
  end  -- if movie_ids
  



        
  if movie_theaters then
	  print( "Fillstore: Updating movie theaters table from datapackage")
	  ctable = datastore.movies.theatres
	  
	  for k,v in pairs(movie_theaters) do

	    if ctable[k] == nil then
	      ctable[k] = {}
	    end
	    
		ctable[k].name     = movie_theaters[k].name
		ctable[k].address  = movie_theaters[k].address
		ctable[k].city     = movie_theaters[k].city
		ctable[k].state    = movie_theaters[k].state
		ctable[k].zipcode  = movie_theaters[k].zipcode
		ctable[k].phone    = movie_theaters[k].phone
		
	  end
	  movie_theaters = nil
	  
  end   -- if movie_theatres



  
  
  if movie_times_per_theater then
	  print( "Fillstore: Updating movie times per theater table from datapackage")

	for k,v in pairs(movie_times_per_theater) do -- k = movie_id
	   if datastore.movies.movieshowsbytheatre == nil then
		  datastore.movies.movieshowsbytheatre = {}
	   end

	   --first create (or remove old) entry for the list of movies for this theatre 
	     datastore.movies.movieshowsbytheatre[k] = {}

	   --now remove the entries for this theater from the movie_tickets table as well

	   for key,val in pairs(datastore.movies.movie_tickets_per_movie_and_theatre) do
		   -- key contains movie_id
		   -- now iterate over each movie_id
		   for key2, val2 in pairs(val) do
			   --key2 = theatre
			   if key2 == k then -- if the theater exists in the table - remove it's information
				   datastore.movies.movie_tickets_per_movie_and_theatre[key][key2] = nil
			   end
		   end
				   

	   end
	   
	   --here "k2" will be the day id and "v2" will be the table for that dayid
	   for k2,v2 in pairs(v) do
	   
		   --create entry for day id
		     datastore.movies.movieshowsbytheatre[k][k2] = {}

		   --here "k3" is a theatre id and "v3" is the table that holds its showtimes
		   for k3,v3 in pairs(v2) do
		   	datastore.movies.movieshowsbytheatre[k][k2][k3] = v3	
		   end --end for k3,v3
	     
	     
	   end --end for k2,v2
	   
	end --end for k,v
	
	movie_times_per_theater = nil
  end  --end if movie times per theater
  
  if theater_times_per_movie then
	  print( "Fillstore: Updating theater times per movie table from datapackage")
  
	 for k,v in pairs(theater_times_per_movie) do
		   if datastore.movies.theatreshowsbymovie == nil then
			  datastore.movies.theatreshowsbymovie = {}
		   end

		   --first create (or remove the old entry) for the list of theatres for this movie 
		     datastore.movies.theatreshowsbymovie[k] = {}

		   --remove the entry for this movie from movie_tickets table

		     if datastore.movies.movie_tickets_per_movie_and_theatre and datastore.movies.movie_tickets_per_movie_and_theatre[k] then
			     datastore.movies.movie_tickets_per_movie_and_theatre[k] = nil
		     end


		   --here "k2" will be the day id and "v2" will be the table for that dayid
		   for k2,v2 in pairs(v) do

			   --create entry for day id, if it doesn't already exist
			     datastore.movies.theatreshowsbymovie[k][k2] = {}

			   --here "k3" is a theatre id and "v3" is the string that holds its showtimes
			   for k3,v3 in pairs(v2) do
		           	datastore.movies.theatreshowsbymovie[k][k2][k3] = v3
			   end --end for k3,v3


		   end --end for k2,v2

		end --end for k,v

		theater_times_per_movie = nil

  end  --end if movie times per theatre


  if movie_tickets_per_movie_and_theater then
     print( "Fillstore: Updating movie tickets per movie and theater table from datapackage")
     local onetime = true
     -- movie_tickets table has day_id - theatre_id - movie_id. 
     -- Need to flip it so that it has movie_id -  theater-id - timestamp
     for day_id, vtable in pairs(movie_tickets_per_movie_and_theater) do
	for movie_id, theatertable in pairs(vtable) do
		    onetime = true
	            if not datastore.movies.movie_tickets_per_movie_and_theatre[movie_id] then
			datastore.movies.movie_tickets_per_movie_and_theatre[movie_id] = {}
		    end

		    for theater_id, timestable in pairs(theatertable) do
		            if not datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id] then
				datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id] = {}
			    end
			
	
			    -- get details only the first time for each movie	
			    if onetime then
			    	datastore.movies.movie_tickets_per_movie_and_theatre[movie_id].details = timestable.details
				onetime = false
			    end

			    -- we don't want these details to go into the day_id entry, so remove it
			    timestable.details = nil
			    stimes = getSortedShowtimes(timestable.sorted_times)

			    datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id][day_id] = {}
			    for i, stime in ipairs(stimes) do
			            datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id][day_id][i] = {}
			            datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id][day_id][i][tostring(stime)] = 
				    											timestable[tostring(stime)]
			    end

		            --datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theater_id][day_id] = timestable		
		   end
	
	end

     end

     
     movie_tickets_per_movie_and_theater = nil

 end -- if movie_times_per_movie_and_theater

end -- fillmovies()


------------------------------------------------------------------------------
--                      Function fillnews()                                 --
--    Fills the images table from the data package into the datastore       --
------------------------------------------------------------------------------
function fillnews()
  
  
  if categories then
  
	  print( "Fillstore: Updating news categories table from datapackage")
	   for k,v in pairs(categories) do

		     if datastore.news.categories[k] == nil then
		        datastore.news.categories[k] = {}
		     end


		     datastore.news.categories[k].label = categories[k].label
		     datastore.news.categories[k].image = categories[k].image
		     datastore.news.categories[k].description = categories[k].description
			 datastore.news.categories[k].default = categories[k].default

			 if categories[k].default == true then
				   print("Default category is " .. k .. " :updating in DS")
				   datastore.news.defaultCategory = k
			 end

       end --end for k,v
 
  categories = nil
  end -- if categories
  
  
  if news then
  
	  print( "Fillstore: Updating news headlines table from datapackage")
      if datastore.news.headlines == nil then
         datastore.news.headlines = {}
      end
      
  -- fill the news table from here
  
      ctable = datastore.news.headlines
      
	  for k,v in pairs(news) do
	  
	      if ctable[k] == nil then
	        ctable[k] = {}	     
	      end
	      
		  ctable[k].timestamp = news[k].timestamp
		  ctable[k].label = news[k].label
		  ctable[k].story = news[k].story -- if story doesn't exist, this will still work
		  
		  --special handling for images and categories
		  
		  --[[ 
		  
		    first add categories to the news.headlines table
		    This is because each news item should know what categories it belongs to
		  
		  --]]
		  
		  ctable[k].categories =  news[k].categories
		  
		  
		  
		  
		  --[[
		  
		     At the same time, each category should also know which news items belong to it
		  
		  --]]
		  --
		  --[[
		  
		  if datastore.news.categories == nil then
		  	datastore.news.categories = {}
		  end
		  
		  
		  
		  for k1,v1 in pairs(news[k].categories) do
		   
			   if datastore.news.categories[k1] == nil then
			      datastore.news.categories[k1] = {}
			   end
			   
			    
			   -- get next availble integer index in the categories[k1].news table
			   
			   if datastore.news.categories[k1].news == nil then
			      datastore.news.categories[k1].news = {}
			      index = 1		  
			   else	   
			      index = table.getn(datastore.news.categories[k1].news) + 1	    
			   end
			   
			   --add this news id (k) to the category (k1)
			   datastore.news.categories[k1].index = k
		  
		  
		  end -- for k1,v1
		  
		  --]]
		
		 --[[ 
		     Adding the images to the table
			   - Things that are unclear
			    -> Will images come down with this dpkg? Meaning that the images can refer to an fs;/ path or 
				   they will be a short name in the table. But what if the image doesn't exist yet? If the image
				   is coming down with the dpkg, there has to be assurance that the shortname/fs path it refers it
				   is already created in the images table, before it refers to it		 
				   
		Currently, 
	     --]]  	
		 
		 ctable[k].images = news[k].images 
		  	  
	end -- for k,v in pairs(news)
	  
  	news = nil
  
  
  
  end




end  -- fillnews


------------------------------------------------------------------------------
--                      Function fillweather()                              --
--    Fills the weather table from the data package into the datastore      --
------------------------------------------------------------------------------
function fillweather()

 local newAlert = false
 if weather_alerts then 
	  print( "Fillstore: Updating weather alerts table from datapackage")
	if isTableEmpty(weather_alerts) then
		datastore.weather.alerts = {}
	else
	 	for k,v in weather_alerts do
 	
 		    if datastore.weather.alerts[k] == nil then
 	       		datastore.weather.alerts[k] = {}
	 	    end

 		    datastore.weather.alerts[k].flag = true
	            datastore.weather.alerts[k].alertviewed = nil
 		    newAlert = true   	       
	 	    datastore.weather.alerts[k].timestamp = weather_alerts[k].timestamp
 		    datastore.weather.alerts[k].text = weather_alerts[k].text 			 
		end	 -- for k,v in weather_alerts
	end -- if weather_alerts
  end -- if weather_alerts


 
 
 if weather_locations then
	  print( "Fillstore: Updating weather locations table from datapackage")
 
    ctable = datastore.weather.locations
 	for k,v in weather_locations do
 	
 	    if ctable[k] == nil then 
 	       ctable[k] = {}
 	    end
 	
	 	ctable[k].timestamp = weather_locations[k].timestamp
	 	ctable[k].city = weather_locations[k].city
	 	ctable[k].state = weather_locations[k].state
	 	ctable[k].zipcode = weather_locations[k].zipcode
	 	ctable[k].current = weather_locations[k].current
	 	ctable[k].high = weather_locations[k].high
	 	ctable[k].low = weather_locations[k].low
	 	ctable[k].images = weather_locations[k].images
	 	ctable[k].alerts = weather_locations[k].alerts
		for i,alert in ctable[k].alerts do
			if datastore.weather.alerts[k] then
				datastore.weather.alerts[k].flag = true
                                datastore.weather.alerts[k].alertviewed = nil
			end
		end
		ctable[k].default = weather_locations[k].default
		if weather_locations[k].default == true then
		   datastore.weather.defaultLocation = k
		end
 	
 	end  -- for
	weather_locations = nil
 end  -- if weather_locations
 
	-- The purging of weather alerts is after the weather locations table has been parsed
	-- This is so that weather locations table has a chance to "save" its alerts from deletion	
	if weather_alerts then 
        -- Remove the viewed alerts 
	 	for k,v in datastore.weather.alerts do
		   if datastore.weather.alerts[k].alertviewed then
             		datastore.weather.alerts[k] = nil
	           end
		end
        	weather_alerts = nil
	end

if weather_summary then

	  print( "Fillstore: Updating weather summary table from datapackage")
   ctable = datastore.weather.summary
   
   for k,v in pairs(weather_summary) do
   
        --ensure that weather summary table for location id "k" exists
   
   	         ctable[k] = {}
 
   		
   		for k2,v2 in pairs(v) do
   		
   		--ensure that the weather summary table for timestamp "k2" exists
   		   if ctable[k][k2] == nil then
   		     	ctable[k][k2] = {}
   		   end
   		
   		   ctable[k][k2].summary = weather_summary[k][k2].summary
   		   ctable[k][k2].images = weather_summary[k][k2].images
   		   ctable[k][k2].high = weather_summary[k][k2].high
   		   ctable[k][k2].low = weather_summary[k][k2].low
   		   ctable[k][k2].radar = weather_summary[k][k2].radar
   		   ctable[k][k2].id = weather_summary[k][k2].id
 
        end -- for k2,v2 in pairs(v)
   

   end -- for k,v in pairs (weather_summary)

  weather_summary = nil

end  -- if weather_summary

-- details contains radar images and text for each day
if weather_details then

	print("Fillstore: Updating weather details table from datapackage");

	-- Get pointer to datastore
	ctable = datastore.weather.details

    --ensure that weather summary table exists
	if ctable == nil then
		ctable = {}
    end

   for k,v in pairs(weather_details) do
   
        --ensure that weather summary table for location id "k" exists
		if ctable[k] == nil then
		   ctable[k] = {}
        end
   		
   		for k2,v2 in pairs(v) do
   		
   		--ensure that the weather summary table for timestamp "k2" exists
   		   if ctable[k][k2] == nil then
   		     	ctable[k][k2] = {}
   		   end
   		
   		   ctable[k][k2].radar = weather_details[k][k2].radar
   		   ctable[k][k2].text = weather_details[k][k2].text
 
        end -- for k2,v2 in pairs(v)
   

   end -- for k,v in pairs (weather_details)

	weather_details = nil

end -- if weather_details

 return newAlert

end  -- fillweather


------------------------------------------------------------------------------
--                      Function fillsports()                               --
--    Fills the sports table from the data package into the datastore       --
------------------------------------------------------------------------------
function fillsports()


	if sports_types then

	  print( "Fillstore: Updating sports types table from datapackage")
		for k,v in pairs(sports_types) do

			if datastore.sports.types[k] == nil then
			    datastore.sports.types[k] = {}
			end

			datastore.sports.types[k].label = sports_types[k].label
			datastore.sports.types[k].image = sports_types[k].image
			datastore.sports.types[k].in_season = sports_types[k].in_season
		end --for k,v

	sports_types = nil
	end -- if sports_types
	
   if sports_teams then
   
	  print( "Fillstore: Updating sports teams table from datapackage")
		for k,v in pairs(sports_teams) do --iterate over the sports types


			if datastore.sports.teams[k] == nil then -- here k is the sports type
			    datastore.sports.teams[k] = {}
			end
			
			
			for k2,v2 in pairs(v) do -- now iterate over each team in this type
			
			    if datastore.sports.teams[k][k2] == nil then -- here k2 is the sports team id
			        datastore.sports.teams[k][k2] = {}
				end  -- if datastore.sports....
				
				datastore.sports.teams[k][k2].city = sports_teams[k][k2].city -- a.k.a v2.city
				datastore.sports.teams[k][k2].name = sports_teams[k][k2].name
				datastore.sports.teams[k][k2].image = sports_teams[k][k2].image
				
				
			end -- for k2,v2

		end -- for k,v
		sports_teams = nil
   end -- if sports_teams


   if sports_standings then
   
	  print( "Fillstore: Updating sports standings table from datapackage")
		for k,v in pairs(sports_standings) do -- iterate over the sports type
		
		    if datastore.sports.standings[k] == nil then
		        datastore.sports.standings[k] = {}
			end  -- end if
			
			
			for k2,v2 in pairs(v) do -- iterative over the division/poll
			
			    if datastore.sports.standings[k][k2] == nil then
			        datastore.sports.standings[k][k2] = {}
				end  -- end if
				

				datastore.sports.standings[k][k2].picker_label = sports_standings[k][k2].picker_label
				datastore.sports.standings[k][k2].standings_label = sports_standings[k][k2].standings_label
				datastore.sports.standings[k][k2].date = sports_standings[k][k2].date
				datastore.sports.standings[k][k2].details = sports_standings[k][k2].details
				
			end -- for k2,v2
			
		end -- for k,v
		sports_standings = nil
   end -- if sports_standings
   
   
   if sports_scores then
	      
	  print( "Fillstore: Updating sports scores table from datapackage")
        for k,v in pairs(sports_scores) do -- iterate over the sports type
        
            if datastore.sports.scores[k] == nil then
                datastore.sports.scores[k] = {}
			end -- end if
			
			for k2,v2 in pairs(v) do -- iterate over the date timestamps
			
			    if datastore.sports.scores[k][k2] == nil then
			        datastore.sports.scores[k][k2] = {}
				end -- end if
				
				for k3,v3 in pairs(v2) do -- iterate over the game ids
				
				    if datastore.sports.scores[k][k2][k3] == nil then
				        datastore.sports.scores[k][k2][k3] = {}
				    end -- end if

				    --now if this 
					
				    -- datastore.sports.scores[sports_type][date][gameID] = scores_string
				    datastore.sports.scores[k][k2][k3] = v3;
					
				end -- for k3,v3
					
				
			end -- for k2,v2
			
		end -- for k,v
		sports_scores = nil
	end -- if sports_scores
	
	if sports_schedules then
	
	  print( "Fillstore: Updating sports schedules table from datapackage")
	    for k,v in pairs(sports_schedules) do -- iterate over team IDs
	    
	        if datastore.sports.schedules[k] == nil then
	            datastore.sports.schedules[k] = {}
			end -- end if
			
			
			for k2,v2 in pairs(v) do -- iterate over timestamps
			
			    if datastore.sports.schedules[k][k2] == nil then
			        datastore.sports.schedules[k][k2] = {}
			    end -- end if				
				
				for k3,v3 in pairs(v2) do -- iterate over game IDs
				-- datastore.sports.schedules[team_id][timestamp][game_id] = game_details_string
					datastore.sports.schedules[k][k2][k3] = v3
				end -- for k3,v3
				
			end -- for k2,v2
	   end -- for k,v
	   sports_schedules = nil
	end --if sports_schedules
	
	
   if sports_games then
   
	  print( "Fillstore: Updating sports games table from datapackage")
		for k,v in pairs(sports_games) do -- iterate over game IDs
		
		    if datastore.sports.games[k] == nil then
		        datastore.sports.games[k] = {}
			end -- end if
			
			datastore.sports.games[k].label = sports_games[k].label
			datastore.sports.games[k].summary = sports_games[k].summary
			datastore.sports.games[k].details = sports_games[k].details
			datastore.sports.games[k].date = sports_games[k].date
			datastore.sports.games[k].teams = sports_games[k].teams
			datastore.sports.games[k].score1 = sports_games[k].score1
			datastore.sports.games[k].score2 = sports_games[k].score2
			datastore.sports.games[k].status = sports_games[k].status
		end  -- for k,v
   		sports_games = nil
   end -- if sports_games
				
end --fillsports()

function fillOTA()
   if ota_updates then
      print("Filling the OTA table from datapackage")
      datastore.ota = {}
      datastore.ota.url = ota_updates.trig_update_url
      datastore.ota.newUrl = true
   end

   ota_updates = nil

end

------------------------------------------------------------------------------
--                      main()                                              --
--  The main chunk starts here (execution of script will start here)       --
------------------------------------------------------------------------------

-- possible that the datastore has fake data
if datastore.internal.IsFakeData == true then
	--clear all the fake data
	print("Fillstore: Data store has fake data.. clearing out before applying data package")
	datastore.clear()
	datastore.internal.IsFakeData = false
  
end
	
if datastore.internal.IsInit == false then
	print("Fillstore: Data store is not initialized.. re-initializing data store")
	datastore.init()
	datastore.internal.IsInit = true
	datastore.clear()
end

if not datastore.internal.IsBeingUpdated then 
	datastore.internal.IsBeingUpdated = true
	print("Fillstore: Locked data store, applying data package...")
	fillimages()
	fillmarketing()
	fillmoney()
	fillmovies()
	fillnews()
	local alertFlag = fillweather()
	fillsports()
	fillOTA()
	datastore.internal.IsBeingUpdated = false
	print("Fillstore: Applied data package, unlocked data store, notifying interface...")
	if datastore.interfaceCB then
		showtime = datastore.get_showtime()
		if showtime ~= nil and showtime.time ~= nil then
			datastore.set_last_update_time(showtime.time)
		else
			datastore.set_last_update_time(net.getutctime())
		end
		datastore.interfaceCB(0,alertFlag) --notify interface that update is over
	end	
	--datastore.dumpStore()
else
	print("Fillstore:: Datastore locked! Ignoring data package")
end -- datastore.internal.IsBeingUpdated


      -- Restore the "print" function if it has been disabled - so that this change does not affect other scripts
       if fsRemoveDebugMessages then
	  print = printfn
       end


--
--end main()



