local cps,
      tableutil,
      harel,
      hareltableparser
	  = ...
      
local process

function process(continuation, root, fileName, parent, fileParent, parentId)
    parentId = parentId or {}

	-- if fileParent then print(harel.getQualifiedName(fileParent)) end
	return json.load(
		function(data, error)
			if not data then
				print(fileName..":\n"..error)
				return continuation()
			end

			local stateTable, builtStates, error = hareltableparser.parse(root, fileName, parent, fileParent, data)
			if not stateTable then
				print(fileName..":\n"..error)
				return continuation()
			else
				-- filter output states
				if fileParent and fileParent.outputs then
					for k in pairs(fileParent.outputs) do builtStates[k] = nil end
				end

				return cps.parallelApply(
											nil,
											continuation,
											function(_, c, _, v)
                                                
												if v.type == "external" then
                                                    if v.external == v then
                                                        local id = tableutil.shallowcopy(parentId)
                                                        id[#id + 1] = v.fileOrder
                                                    
                                                        return process(c, root, v.file, v.parent, v, id)
                                                    else
                                                        -- input states are ignored as they are simply additional entry points
                                                        return c()
                                                    end
												else
                                                    print(harel.getQualifiedName(v).." ")
                                                    for _, v in ipairs(parentId) do
                                                        print(v)
                                                        print(",")
                                                    end
                                                    
                                                    print(v.fileOrder)
                                                    print("\n")
                                                    
													return c()
												end
											end,
											pairs(builtStates)
										)
			end
		end,
		fileName)
end

local function run(continuation, exeName, fileName)
    if not fileName then
        print("usage: "..exeName.." fileName")
        return continuation()
    else
        return process(continuation, getpath(fileName), fileName)
    end
end

return run
