Cowdenbeath secured their First Division status after coming from behind to defeat Hamilton 3-1 at New Douglas Park.