working script, partially debugged