bug fixes, made script more flexible