fixed compilation on gcc, tweaked and further cleaned up the code.