Initial, messy version, works more or less for simple cases