require("rsmdict")

--The Objects that is supported by the Script
local obj_ids = {
                   RSM.RSM_TagID.TAG_CCD_CFG,
                   RSM.RSM_TagID.TAG_CCD_OVERRIDE,
                   RSM.RSM_TagID.TAG_CCD_FAN,
                   RSM.RSM_TagID.TAG_CCD_AC,
                   RSM.RSM_TagID.TAG_CCD_RESTART                    
                }
      
local profiles = {}  
local overrides = {}
local fans = {}
local fanoutputs = {}
local aircons = {}

local newFanType = 0;

           
local profilePath = "/etc/rsm/ccd/profiles/"
local profileFiles = {}

local ccd_Restartcmd = "sv restart ccd"

function print_table(t,p)

   for k,v in pairs(t) do
     print(p,k,v)
     if(type(v)=="table") then 
         print_table(v,p.."\t")
     end
  end
end


--Retuen the Object List
function getObjects()
 return obj_ids;
end

--Convert the config file into an object message nd return that.
--Actually supposed to check the request object to find the exact object if any to 
--return. We jippo that by always returning all of them
function getConfig(cfg)
  load_profiles()
  msg = profiles_to_msg()
  --print_table(msg,0)
  return msg
end


--Function to lookup and set a specific object(s)
--and then to update the cofig file with those values
function setConfig(cfg)
   load_profiles()   
   update_profiles(cfg)
   store_profiles()
end

function deleteConfig(cfg)
   load_profiles()
   delete_profiles(cfg)
end

function replaceConfig(cfg)
   
end


function command_exec(cmd)
  local f = io.popen(cmd) 
  value = f:read("*a") or "none"
  f:close()
  return value
end

function scandir(directory)
  local i, t, popen = 0, {}, io.popen
    for filename in popen('ls -a "'..directory..'"'):lines() do
        i = i + 1
        t[i] = filename
    end
    return t
end

function writefile(fileaddres,value)
  local f = io.open(fileaddres,"w+")
  f:write(value)
  f:close()
  return true
end

function roundToNthDecimal(num, n)
  local mult = 10^(n or 0)
  return math.floor(num * mult + 0.5) / mult
end

function load_profiles() 
  --print("Loading pf data...")   
  --sf = command_exec("cat "..serial_conf_file)  
  serial_file = sf  
  profiles = {} 
  profileFiles = {}  
  overrides = {}
  fans = {}
  fanoutputs = {}
  aircons = {}
            
  
  --scan profiles directory for any ccd profile files
  profileFiles = scandir(profilePath) 
  table.remove(profileFiles,1)
  table.remove(profileFiles,1)  
  
  --print("Table of filenames: ") 
  --print_table(profileFiles,0) 
  
  
  
  --Populate the profiles array
  if(profileFiles ~= 0) then
  
      --[[priority_overrides = 1
      priority_fans = 1
      count_fanoutputs = 1
      priority_ac = 1]]--
      
      for k,filename in pairs(profileFiles) do
          --print("Filename: "..filename)
          xml = command_exec("cat "..profilePath .. "/" .. filename)      
          name, tmp = xml:match("<profile%s+name=\"(.-)\">%s*(.-)%s*</profile>")    
          
          priority_overrides = 1
          priority_fans = 1
          count_fanoutputs = 1
          priority_ac = 1
          
          
          --Profile Information
          if name ~= nil and tmp ~= nil then
             profiles[filename] = {}
             profiles[filename].overrides = {}  
             profiles[filename].aircons = {}  
             profiles[filename].fans = {}  
             
             profiles[filename].filename = filename
             profiles[filename].label = name or "unknown"
             profiles[filename].tempideal = xml:match("<ideal>%s-(.-)%s-</ideal>") or "20.0" 
             profiles[filename].temprange = xml:match("<range>%s-(.-)%s-</range>") or "2.0"
             profiles[filename].internal = xml:match("<internal>%s-<analog>%s-(.-)%s-</analog>%s-</internal>")
             profiles[filename].external = xml:match("<external>%s-<analog>%s-(.-)%s-</analog>%s-</external>")
             profiles[filename].acmonitor = xml:match("<ACmonitor>%s-<input>%s-(.-)%s-</input>%s-</ACmonitor>")               
             
             profiles[filename].deltatemp = xml:match("<delta>%s-(.-)%s-</delta>")
             profiles[filename].deltatempmin = xml:match("<minimum>%s-(.-)%s-</minimum>")
             if(profiles[filename].deltatemp ~= nil) and (profiles[filename].deltatempmin ~= nil)then
                profiles[filename].deltaenable = 1                
             else
                profiles[filename].deltaenable = 0
             end
             
             --add overrides
             ovr = xml:match("<overrides>%s-(.-)%s-</overrides>") or ""                          
             --priority_overrides = 0
             if ovr ~= nil then
                 for o in ovr:gmatch("<input>%s-(.-)%s-</input>") do
                    --print("Override input: "..o)
                    --[[overrides[priority_overrides] = {}
                    overrides[priority_overrides].filename = filename 
                    overrides[priority_overrides].label = o 
                    overrides[priority_overrides].count = priority_overrides ]]--    
                    
                    --trying nested arrays
                    profiles[filename].overrides[priority_overrides] = {}
                    profiles[filename].overrides[priority_overrides].priority = priority_overrides
                    profiles[filename].overrides[priority_overrides].filename = filename
                    profiles[filename].overrides[priority_overrides].label = o
                    --*************       
                                                   
                    priority_overrides = priority_overrides + 1
                    
                    
                    
                 end
             end
             
             --add fans
             
             highestOutputCount = 0    
             for fan in xml:gmatch("<fan>%s-(.-)%s-</fan>") do
                --fans[priority_fans] = {}
                --fans[priority_fans].filename = filename
                --fans[priority_fans].count = priority_fans
                
                
                --priority_fans = priority_fans + 1
                --trying nested arrays
                profiles[filename].fans[priority_fans] = {} 
                profiles[filename].fans[priority_fans].fanoutputs = {}      
                profiles[filename].fans[priority_fans].priority  =  priority_fans 
                count_fanoutputs = 0          
                --print("Identified new fan: "..profiles[filename].fans[priority_fans].priority)
                --*************       
                      
                for out in fan:gmatch("<output>%s-(.-)%s-</output>") do
                    --[[fans[count_fanoutputs] = {}          
                    fanoutputs[count_fanoutputs] = {}
                    fanoutputs[count_fanoutputs].filename = filename
                    fanoutputs[count_fanoutputs].fan = priority_fans
                    fanoutputs[count_fanoutputs].label = out  
                    fans[count_fanoutputs].filename = filename
                    fans[count_fanoutputs].fan = priority_fans
                    fans[count_fanoutputs].label = out]]--
                    
                    
                    --trying nested arrays
                    profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs] = {} 
                    profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs].fan = priority_fans   
                    profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs].filename = filename    
                    profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs].label = out      
                    --print("Fan output: "..profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs].label)         
                    --*************     
                    --print("Reading fan output: "..profiles[filename].fans[priority_fans].fanoutputs[count_fanoutputs].label)
                    
                    count_fanoutputs = count_fanoutputs + 1
                    
                    if count_fanoutputs > highestOutputCount then
                        highestOutputCount = count_fanoutputs
                    end
                end
                
                if highestOutputCount>1 then
                    profiles[filename].fantype = 1
                elseif highestOutputCount == 1 then
                    profiles[filename].fantype = 0
                else
                    profiles[filename].fantype = newFanType
                end
                
              priority_fans = priority_fans + 1   
             end
             
             --profiles[filename].fancount = 0 
             profiles[filename].fancount = priority_fans 
             
             --add aircons
             --aircons = {}
             --priority_ac = 0
             for power,failure,probe in xml:gmatch("<aircon>.-<power>%s-(.-)%s-</power>.-<failure>%s-(.-)%s-</failure>.-<probe>%s-(.-)%s-</probe>.-</aircon>") do
                --aircons[priority_ac] = {}
                --aircons[priority_ac].filename = filename
                --aircons[priority_ac].label = a
                --aircons[priority_ac].ac = priority_ac
                
                --trying nested arrays
                profiles[filename].aircons[priority_ac] = {}
                profiles[filename].aircons[priority_ac].priority = priority_ac
                profiles[filename].aircons[priority_ac].filename = filename
                profiles[filename].aircons[priority_ac].label = power
                profiles[filename].aircons[priority_ac].failure = failure
                profiles[filename].aircons[priority_ac].probe = probe 
                --*************       
                
                priority_ac = priority_ac + 1
             end
                 
          end        
          
                    
      end     
      
  end
  
   
              
end --function

function profiles_to_msg()
  local msg = {}
  profile_ctr = 0
  
  --print("***Message: ")
  
  --Load profile information into a message
  for idx,pf in pairs(profiles) do  
        
     profile_cfg = {}
     --print{"Testing filename value: "..pf.filename}
     profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_CFG
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = pf.filename
     profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = pf.label
     profile_cfg[RSM.RSM_TagID.TAG_CCD_TEMP] = tonumber(pf.tempideal)
     profile_cfg[RSM.RSM_TagID.TAG_CCD_RANGE] = tonumber(pf.temprange)
     profile_cfg[RSM.RSM_TagID.TAG_CCD_INTERNAL] = pf.internal
     profile_cfg[RSM.RSM_TagID.TAG_CCD_EXTERNAL] = pf.external
     profile_cfg[RSM.RSM_TagID.TAG_CCD_ACMONITOR] = pf.acmonitor
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] = tonumber(pf.fantype)
     
     if(pf.deltaenable == 1) then
        profile_cfg[RSM.RSM_TagID.TAG_CCD_DELTA] = pf.deltaenable
        profile_cfg[RSM.RSM_TagID.TAG_CCD_DELTA_TEMP] = tonumber(pf.deltatemp)
        profile_cfg[RSM.RSM_TagID.TAG_CCD_DELTA_MIN  ] = tonumber(pf.deltatempmin)
     end                              
     
     --print("Filename sent: "..profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME]) 
        
     msg[profile_ctr] = profile_cfg
     profile_ctr = profile_ctr+1
     
     --testing nested arrays - Overrides
     --for p,pff in pairs(profiles) do   
           --print("Overrides for profile: "..pf.filename) 
         for ov,off in pairs(profiles[pf.filename].overrides) do 
             profile_cfg = {}
             profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_OVERRIDE
             profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = off.filename
             profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = off.label
             profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = tonumber(off.priority)   
             
             --print("Adding override to message: "..profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL]) 
                          
             msg[profile_ctr] = profile_cfg
             profile_ctr = profile_ctr+1
         end
     --end 
     --*************************
     
     --testing nested arrays - Aircons
     --for p,pff in pairs(profiles) do 
         for ac,acff in pairs(profiles[pf.filename].aircons) do 
             profile_cfg = {}
             profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_AC
             profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = acff.filename
             profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = acff.label
             profile_cfg[RSM.RSM_TagID.TAG_CCD_INTERNAL] = acff.failure
             profile_cfg[RSM.RSM_TagID.TAG_CCD_EXTERNAL] = acff.probe
             profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = tonumber(acff.priority)   
                          
             msg[profile_ctr] = profile_cfg
             profile_ctr = profile_ctr+1
         end
     --end 
     --*************************
     
     
     --testing nested arrays - Fans     
     --for p,pff in pairs(profiles) do 
     countfan = 1
     --print("Profile fan count = "..profiles[pff.filename].fancount)
     
         for f,fan in pairs(profiles[pf.filename].fans) do 
            --print("Current fan = "..fan.priority)
            --while fan.priority <= profiles[pff.filename].fancount do
            for o,out in pairs(profiles[pf.filename].fans[fan.priority].fanoutputs) do
                
                 profile_cfg = {}
                 profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_FAN
                 profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = out.filename
                 profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = out.label
                 profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = tonumber(out.fan)   
                 
                 --print("Adding output to message: "..out.label)        
                 msg[profile_ctr] = profile_cfg
                 profile_ctr = profile_ctr+1
            end                 
            --end  
         countfan = countfan + 1            
         end
     --end 
     --*************************
  end
  
  --Load overrides information into a message
  --[[for idx,off in pairs(overrides) do     
     profile_cfg = {}
     profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_OVERRIDE
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = off.filename
     profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = off.label
     profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = tonumber(off.count)   
                  
     msg[profile_ctr] = profile_cfg
     profile_ctr = profile_ctr+1
  end]]--
  
  --Load fan information into a message
  --[[for idx,ff in pairs(fans) do     
     profile_cfg = {}
     profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_FAN
     --profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = ff.filename
     --profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = ff.count    
     --profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = ff.label
     
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = ff.filename
     profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = tonumber(ff.fan)    
     profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = ff.label     
                  
     msg[profile_ctr] = profile_cfg
     profile_ctr = profile_ctr+1
  end ]]--
  
  --Load fan outputs information into a message
  --[[for idx,fof in pairs(fanoutputs) do     
     profile_cfg = {}
     profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_FAN_OUTPUTS
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = fof.filename
     profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = fof.label
     profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = fof.fan    
         
                  
     msg[profile_ctr] = profile_cfg
     profile_ctr = profile_ctr+1
  end ]]--
  
  --Load ac information into a message
  --[[for idx,af in pairs(aircons) do     
     profile_cfg = {}
     profile_cfg.objid =  RSM.RSM_TagID.TAG_CCD_AC
     profile_cfg[RSM.RSM_TagID.TAG_CCD_FILENAME] = af.filename
     profile_cfg[RSM.RSM_TagID.TAG_CCD_LABEL] = af.label
     profile_cfg[RSM.RSM_TagID.TAG_CCD_PRIORITY] = af.ac     
                  
     msg[profile_ctr] = profile_cfg
     profile_ctr = profile_ctr+1
  end]]--
  
     
  
  return msg
end

function update_profiles(cfg)
    count_overrides = 0
    count_fans = 0
    count_fans_outputs = 0
    count_aircons = 0
    
    --overrides = {}
    
    --fanoutputs = {}
    --aircons = {}
    
   for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_CFG then   --Config Tag                 
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' then
              --print("Incoming Profile filename: "..obj[RSM.RSM_TagID.TAG_CCD_FILENAME])        
              --obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] = obj[RSM.RSM_TagID.TAG_BUS_SERIALNUM] .. ".xml"  
              
              sf = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]]              
              if sf then
                  --sf.fancount = 0
                  setCCD(sf,obj)
              end                           
          else--New ccd profile
              --print("Recognised new profile...")              
              newFile = obj[RSM.RSM_TagID.TAG_CCD_LABEL]..".xml"               
              --print("Incomming profile: "..newFile)       
              profiles[newFile] = {}
              sf = profiles[newFile]              
              if sf then
                sf.filename = newFile  
                sf.fancount = 0                       
                setCCD(sf,obj)
              end                            
                            
          end -- if filename       
          
      end -- if cfg
      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_OVERRIDE then  --Override tag                  
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' or obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= nil then
              --print("(Override) Incoming Profile filename: "..obj[RSM.RSM_TagID.TAG_CCD_FILENAME])
              if count_overrides == 0 then
                  --[[for idx, f in pairs(overrides) do
                      if f.filename == obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
                          overrides[idx] = {}                            
                      end
                  end]]--
                  profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].overrides = {}
              end        
              --[[overrides[count_overrides]={}              
              of = overrides[count_overrides]              
              if of then
                  setoverrides(of,obj)
              end--]]
              
              --Testing nested arrays
              --profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].overrides = {}
              profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].overrides[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] = {}
              of = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].overrides[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]]
              if of then
                  of.priority = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
                  setoverrides(of,obj)
              end
              --*******************                           
          else--New ccd profile
              --print("Error: No file name provided..")                    
          end -- if filename       
          count_overrides = count_overrides + 1
      end -- if override 
      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_FAN then  --Fan tag                  
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' or obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '\0' then
          
          
              --print("(Fan) Incoming Profile filename: "..obj[RSM.RSM_TagID.TAG_CCD_FILENAME]) 
              --print("Fans type: "..profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fantype) 
              --print("Fan number: "..obj[RSM.RSM_TagID.TAG_CCD_PRIORITY])              
              --if count_fans == 0 then
                  --print("Init Fans...")
                  --for idx, f in pairs(fans) do
                  --    if f.filename == obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
                  --        fans[idx] = nil                      
                  --        profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount = 0
                  --    end                  
                  --end                  
                  --profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount = 0
                  --profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans = {}
             -- end
             -- if count_fans_outputs == 0 then    
              --    print("Init Fans outputs...")   
             --     profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] = {}                        
             --     profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs = {}
             -- end
              
              --[[if RSM.RSM_TagID.TAG_CCD_PRIORITY ~= nil then                  
                  fans[count_fans_outputs]={}
                  ff = fans[count_fans_outputs]                               
                  if ff then
                      setfans(ff,obj)
                  end  
              end]]-- 
              
--                  profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[count_fans_outputs] = {}
--                  ff = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[count_fans_outputs]
--                  if ff then
--                      ff.fan = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
--                      setfans(ff,obj)
--                  end   
                  if count_fans == 0 then                  
                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount = 0
                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans = {}
                  end        
                  
--                  if profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fantype == 0 then --SINGLE SPEED
--                      maxOutputs = 1         
--                      --profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans = {}
--                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] = {}
--                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs = {}
--                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[count_fans_outputs] = {}
--                      ff = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[count_fans_outputs]
--                      
--                  elseif profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fantype == 1 then --VARIABLE SPEED            
--                      maxOutputs = 4
                      if profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] == nil then
                          profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] = {}
                          profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].priority = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
                      end
                      if profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs == nil then
                          profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs = {}
                      end
                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].priority = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
                      profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[obj[RSM.RSM_TagID.TAG_CCD_LABEL]] = {}
                      ff = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fanoutputs[obj[RSM.RSM_TagID.TAG_CCD_LABEL]]
                  --end          
                  
                  if ff then
                      ff.fan = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
                      setfans(ff,obj)
                  end 
                                      
          else--New ccd fan
              print("Error: No file name provided..")                    
          end -- if filename       
          count_fans_outputs = count_fans_outputs + 1
          
          
          
      end -- if fan  
      
      
      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_AC then  --AC tag                 
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' or obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= nil then
              --print("(AC) Incoming Profile filename: "..obj[RSM.RSM_TagID.TAG_CCD_FILENAME])
              if count_aircons == 0 then
                  --[[for idx, f in pairs(aircons) do
                      if f.filename == obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
                          aircons[idx] = nil                   
                      end
                  end]]--
                  profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].aircons = {}
              end
              --[[if RSM.RSM_TagID.TAG_CCD_PRIORITY ~= nil then
                  aircons[count_aircons]={}
                  ff = aircons[count_aircons]                               
                  if ff then
                      setAC(ff,obj)
                  end   
              end]]--         
              --Testing nested arrays
              --if obj[RSM.RSM_TagID.TAG_CCD_Priority] ~= nil then                  
                  profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].aircons[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]] = {}
                  af = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].aircons[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]]
                  if af then
                      af.priority = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
                      setAC(af,obj)
                  end
              --end
              --*******************                         
          else--New ccd profile
              --print("Error: No file name provided..")                    
          end -- if filename       
          count_aircons = count_aircons + 1
      end -- if aircons      
      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_RESTART then   --CCD Restart Tag                 
          command_exec(ccd_Restartcmd)   
          --print("Restarting CCD...")  
      end
       
   end -- for
end --function


function setCCD(sf,obj)
    
    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_TEMP] then
       sf.tempideal = obj[RSM.RSM_TagID.TAG_CCD_TEMP]
    end  
    
    if obj[RSM.RSM_TagID.TAG_CCD_RANGE] then
       if obj[RSM.RSM_TagID.TAG_CCD_RANGE] == RSM.TAG_CCD_RANGE_Types.TAG_CCD_RANGE_ONE then  
          sf.temprange = 1
       end 
       if obj[RSM.RSM_TagID.TAG_CCD_RANGE] == RSM.TAG_CCD_RANGE_Types.TAG_CCD_RANGE_TWO then  
          sf.temprange = 2
       end 
       if obj[RSM.RSM_TagID.TAG_CCD_RANGE] == RSM.TAG_CCD_RANGE_Types.TAG_CCD_RANGE_THREE then  
          sf.temprange = 3
       end  
       if obj[RSM.RSM_TagID.TAG_CCD_RANGE] == RSM.TAG_CCD_RANGE_Types.TAG_CCD_RANGE_FOUR then  
          sf.temprange = 4
       end    
       if obj[RSM.RSM_TagID.TAG_CCD_RANGE] == RSM.TAG_CCD_RANGE_Types.TAG_CCD_RANGE_FIVE then  
          sf.temprange = 5
       end  
    end   
    
    if obj[RSM.RSM_TagID.TAG_CCD_INTERNAL] then
       sf.internal = obj[RSM.RSM_TagID.TAG_CCD_INTERNAL]
    end  
    
    if obj[RSM.RSM_TagID.TAG_CCD_EXTERNAL] then
       sf.external = obj[RSM.RSM_TagID.TAG_CCD_EXTERNAL]
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_ACMONITOR] then
       sf.acmonitor = obj[RSM.RSM_TagID.TAG_CCD_ACMONITOR]
    end       
    
    if obj[RSM.RSM_TagID.TAG_CCD_DELTA] then
       if obj[RSM.RSM_TagID.TAG_CCD_DELTA] == RSM.TAG_CCD_DELTA_Types.TAG_CCD_DELTA_DISABLE then  
          sf.deltaenable = 0
       end 
       if obj[RSM.RSM_TagID.TAG_CCD_DELTA] == RSM.TAG_CCD_DELTA_Types.TAG_CCD_DELTA_ENABLE then  
          sf.deltaenable = 1
       end            
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_DELTA_TEMP] then
       sf.deltatemp = obj[RSM.RSM_TagID.TAG_CCD_DELTA_TEMP]       
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_DELTA_MIN] then
       --sf.deltatempmin = obj[RSM.RSM_TagID.TAG_CCD_DELTA_MIN]
       sf.deltatempmin = roundToNthDecimal(obj[RSM.RSM_TagID.TAG_CCD_DELTA_MIN],2)
       --print("Rounded Delta Min: "..roundToNthDecimal(sf.deltatempmin,2)) 
    end
    
--    if obj[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] then
--       if obj[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] == RSM.TAG_CCD_FAN_TYPE_Types.TAG_CCD_FAN_TYPE_SINGLE then  
--          sf.fantype = 0
--       end 
--       if obj[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] == RSM.TAG_CCD_FAN_TYPE_Types.TAG_CCD_FAN_TYPE_VARIABLE then  
--          sf.fantype = 1
--       end 
--       --newFanType = sf.fantype
--       --sf.fantypechanged = 1           
--    end   
    --print("Setting fan type: "..sf.fantype)
     
    sf.changed = 1
    
end

function setoverrides(sf,obj)

    
    
    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
    end 
    
    if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
       sf.filename = obj[RSM.RSM_TagID.TAG_CCD_FILENAME]
    end     
    
    --print("Setting override: "..sf.label.." Override priority: "..sf.priority)
    sf.changed = 1
    profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].changed = 1
end

function setfans(sf,obj)    

--    local newfan = true
--    --print("New fan number: "..obj[RSM.RSM_TagID.TAG_CCD_PRIORITY])
--    
--    for idx, fan in pairs(fans) do    
--        if fan.filename == obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
--            --print("in filename loop...")
--            if fan.fan ~= nil then
--                --print("Array fan number : "..fan.fan)
--                --print("Array fan label: "..fan.label)
--                if obj[RSM.RSM_TagID.TAG_CCD_PRIORITY] == fan.fan then
--                    --print("false...")
--                    newfan = false                
--                end            
--            end
--        --[[elseif fan.filename == nil then            
--            print("true...")
--            newfan = true]]--
--        end
--        
--    
--    end
--    
--    --print("add count?..."..tostring(newfan))
--    if newfan == true then
--        count_fans = count_fans + 1
--        profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount + 1
--        --print("Fan count.."..profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount)
--    end
--        
--    if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
--       sf.filename = obj[RSM.RSM_TagID.TAG_CCD_FILENAME]
--    end  
--    if obj[RSM.RSM_TagID.TAG_CCD_PRIORITY] then
--       sf.fan = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
--    end 
--    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
--       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
--    end   
    
    --Testing Nested Arrays
    local newfan = true
    
    --print("New fan number: "..obj[RSM.RSM_TagID.TAG_CCD_PRIORITY])    
    for idx, fann in pairs(profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fans) do    
        if fann.filename == obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
            --print("in filename loop...")
            if fann.fanoutputs[obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]].fan ~= nil then --new fan
                --print("Array fan number : "..fan.fan)
                --print("Array fan label: "..fan.label)
                if obj[RSM.RSM_TagID.TAG_CCD_PRIORITY] == fann.fan then --existing fan
                    --print("false...")
                    newfan = false                
                end            
            end
        --[[elseif fan.filename == nil then            
            print("true...")
            newfan = true]]--
        end       
    end    
    if newfan == true then
        count_fans = count_fans + 1
        count_fans_outputs = 0
        profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount + 1
        --print("Fan count.."..profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].fancount)
    end
    
    if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
       sf.filename = obj[RSM.RSM_TagID.TAG_CCD_FILENAME]
    end  
    if obj[RSM.RSM_TagID.TAG_CCD_PRIORITY] then
       sf.fan = obj[RSM.RSM_TagID.TAG_CCD_PRIORITY]
    end 
    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
    end  
    
    --print("Setting Fan Output: "..sf.label.." Fan number: "..sf.fan)
    --*******************************
    
    sf.fantypechanged = 0
    sf.changed = 1
    profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].changed = 1
    --print("Fan count: "..count_fans)
end

function setAC(sf,obj)    
        
    if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] then
       sf.filename = obj[RSM.RSM_TagID.TAG_CCD_FILENAME]
    end  
    
    if obj[RSM.RSM_TagID.TAG_CCD_LABEL] then
       sf.label = obj[RSM.RSM_TagID.TAG_CCD_LABEL]
    end   
    
    --print("Setting AC: "..sf.label.." AC priority: "..sf.priority)
    sf.changed = 1
    profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]].changed = 1
end

function store_profiles()



  for idx,pf in pairs(profiles) do
      
          local fan_number = 0
         if pf.changed and pf.changed == 1 then
            --print("Storing: "..pf.filename)
         
            newXML = [[
 <?xml version="1.0"?>
 <profile name="]]..pf.label..[[">
     <settings>
         <temperature>
             <ideal>]]..pf.tempideal..[[</ideal>
             <range>]]..pf.temprange..[[</range>
         </temperature>
 ]]
              if pf.deltaenable == 1 then
              newXML = newXML .. [[
         <deltacooling>
             <delta>]]..pf.deltatemp..[[</delta>
             <minimum>]]..pf.deltatempmin..[[</minimum>
         </deltacooling>
 ]]
              end
          
              newXML = newXML .. [[
     </settings>
     <inputs>
         <probes>
             <internal>
                 <analog>]]..pf.internal..[[</analog>
             </internal>
 ]]

              if pf.external ~= nil then
              newXML = newXML .. [[
             <external>
                 <analog>]]..pf.external..[[</analog>
             </external>
 ]]
              end
          
              newXML = newXML .. [[
         </probes>
 ]]
 --Overrides          
              newXML = newXML .. [[
         <overrides>
 ]]              
              --Testing nested arrays
              if profiles[pf.filename].overrides then
                  for ov,off in pairs(profiles[pf.filename].overrides) do
                      --print("Storing Override: "..off.label) 
                      newXML = newXML .. [[
             <input>]]..off.label..[[</input>
 ]]
                  end              
              --**********************************
                      newXML = newXML .. [[
         </overrides>
 ]]
              end
              
             
--AC monitor                     
              if pf.acmonitor ~= "" then
              newXML = newXML .. [[
         <ACmonitor>
             <input>]]..pf.acmonitor..[[</input>
         </ACmonitor>
 ]]
              end    
 
              newXML = newXML .. [[
     </inputs>
     <outputs>
 ]]
    
 --Fans
        --if pf.fantypechanged and pf.fantypechanged == 0 then  
            --Testing nested arrays
            if profiles[pf.filename].fans then
                for f, ff in pairs(profiles[pf.filename].fans) do
                    --print("Fan: "..ff.priority)
                    newXML = newXML .. [[
             <fan>
     ]]         
                    for of,off in pairs(ff.fanoutputs) do 
                        --print("Output fan number: "..off.fan)
                        --print("Output fan label: "..off.label)
                        newXML = newXML .. [[
                 <output>]]..off.label..[[</output>
     ]]
                    end  
                newXML = newXML .. [[
             </fan>
     ]]           
                end
            end
            
          --**********************************      
        --end  --end fantype changed    
         
              
  --AC      
          --Testing nested arrays
          if profiles[pf.filename].aircons then
              for ac,acff in pairs(profiles[pf.filename].aircons) do 
              --print("Storing AC: "..acff.label)
                  newXML = newXML .. [[
         <aircon>
             <power>]]..acff.label..[[</power>
             <failure>]]..acff.failure..[[</failure>
             <probe>]]..acff.probe..[[</probe>
         </aircon>
 ]]
              end        
          end
                    
          --**********************************
         
            newXML = newXML .. [[
     </outputs>
 </profile>
 
 ]]         
 
              
            writefile(profilePath .. "/" .. pf.filename, newXML)
            --writefile("/usr/share/lua/kses/" .. pf.filename, newXML)
            
          end      
    end 

end

function delete_profiles(cfg)
    
   for idx,obj in pairs(cfg) do      
      if obj.objid and obj.objid == RSM.RSM_TagID.TAG_CCD_CFG then   --Config Tag                 
          if obj[RSM.RSM_TagID.TAG_CCD_FILENAME] ~= '' then
              
              sf = profiles[obj[RSM.RSM_TagID.TAG_CCD_FILENAME]]              
              if sf then                  
                  delCCD(sf,obj)
              end                           
          else                    
              --print("Error: No serial nmber provided to delete!")               
          end -- if filename       
          
      end -- if cfg
   end
end

function delCCD(sf,obj)

    command_exec("rm "..profilePath .. "/" .. sf.filename, newXML)
    --command_exec("rm /usr/share/lua/kses/" .. sf.filename, newXML)
end

--Testing....

--print("Testing...")

--load_profiles()
--[[print("Profiles Table: ")
print_table(profiles,0)
print("Overrides Table: ")
print_table(overrides,0)
print("Fans Table: ")
print_table(fans,0)
print("Fanoutputs Table: ")
print_table(fanoutputs,0)
print("Aircons Table: ")
print_table(aircons,0)]]--
--print("Get Config...............")
--print_table(getConfig(),0)

local testCfg = {}
local obj ={}
local obj1 ={}
local obj2 ={}
local obj3 ={}
local obj4 ={}
local obj5 ={}
local obj6 ={}

local obj7 ={}
local obj8 ={}
local obj9 ={}
local obj10 ={}
local obj11 ={}
local obj12 ={}

local obj13 ={}

obj.objid = RSM.RSM_TagID.TAG_CCD_CFG
obj[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
--obj[RSM.RSM_TagID.TAG_BUS_DEVICE] = "/dev/ttyS1"
obj[RSM.RSM_TagID.TAG_CCD_LABEL] = "Testccd_change"     
--obj[RSM.RSM_TagID.TAG_BUS_TEMPLATE] = "t2s.xml"
--obj[RSM.RSM_TagID.TAG_BUS_ADDR] = "1.2.3.55"
--obj[RSM.RSM_TagID.TAG_BUS_GATE_ADDR] = "1.2.3.44"
--obj[RSM.RSM_TagID.TAG_BUS_PORT] = 88
--obj[RSM.RSM_TagID.TAG_BUS_BAUD] = "115200"
--obj[RSM.RSM_TagID.TAG_BUS_PARITY] = 1
--obj[RSM.RSM_TagID.TAG_BUS_DATA] = 5
--obj[RSM.RSM_TagID.TAG_BUS_STOP] = "1.1"
--obj[RSM.RSM_TagID.TAG_BUS_MODE] = 1

obj1.objid = RSM.RSM_TagID.TAG_CCD_OVERRIDE
obj1[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj1[RSM.RSM_TagID.TAG_CCD_LABEL] = "tesrOverrideLabel"
--obj1[RSM.RSM_TagID.TAG_BUS_LABEL] = "TESTdlms" 

obj2.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj2[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj2[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj2[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan1 Output"

obj3.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj3[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj3[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj3[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan2 Output"

obj4.objid = RSM.RSM_TagID.TAG_CCD_AC
obj4[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj4[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj4[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput1"

obj5.objid = RSM.RSM_TagID.TAG_CCD_AC
obj5[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj5[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 2
obj5[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput2"

obj13.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj13[RSM.RSM_TagID.TAG_CCD_FILENAME] = "testccd.xml"
obj13[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj13[RSM.RSM_TagID.TAG_CCD_LABEL] = "Test1 Output2"

--Add new profile
obj6.objid = RSM.RSM_TagID.TAG_CCD_CFG
obj6[RSM.RSM_TagID.TAG_CCD_FILENAME] = ""
obj6[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestNewProfile"
obj6[RSM.RSM_TagID.TAG_CCD_TEMP] = 20
obj6[RSM.RSM_TagID.TAG_CCD_RANGE] = 0
obj6[RSM.RSM_TagID.TAG_CCD_INTERNAL] = "Test Internal_new"
obj6[RSM.RSM_TagID.TAG_CCD_EXTERNAL] = "Test External_new"
obj6[RSM.RSM_TagID.TAG_CCD_ACMONITOR] = "Test ACmonitor_new"
obj6[RSM.RSM_TagID.TAG_CCD_DELTA] = 0
obj6[RSM.RSM_TagID.TAG_CCD_FAN_TYPE] = 0

obj7.objid = RSM.RSM_TagID.TAG_CCD_OVERRIDE
obj7[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj7[RSM.RSM_TagID.TAG_CCD_LABEL] = "testOverrideLabel_new"

obj8.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj8[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj8[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj8[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan1 Output_new"

obj9.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj9[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj9[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj9[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan2 Output_new"

obj10.objid = RSM.RSM_TagID.TAG_CCD_FAN
obj10[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj10[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 0
obj10[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestFan1 Output2_new"

obj11.objid = RSM.RSM_TagID.TAG_CCD_AC
obj11[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj11[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 1
obj11[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput1_new"

obj12.objid = RSM.RSM_TagID.TAG_CCD_AC
obj12[RSM.RSM_TagID.TAG_CCD_FILENAME] = "TestNewProfile.xml"
obj12[RSM.RSM_TagID.TAG_CCD_PRIORITY] = 2
obj12[RSM.RSM_TagID.TAG_CCD_LABEL] = "TestACOutput2_new"


--testCfg[0] = obj
--testCfg[1] = obj1
--testCfg[0] = obj2
--testCfg[1] = obj3
--testCfg[4] = obj4
--testCfg[5] = obj5

--testCfg[6] = obj6
--testCfg[7] = obj7
--testCfg[8] = obj8
--testCfg[9] = obj9
--testCfg[10] = obj10
--testCfg[11] = obj11
--testCfg[12] = obj12
--testCfg[2] = obj13

--setConfig(testCfg)





























