# HG changeset patch
# User Markus Mützel <markus.muetzel@gmx.de>
# Date 1500063698 -7200
#      Fri Jul 14 22:21:38 2017 +0200
# Node ID c397640332826cfb4dd4b0a7b966652e54c07f31
# Parent  d90c36bbd09f81b355c3a975551263c0a0f10f27
Unzipped content instead of actual xlsx file in destination path (bug #51203).

__OCT_spsh_open__.m: Call InfoZip directly instead of unpack. Return to
original working directory on errors. Always set output arguments.

__OCT_spsh_close__.m: Zip and move/rename in two steps. Return to original
working directory on errors.

diff -r d90c36bbd09f -r c39764033282 inst/private/__OCT_spsh_close__.m
--- a/inst/private/__OCT_spsh_close__.m	Tue May 16 23:15:14 2017 +0200
+++ b/inst/private/__OCT_spsh_close__.m	Fri Jul 14 22:21:38 2017 +0200
@@ -44,18 +44,35 @@
     if (xls.changed && xls.changed < 3)
       ## Go to temp dir where ods file has been unzipped
       cd (xls.workbook);
-            pause (0.05);
+
       ## Zip tmp directory into .ods or .xlsx and copy it over original file
       try
-        [stts, op] = system (sprintf ('zip -q -r "%s" *.* .', filename));
-        pause (0.20);
+        if exist (fullfile (xls.workbook, [fname ".zip"]), "file")
+          delete (fullfile (xls.workbook, [fname ".zip"]));
+        endif
+        [stts, op] = system (sprintf ('zip -q -r "%s" *', [fname ".zip"]));
+
         if (stts == 0)
+          ## Move file from temp folder and rename
+          [mvst, msg] = movefile (["." filesep fname ".zip"], filename, "f");
+          if ~mvst
+            warning ('Moving file "%s" to "%s" failed with meassage: "%s"', ...
+                     fullfile (xls.workbook, [fname ".zip"]), filename, msg);
+          endif
           xls.changed = 0;
+        else
+          warning ("Zipping xlsx-file failed with with error %d\nOutput:\n%s\n", stts, op);
         endif
-      catch
+      catch err
         printf ("odsclose: could not zip ods contents in %s to %s\n", ...
                 xls.workbook, filename);
-      end_try_catch;
+        disp (err.message)
+        disp (err.stack)
+        cd (opwd);
+      end_try_catch
+
+      ## Return to work dir
+      cd (opwd);
     endif
 
   elseif (strcmpi (xls.filename(end-8:end), ".gnumeric"))
@@ -77,8 +94,7 @@
     endif
   endif
 
-  ## Delete tmp file and return to work dir
-  cd (opwd);
+  ## Delete tmp file
   if (! xls.changed)
     ## Below is needed for a silent delete of our tmpdir
     confirm_recursive_rmdir (0, "local");
diff -r d90c36bbd09f -r c39764033282 inst/private/__OCT_spsh_open__.m
--- a/inst/private/__OCT_spsh_open__.m	Tue May 16 23:15:14 2017 +0200
+++ b/inst/private/__OCT_spsh_open__.m	Fri Jul 14 22:21:38 2017 +0200
@@ -27,6 +27,9 @@
 
 function [ xls, xlssupport, lastintf] = __OCT_spsh_open__ (xls, xwrite, filename, xlssupport, ftype)
 
+  ## default output (on error)
+  lastintf = "";
+
   ## Open and unzip file to temp location (code by Markus Bergholz)
   ## create current work folder
   tmpdir = tmpnam;
@@ -58,12 +61,19 @@
   else
     ## xlsx and ods are zipped
     try
-      unpack (templ, tmpdir, "unzip");
-      ## Allow unpack dust to settle down (lazy write file I/O)
-      pause (0.2);
-    catch
+      t_unpack = tic;
+      ## FIXME: Use "unpack" instead of system ("unzip...") when it is fixed:
+      ##        unpack (templ, tmpdir, "unzip");
+      [stts, op] = system (sprintf ('unzip -o "%s" -d %s', templ, tmpdir));
+      if (stts != 0)
+        warning ("UnZip failed with error %d\nOutput:\n%s\n", stts, op);
+      endif
+    catch err
       printf ("file %s couldn't be unpacked. Is it the proper file format?\n", filename);
+      disp (err.message)
+      disp (err.stack)
       xls = [];
+      cd (opwd);
       return
     end_try_catch
   endif
@@ -83,39 +93,38 @@
       warning ("xls2open: file %s couldn't be unzipped\n", filename);
       xls = [];
       return
-    else
-      ## Fill xlsx pointer 
-      xls.workbook          = tmpdir;       # subdir containing content.xml
-      xls.xtype             = "OCT";        # OCT is fall-back interface
-      xls.app               = 'xlsx';       # must NOT be an empty string!
-      xls.filename = filename;              # spreadsheet filename
-      xls.changed = 0;                      # Dummy
+    endif
 
-      ## Get content.xml
-      xml = fread (fid, "char=>char").';
-      ## Close file
-      fclose (fid);
+    ## Fill xlsx pointer 
+    xls.workbook          = tmpdir;       # subdir containing content.xml
+    xls.xtype             = "OCT";        # OCT is fall-back interface
+    xls.app               = 'xlsx';       # must NOT be an empty string!
+    xls.filename = filename;              # spreadsheet filename
+    xls.changed = 0;                      # Dummy
+
+    ## Get content.xml
+    xml = fread (fid, "char=>char").';
+    ## Close file
+    fclose (fid);
 
-      ## Get sheet names and indices
-      sheets = getxmlnode (xml, "sheets", [], 1);
-      xls.sheets.sh_names = cell2mat (regexp (sheets, '<sheet name="(.*?)"', "tokens"));
-      xls.sheets.rid = str2double (cell2mat (regexp (sheets, ' r:id="rId(\d+)"', "tokens")));
-      xls.sheets.sheetid = str2double (cell2mat (regexp (sheets, ' sheetId="(\d+)"', "tokens")));
-      
-      ## read worksheet.xml.rels
-      fid = fopen (sprintf ("%s/xl/_rels/workbook.xml.rels", tmpdir));
-      if (fid > 0)
-        str = fread (fid, "char=>char").';
-        fclose (fid);
-        xls.sheets.rels = ...
-         regexp (str, ['<Relationship Id="rId(\d+)" ' ...
-                       'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" ' ...
-                       'Target="worksheets/sheet(\d+).xml"[^/>]*/>'], "tokens");
-        xls.sheets.rels = reshape (str2double (cell2mat (xls.sheets.rels)), [], columns(xls.sheets.rels))';
-      else
-        xls.sheets.rels = reshape([xls.sheets.rid xls.sheets.rid], [], columns (xls.sheets.rid));
-      endif
+    ## Get sheet names and indices
+    sheets = getxmlnode (xml, "sheets", [], 1);
+    xls.sheets.sh_names = cell2mat (regexp (sheets, '<sheet name="(.*?)"', "tokens"));
+    xls.sheets.rid = str2double (cell2mat (regexp (sheets, ' r:id="rId(\d+)"', "tokens")));
+    xls.sheets.sheetid = str2double (cell2mat (regexp (sheets, ' sheetId="(\d+)"', "tokens")));
 
+    ## read worksheet.xml.rels
+    fid = fopen (sprintf ("%s/xl/_rels/workbook.xml.rels", tmpdir));
+    if (fid > 0)
+      str = fread (fid, "char=>char").';
+      fclose (fid);
+      xls.sheets.rels = ...
+        regexp (str, ['<Relationship Id="rId(\d+)" ' ...
+                      'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" ' ...
+                      'Target="worksheets/sheet(\d+).xml"[^/>]*/>'], "tokens");
+      xls.sheets.rels = reshape (str2double (cell2mat (xls.sheets.rels)), [], columns(xls.sheets.rels))';
+    else
+      xls.sheets.rels = reshape([xls.sheets.rid xls.sheets.rid], [], columns (xls.sheets.rid));
     endif
 
   elseif (ftype == 3)
