original version of script
fixed closing of groups