Fixed major problems in this script and added additional debugging output.