First implementation, messy but maybe works