Rewritten whole code with prototypes