Cleaned code. Static variables moved into the function.