Fix write algorithm