a lot of stuff converted from python to perl