updated implementation, rearranged some logic as lifo/fifo wasnt working