fixed a bug and simplified the code a bit.