From what I understand you want memory that won’t be erased every time the Arduino is off. Do some research into EEPROM.
In terms of debugging, the code you have there is a bit difficult to read. Try inserting statements which print the value of a certain variable as the program progresses and see where it goes wrong.
Best of luck! Tell us what happens.