Cleaned up tm function