Initial version, based on erikcas work