updated and slightly debugged