-#if defined(_MSC_VER)
- struct _timeb t;
- _ftime(&t);
- return int(t.time * 1000 + t.millitm);
-#else
- struct timeval t;
- gettimeofday(&t, NULL);
- return t.tv_sec * 1000 + t.tv_usec / 1000;
-#endif
-}
+ Logger() : in(cin.rdbuf(), file), out(cout.rdbuf(), file) {}
+ ~Logger() { start(false); }
+
+ struct Tie: public streambuf { // MSVC requires splitted streambuf for cin and cout
+
+ Tie(streambuf* b, ofstream& f) : buf(b), file(f) {}
+
+ int sync() { return file.rdbuf()->pubsync(), buf->pubsync(); }
+ int overflow(int c) { return log(buf->sputc((char)c), "<< "); }
+ int underflow() { return buf->sgetc(); }
+ int uflow() { return log(buf->sbumpc(), ">> "); }
+
+ int log(int c, const char* prefix) {
+
+ static int last = '\n';
+
+ if (last == '\n')
+ file.rdbuf()->sputn(prefix, 3);
+
+ return last = file.rdbuf()->sputc((char)c);
+ }
+
+ streambuf* buf;
+ ofstream& file;
+ };
+
+ ofstream file;
+ Tie in, out;
+
+public:
+ static void start(bool b) {
+
+ static Logger l;
+
+ if (b && !l.file.is_open())
+ {
+ l.file.open("io_log.txt", ifstream::out | ifstream::app);
+ cin.rdbuf(&l.in);
+ cout.rdbuf(&l.out);
+ }
+ else if (!b && l.file.is_open())
+ {
+ cout.rdbuf(l.out.buf);
+ cin.rdbuf(l.in.buf);
+ l.file.close();
+ }
+ }
+};
+
+
+/// Trampoline helper to avoid moving Logger to misc.h
+void start_logger(bool b) { Logger::start(b); }