#include <iostream>
#include <windows.h>
#include "str.h"
#include "file.h"

using namespace std;
using namespace io_tools;

#ifndef NO_MAIN
inline
bool file_exists(const string & ff) 
{
   File file(ff);
   return file.is_file();
}
inline
bool dir_exists(const string & ff) 
{
   File file(ff);
   return file.is_directory();
}
#else
extern bool file_exists(const string & ff);
extern bool dir_exists(const string & ff);
#endif

#ifdef NO_MAIN
extern "C" {
extern int mv_main(int argc, char ** argv);
}
int mv_main(int argc, char ** argv)
#else 
int main(int argc, char ** argv)
#endif
{
   int rc = 0;
   if(argc == 3) {
      File src(argv[1]);
      File dst(argv[2]);
      if(src.is_file() && !dst.is_directory()) {
         if(DeleteFile(argv[2]) != FALSE) {
            cerr << "error..." << endl;
            rc = 1;
         }
      }
      if(!rc)
      if(!src.is_file() && !dst.is_directory()) {
         cerr << "not found..." << endl;
         rc = 1;
      }
      else {
         if(src.is_file() && dst.is_directory()) {
            if(CopyFile(src.get_full_path().c_str(), (string(argv[2]) + string("\\") + string(argv[1])).c_str(), FALSE) != FALSE) {
               if(DeleteFile(src.get_full_path().c_str()) != FALSE) {
                  rc = 0;
               }
               else {
                  cerr << "error..." << endl;
                  rc = 1;
               }
            }
            else {
               cerr << "error..." << endl;
               rc = 1;
            }
         }
         else if(src.is_directory() && dst.is_directory()) {
            string temp = string(argv[2]) + "\\" + string(argv[1]);
            if(MoveFile(argv[1], temp.c_str()) != FALSE) {
               rc = 0;
            }
            else {
               cerr << "error..." << endl;
               rc = 1;
            }
         }
         else if(MoveFile(argv[1], argv[2]) != FALSE) {
            rc = 0;
         }
         else {
            cerr << "error..." << endl;
            rc = 1;
         }
      }
   }
   else {
      cerr << "usage: mv <source> <dest>" << endl;
      rc = 1;
   }
   return rc;
}  
