Applied comments and increased error checking a bit. Should be the final version.