Fix a bunch of stuff, improve performance

Signed-off-by: Andrew Tselischev <andrewtselischev@gmail.com>