Fixed legend generation bug. Changed where legend gets output.