Migrated to functions, bugfixes