#!lua
-- GCW March 2021
--[=[
This program consists of four chunks:
    'read item', 'check', 'get targets',  'main loop'
Each has comments 'uses', 'exports'.
 'uses' lists variables in the chunk previously defined as local
   or built-in.
 'exports' lists variables defined in the chunk, as local,
    to be used by subsequent chunks.
Other names in the chunk are either built-in or local to
the chunk and not used elsewhere.
Variable names should be distinguished from syntax words:
   local, in, do, for, if, then, true, not, end
built-in names:
  riscos, os, arg, io, print  (globals)
  format, upper, match (in the string library)
and built-in operators:
 ==, :, \, =>, .., >
The only globals are riscos, os, io, arg, print.
--]=]

-- read item ---------------------------[
-- exports filetype, dir, getenv, execute, infile, leaf
local filetype, dir in riscos
local getenv, execute in os
local read, write, lines in io
local infile = arg[1]
------------------------------------------]

-- check ---------------------------------[
-- uses dir
-- exports check
local check
do
 local ask = "%s already exists in %s\nOverwrite? (Y/N) > "
 check = \ (d, obj)
   for item, _ in dir (d) do
       if item == obj then
         write (ask:format (d, obj))
         => (read (1)):upper ( ) == "Y"
       end -- if
   end -- for
   => true
 end -- function
end -----------------------------------------]

-- get targets --------------------------[
-- uses getenv
-- exports targetfile
local targetfile
do
 local here = getenv "multisave$dir"
 targetfile = here .. ".targets"
end ----------------------------------------]

-- main loop ------------------------------[
-- uses targetfile, filetype, check, execute
local moan = "%s is not a directory or an application"
local dot = "%s.%s"
local copy_cmd = "copy %s %s ~CQ~V"
local leaf = assert (infile:match ("[^%.%s]+$"))
for target in lines (targetfile) do
    if not target:match "^#" then  -- comment maybe
       assert (filetype (target) > 0xfff, moan:format (target))
       if check (target, leaf) then
          local outfile = dot:format (target, leaf)
           execute (copy_cmd:format (infile, outfile))
       end -- if
    end -- if
end -- for
print "======= multisave finished ========"
-------------------------------------------]