rewrite logic in maes.c