Index: trunk/Mars/mcore/fits.h
===================================================================
--- trunk/Mars/mcore/fits.h	(revision 15278)
+++ trunk/Mars/mcore/fits.h	(revision 15364)
@@ -17,4 +17,5 @@
 #include <map>
 #include <string>
+#include <fstream>
 #include <sstream>
 #include <algorithm>
@@ -420,4 +421,6 @@
 
 private:
+    ofstream fCopy;
+
     Table fTable;
 
@@ -497,6 +500,5 @@
     }
 
-public:
-    fits(const string &fname, bool force=false) : izstream(fname.c_str())
+    void Constructor(const string &fname, string fout, bool force)
     {
         char simple[10];
@@ -595,4 +597,52 @@
             }
         }
+
+        if (fout.empty())
+            return;
+
+        if (*fout.rbegin()=='/')
+        {
+            const size_t p = fname.find_last_of('/');
+            fout.append(fname.substr(p+1));
+        }
+
+        fCopy.open(fout);
+        if (!fCopy)
+        {
+            clear(rdstate()|ios::badbit);
+#ifdef __EXCEPTIONS
+            throw runtime_error("Could not open output file.");
+#else
+            gLog << ___err___ << "ERROR - Failed to open output file." << endl;
+#endif
+        }
+
+        const streampos p = tellg();
+        seekg(0);
+
+        vector<char> buf(p);
+        read(buf.data(), p);
+
+        fCopy.write(buf.data(), p);
+        if (!fCopy)
+            clear(rdstate()|ios::badbit);
+    }
+
+public:
+    fits(const string &fname, bool force=false) : izstream(fname.c_str())
+    {
+        Constructor(fname, "", force);
+    }
+
+    fits(const string &fname, const string &fout, bool force=false) : izstream(fname.c_str())
+    {
+        Constructor(fname, fout, force);
+    }
+
+    ~fits()
+    {
+        copy(istreambuf_iterator<char>(*this),
+             istreambuf_iterator<char>(),
+             ostreambuf_iterator<char>(fCopy));
     }
 
@@ -625,5 +675,14 @@
 
         if (row==fRow+1)
+        {
             fChkData.add(fBufferRow);
+            if (fCopy.is_open() && fCopy.good())
+                fCopy.write(fBufferRow.data()+offset, fTable.bytes_per_row);
+            if (!fCopy)
+                clear(rdstate()|ios::badbit);
+        }
+        else
+            if (fCopy.is_open())
+                clear(rdstate()|ios::badbit);
 
         fRow = row;
