# Description: Apply SPE improvements to main.py.
#  The SPE (Stani's Python Editor) folks have made some minor improvements to
#  pychecker2/main.py, to make it handle errors better and make it more
#  flexible. The changes are straightforward and look safe to me.  Since SPE is
#  already using them this implies that they work properly.
# Bug-Debian: http://bugs.debian.org/453092
# Forwarded: http://sourceforge.net/tracker/?func=detail&aid=1845213&group_id=24686&atid=382219
# Author: SPE (Stani's Python Editor), http://pythonide.stani.be
# Reviewed-By: Kenneth J. Pronovici <pronovic@debian.org>
--- a/pychecker2/main.py
+++ b/pychecker2/main.py
@@ -1,5 +1,28 @@
 import sys
 from os.path import dirname, realpath
+import os
+
+def userPath(dirname=''):
+    """'safer' function to find user path."""
+    # 'safer' function to find user path: look for one of these directories
+    try:
+        path = os.path.expanduser("~")
+        if os.path.isdir(path):
+            return os.path.join(path, dirname)
+    except:
+        pass
+    for evar in ('HOME', 'USERPROFILE', 'TMP'):
+        try:
+            path = os.environ[evar]
+            if os.path.isdir(path):
+                return os.path.join(path, dirname)
+        except:
+            pass
+    #if no match found, use module directory
+    return os.path.join(os.path.dirname(os.path.abspath(__file__)), dirname)
+
+CACHE_FILE = userPath(".pychecker_cache")
+
 sys.path.append(dirname(dirname(realpath(sys.argv[0]))))
 
 from pychecker2.Check import CheckList
@@ -16,8 +39,6 @@
 from pychecker2 import ConditionalChecks
 from pychecker2 import FormatStringChecks
 
-CACHE_FILE = '/tmp/t'
-
 def print_warnings(f, out):
     if not f.warnings:
         return 0
@@ -69,7 +90,7 @@
     options = Options.Options()
     try:
         checker = cPickle.load(open(CACHE_FILE, 'rb'))
-    except (EOFError, IOError):
+    except (EOFError, IOError, ImportError):
         checker = create_checklist(options)
 
     try:
@@ -79,10 +100,17 @@
         options.usage(sys.argv[0], sys.stderr)
         return 1
 
+    # Properly load local modules relative to the file which is being checked
+    sys_path = sys.path[:]
     for f in files:
+        f_dir = dirname(f.name)
+        sys.path= sys_path[:]
+        if f_dir not in sys.path:
+            sys.path.insert(0,f_dir)
         checker.check_file(f)
         if options.incremental and not options.profile:
             print_warnings(f, sys.stdout)
+    sys.path = sys_path
 
     result = 0
     if not options.incremental and not options.profile:
