fixed several issues, improved logic in some places