modified version, makes beter use of stack - still crashes on error