wd = pwd ();
files = {"scripta.m", "scripta", "scriptb.m", ...
         "scriptc", "scriptd.sd.m", "scriptd.sd"};
pathadded = false;

unwind_protect
  cd (tempdir)
  for ii = 1:numel (files)
    id = fopen (files{ii}, "w+");
    fprintf (id, "fname = ""%s""; ", files{ii});
    fprintf (id, "fname = fullfile (fileparts (mfilename (\"fullpath\")), fname); ", files{ii});
    fprintf (id, "execdir = pwd ();");
    fclose (id);
  endfor
  
  if (! exist ("foo", "dir"))
    mkdir (foo);
  endif
  for ii = 1:numel (files)
    copyfile (files{ii}, fullfile ("foo", files{ii}), "f");
  endfor
  

  
  ## prefer .m extensions
  run ("scripta.m")
  assert (fname, fullfile (tempdir(), "scripta.m"))
  assert (execdir, pwd ())
  run ("scripta")
  assert (fname, fullfile (tempdir(), "scripta.m"))
  assert (execdir, pwd ())
  
  run ("./foo/scripta.m")
  assert (fname, fullfile (tempdir(), "foo", "scripta.m"))
  assert (execdir, [pwd() filesep() "foo"])
  run ("./foo/scripta")
  assert (fname, fullfile (tempdir(), "foo", "scripta.m"))
  assert (execdir, [pwd() filesep() "foo"])

  
  delete ("./scriptb.m")
  addpath ([pwd() filesep() "foo"])
  pathadded = true;

  ## script in the path
  run ("scriptb")
  assert (fname, fullfile (tempdir(), "foo", "scriptb.m"))
  assert (execdir, pwd ())

  ## no .m counterpart
  run ("scriptc")
  assert (fname, fullfile (tempdir(), "scriptc"))
  assert (execdir, pwd ())
  
  delete ("scriptc")

  run ("scriptc")
  assert (fname, fullfile (tempdir(), "foo", "scriptc"))
  assert (execdir, pwd ())
  run ("./foo/scriptc")
  assert (fname, fullfile (tempdir(), "foo", "scriptc"))
  assert (execdir, [pwd() filesep() "foo"])

  ## scripts with weird extensions
  run ("scriptd.sd")
  assert (fname, fullfile (tempdir(), "scriptd.sd.m"))
  assert (execdir, pwd ())
  run ("scriptd.sd.m")
  assert (fname, fullfile (tempdir(), "scriptd.sd.m"))
  assert (execdir, pwd ())
  
  delete ("scriptd.sd");
  delete ("scriptd.sd.m");
  addpath ([pwd() filesep() "foo"]) # for update
  run ("scriptd.sd")
  assert (fname, fullfile (tempdir(), "foo", "scriptd.sd.m"))
  assert (execdir, pwd ())
  run ("scriptd.sd.m")

  
unwind_protect_cleanup
  if (pathadded)
    rmpath ([pwd() filesep() "foo"])
  endif
  
  cd (wd);
end_unwind_protect
